file_path
stringlengths
21
207
content
stringlengths
5
1.02M
size
int64
5
1.02M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.27
0.93
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_commands.py
import omni.kit.commands import omni.kit.tagging import omni.client class AddTagCommand(omni.kit.commands.Command): """ Add a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 excluded (str): excluded version of the tag (or empty string) to remove if present """ def __init__(self, asset_path: str, tag: str, excluded: str = ""): self._asset_path = asset_path self._tag = tag self._excluded = excluded def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="add") if self._excluded: tagging.tags_action(self._asset_path, self._excluded, action="remove") def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="remove") if self._excluded: tagging.tags_action(self._asset_path, self._excluded, action="add") class RemoveTagCommand(omni.kit.commands.Command): """ Remove a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 """ def __init__(self, asset_path: str, tag: str): self._asset_path = asset_path self._tag = tag def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="remove") def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, self._tag, action="add") class UpdateTagCommand(omni.kit.commands.Command): """ Remove a tag to an asset **Command**. Fails if we are not connected to the tagging server. Args: asset_path (str): Path to the asset. Should start with omniverse: or it will just return old_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 new_tag (str): packed string tag, such as appearance.Car, or .appearance.generated.Truck=99 """ def __init__(self, asset_path: str, old_tag: str, new_tag): self._asset_path = asset_path self._old_tag = old_tag self._new_tag = new_tag def do(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, old_tag=self._old_tag, action="update", new_tag=self._new_tag) def undo(self): broken_url = omni.client.break_url(self._asset_path) if broken_url.scheme != "omniverse": return tagging = omni.kit.tagging.get_tagging_instance() tagging.tags_action(self._asset_path, old_tag=self._new_tag, action="update", new_tag=self._old_tag) omni.kit.commands.register_all_commands_in_module(__name__)
3,827
Python
36.529411
108
0.634962
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/__init__.py
from .tagging_properties import * from .tagging_commands import *
66
Python
21.333326
33
0.787879
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/scripts/tagging_properties.py
import os import carb import omni.ext from pxr import Sdf, UsdShade from pathlib import Path from .style import UI_STYLES class TaggingPropertyExtension(omni.ext.IExt): def __init__(self): self._registered = False self._icon_path = "" super().__init__() def on_startup(self, ext_id): manager = omni.kit.app.get_app().get_extension_manager() extension_path = manager.get_extension_path(ext_id) self._icon_path = Path(extension_path).joinpath("data").joinpath("icons") self._hooks = manager.subscribe_to_extension_enable( on_enable_fn=lambda _: self._register_widget(), on_disable_fn=lambda _: self._unregister_widget(), ext_name="omni.kit.window.property", hook_name="omni.kit.window.property listener", ) def destroy(self): if self._registered: self._unregister_widget() def on_shutdown(self): self._hooks = None if self._registered: self._unregister_widget() def _register_widget(self): theme = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" style = UI_STYLES[theme] # update icon paths style["check"]["image_url"] = str(self._icon_path.joinpath("check.svg")) style["remove"]["image_url"] = str(self._icon_path.joinpath("remove.svg")) style["plus"]["image_url"] = str(self._icon_path.joinpath("plus.svg")) try: import omni.kit.window.property as p from .tagging_attributes_widget import TaggingAttributesWidget w = p.get_window() if w: w.register_widget("prim", "tagging", TaggingAttributesWidget(style)) self._registered = True except Exception as exc: carb.log_error(f"Error registering tagging widget {exc}") def _unregister_widget(self): try: import omni.kit.window.property as p w = p.get_window() if w: w.unregister_widget("prim", "tagging") self._registered = False except Exception as e: carb.log_warn(f"Unable to unregister 'tagging:/attributes': {e}")
2,256
Python
33.723076
108
0.595301
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/test_tagging.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. ## import pathlib import omni.kit.app import omni.kit.commands import omni.kit.test import omni.ui as ui from omni.kit import ui_test from omni.ui.tests.test_base import OmniUiTest from pxr import Kind, Sdf, Gf class TestTaggingWidget(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() ext_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = pathlib.Path(ext_path).joinpath("data/tests/golden_img") from omni.kit.property.usd.usd_attribute_widget import UsdPropertiesWidget import omni.kit.window.property as p self._w = p.get_window() # After running each test async def tearDown(self): await super().tearDown() # Test(s) async def test_tagging_ui(self): usd_context = omni.usd.get_context() await self.docked_test_window( window=self._w._window, width=450, height=250, restore_window = ui.Workspace.get_window("Layer") or ui.Workspace.get_window("Stage"), restore_position = ui.DockPosition.BOTTOM) # new stage await omni.usd.get_context().new_stage_async() stage = omni.usd.get_context().get_stage() ## create prim omni.kit.commands.execute("CreatePrimWithDefaultXform", prim_type="Sphere") # verify one prim prim_list = [prim.GetPath().pathString for prim in stage.TraverseAll() if prim.GetPath().pathString not in ['/Render', '/Render/Vars']] self.assertTrue(prim_list == ['/Sphere']) # Select the prim. usd_context.get_selection().set_selected_prim_paths(["/Sphere"], True) # Need to wait for an additional frames for omni.ui rebuild to take effect await ui_test.human_delay(10) # verify image await self.finalize_test(golden_img_dir=self._golden_img_dir, golden_img_name="test_tagging_ui.png")
2,414
Python
35.590909
143
0.676056
omniverse-code/kit/exts/omni.kit.property.tagging/omni/kit/property/tagging/tests/__init__.py
from .test_tagging import *
28
Python
13.499993
27
0.75
omniverse-code/kit/exts/omni.kit.property.tagging/docs/index.rst
omni.kit.property.tagging ########################### Property Tagging Values .. toctree:: :maxdepth: 1 CHANGELOG
125
reStructuredText
9.499999
27
0.544
omniverse-code/kit/exts/omni.example.ui/PACKAGE-LICENSES/omni.example.ui-LICENSE.md
Copyright (c) 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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.example.ui/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.2.3" # Lists people or organizations that are considered the "authors" of the package. authors = ["NVIDIA"] # The title and description fields are primarly for displaying extension info in UI title = "Omni UI Documentation" description="Examples for using omni.ui library" category = "Example" # URL of the extension source repository. repository = "" # Keywords for the extension keywords = ["kit", "example", "ui"] changelog="docs/CHANGELOG.md" [ui] name = "Omni UI Documentation" [dependencies] "omni.kit.commands" = {} "omni.kit.documentation.builder" = {} "omni.ui" = {} "omni.usd" = {} [[python.module]] name = "omni.example.ui" [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--/app/menu/legacy_mode=false", # needed for golden images to match "--no-window", ] dependencies = [ "omni.kit.mainwindow", "omni.kit.renderer.capture", ]
995
TOML
20.652173
83
0.687437
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/extension.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. # """The documentation of the omni.ui aka UI Framework""" from .scripts.ui_doc import UIDoc from functools import partial import asyncio import carb import carb.settings import omni.ext import omni.kit.app import omni.ui as ui EXTENSION_NAME = "Omni.UI Documentation" class ExampleExtension(omni.ext.IExt): """The Demo extension""" WINDOW_NAME = "Omni::UI Doc" _ui_doc = None def __init__(self): super().__init__() @staticmethod def ui_doc(): return ExampleExtension._ui_doc def get_name(self): """Return the name of the extension""" return EXTENSION_NAME def on_startup(self, ext_id): """Caled to load the extension""" extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path(ext_id) ExampleExtension._ui_doc = UIDoc(extension_path) ui.Workspace.set_show_window_fn( ExampleExtension.WINDOW_NAME, lambda show: show and ExampleExtension._ui_doc.build_window(ExampleExtension.WINDOW_NAME), ) ui.Workspace.show_window(ExampleExtension.WINDOW_NAME) # Dock this extension into mainwindow if running as standalone settings = carb.settings.get_settings() standalone_mode = settings.get_as_bool("app/settings/standalone_mode") if standalone_mode: asyncio.ensure_future(self._dock_window(ExampleExtension.WINDOW_NAME, omni.ui.DockPosition.SAME)) def on_shutdown(self): """Called when the extesion us unloaded""" ExampleExtension._ui_doc.shutdown() ExampleExtension._ui_doc = None ui.Workspace.set_show_window_fn(ExampleExtension.WINDOW_NAME, None) async def _dock_window(self, window_title: str, position: omni.ui.DockPosition, ratio: float = 1.0): frames = 3 while frames > 0: if omni.ui.Workspace.get_window(window_title): break frames = frames - 1 await omni.kit.app.get_app().next_update_async() window = omni.ui.Workspace.get_window(window_title) dockspace = omni.ui.Workspace.get_window("DockSpace") if window and dockspace: window.dock_in(dockspace, position, ratio=ratio) window.dock_tab_bar_visible = False
2,717
Python
33.405063
109
0.676849
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/__init__.py
# NOTE: all imported classes must have different class names from .extension import *
86
Python
27.999991
60
0.790698
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/ui_doc.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. # """The documentation of the omni.ui aka UI Framework""" from .abstract_model_doc import AbstractModelDoc from .attribute_editor_demo import AttributeEditorWindow from .canvas_frame_doc import CanvasFrameDoc from .checkbox_doc import CheckBoxDoc from .colorwidget_doc import ColorWidgetDoc from .combobox_doc import ComboBoxDoc from .custom_window_example import BrickSunStudyWindow from .dnd_doc import DNDDoc from .doc_page import DocPage from .field_doc import FieldDoc from .image_doc import ImageDoc from .layout_doc import LayoutDoc from .length_doc import LengthDoc from .md_doc import MdDoc from .menu_bar_doc import MenuBarDoc from .menu_doc import MenuDoc from .multifield_doc import MultiFieldDoc from .plot_doc import PlotDoc from .progressbar_doc import ProgressBarDoc from .scrolling_frame_doc import ScrollingFrameDoc from .shape_doc import ShapeDoc from .slider_doc import SliderDoc from .styling_doc import StylingDoc from .treeview_doc import TreeViewDoc from .widget_doc import WidgetDoc from .window_doc import WindowDoc from .workspace_doc import WorkspaceDoc from omni.kit.documentation.builder import DocumentationBuilderWindow from omni.kit.documentation.builder import DocumentationBuilderMd from omni.ui import color as cl from omni.ui import constant as fl from pathlib import Path import omni.kit.app as app import omni.ui as ui EXTENSION_NAME = "OMNI.UI Demo" SPACING = 5 CURRENT_PATH = Path(__file__).parent DOCS_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("docs") MVD_PAGES = ["overview.md", "model.md", "delegate.md"] class UIDoc(DocPage): """UI Doc Class""" def __init__(self, extension_path): super().__init__(extension_path) self.omniverse_version, _, _ = app.get_app_interface().get_build_version().partition("-") self.vertical_scrollbar_on = True self._extension_path = extension_path self._style_system = { "Button": { "background_color": 0xFFE1E1E1, "border_color": 0xFFADADAD, "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": {"color": 0xFF000000}, "Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800}, "Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0}, } self._example_windows = {} self._window_list = [["Attribute Editor", AttributeEditorWindow()], ["Custom Window", BrickSunStudyWindow()]] self._mvd_pages = [DocumentationBuilderMd(DOCS_PATH.joinpath(filename)) for filename in MVD_PAGES] self.index_list = [ ["LAYOUT"], [ "Arrangement of elements", LayoutDoc(extension_path), [ "HStack", "VStack", "ZStack", "Spacing", "Frame", "VGrid", "HGrid", "CollapsableFrame", "Placer", "Visibility", "Direction", ], ], ["Lengths", LengthDoc(extension_path), ["Pixel", "Percent", "Fraction"]], ["WIDGETS"], ["Styling", StylingDoc(extension_path), ["The Style Sheet Syntax", "Shades", "URL Shades", "Font Size"]], [ "Base Widgets", WidgetDoc(extension_path), ["Button", "RadioButton", "Label", "Tooltip", "Debug Color", "Font"], ], ["Menu", MenuDoc(extension_path), []], ["ScrollingFrame", ScrollingFrameDoc(extension_path), []], ["CanvasFrame", CanvasFrameDoc(extension_path), []], ["Image", ImageDoc(extension_path), []], ["CheckBox", CheckBoxDoc(extension_path), []], ["AbstractValueModel", AbstractModelDoc(extension_path), []], ["ComboBox", ComboBoxDoc(extension_path), []], ["ColorWidget", ColorWidgetDoc(extension_path), []], ["MultiField", MultiFieldDoc(extension_path), []], ["TreeView", TreeViewDoc(extension_path), []], [ "Shapes", ShapeDoc(extension_path), ["Rectangle", "Circle", "Triangle", "Line", "FreeRectangle", "FreeBezierCurve"], ], ["Fields", FieldDoc(extension_path), ["StringField"]], ["Sliders", SliderDoc(extension_path), ["FloatSlider", "IntSlider", "FloatDrag", "IntDrag"]], ["ProgressBar", ProgressBarDoc(extension_path), []], ["Plot", PlotDoc(extension_path), []], ["Drag and Drop", DNDDoc(extension_path), ["Minimal Example", "Styling and Tooltips"]], ] # Add .md files here self.index_list.append(["MODEL-DELEGATE-VIEW"]) for page in self._mvd_pages: catalog = page.catalog topic = catalog[0]["name"] sub_topics = [c["name"] for c in catalog[0]["children"]] self.index_list.append([topic, MdDoc(extension_path, page), sub_topics]) self.index_list += [ ["WINDOWING SYSTEM"], [ "Windows", WindowDoc(extension_path), ["Window", "ToolBar", "Multiple Modal Windows", "Overlay Other Windows", "Workspace", "Popup"], ], ["MenuBar", MenuBarDoc(extension_path), ["MenuBar"]], ["Workspace", WorkspaceDoc(extension_path), ["Controlling Windows", "Capture Layout"]], ] try: # TODO(vyudin): can we remove? import omni.kit.widget.webview webview_enabled = True except: webview_enabled = False if webview_enabled: from .web_doc import WebViewWidgetDoc web_view_widget_doc = WebViewWidgetDoc() self.index_list += [ ["WEB WIDGETS"], ["WebViewWidget", web_view_widget_doc, web_view_widget_doc.get_sections()], ] def get_style(self): cl.ui_docs_nvidia = cl("#76b900") # Content cl.ui_docs_bg = cl.white cl.ui_docs_text = cl("#1a1a1a") cl.ui_docs_h1_bg = cl.black cl.ui_docs_code_bg = cl("#eeeeee") cl.ui_docs_code_line = cl("#bbbbbb") fl.ui_docs_code_radius = 2 fl.ui_docs_text_size = 18 # Catalog cl.ui_docs_catalog_bg = cl.black cl.ui_docs_catalog_hovered = cl("#1b1f20") style = DocumentationBuilderWindow.get_style() style.update({ "Button::placed:hovered": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "CanvasFrame": {"background_color": 0xFFDDDDDD}, "Circle::blue": {"background_color": 0xFFFF1111, "border_color": 0xFF0000CC, "border_width": 2}, "Circle::default": {"background_color": 0xFF000000, "border_color": 0xFFFFFFFF, "border_width": 1}, "Circle::placed:pressed": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "Circle::red": {"background_color": 0xFF1111FF, "border_color": 0xFFFF0000, "border_width": 2}, "Image::index_h2": {"color": 0xFF484849, "image_url": f"{self._extension_path}/icons/plus.svg"}, "Image::index_h2:selected": {"color": 0xFF5D5D5D, "image_url": f"{self._extension_path}/icons/minus.svg"}, "Image::omniverse_image": {"image_url": "resources/icons/ov_logo_square.png", "margin": 5}, "Label::caption": {"color": 0xFFFFFFFF, "font_size": 22.0, "margin_width": 10, "margin_height": 4}, "Label::code": {"color": cl.ui_docs_text}, "Label::index_h1": { "color": cl.ui_docs_nvidia, "font_size": 16.0, "margin_height": 5, "margin_width": 20, }, "Label::index_h2": {"color": 0xFFD9D9D9, "font_size": 16.0, "margin_height": 5, "margin_width": 5}, "Label::index_h2:selected": {"color": 0xFF404040}, "Label::index_h3": {"color": 0xFF404040, "font_size": 16.0, "margin_height": 5, "margin_width": 30}, "Label::omniverse_version": {"font_size": 16.0, "color": 0xFF4D4D4D, "margin": 10}, "Label::section": { "color": cl.ui_docs_nvidia, "font_size": 22.0, "margin_width": 10, "margin_height": 4, }, "Label::text": {"color": cl.ui_docs_text, "font_size": fl.ui_docs_text_size}, "Line::default": {"color": 0xFF000000, "border_width": 1}, "Line::demo": {"color": 0xFF555500, "border_width": 3}, "Line::separator": {"color": 0xFF111111, "border_width": 2}, "Line::underline": {"color": 0xFF444444, "border_width": 2}, "Rectangle::caption": {"background_color": cl.ui_docs_nvidia}, "Rectangle::code": { "background_color": cl.ui_docs_code_bg, "border_color": cl.ui_docs_code_line, "border_width": 1.0, "border_radius": fl.ui_docs_code_radius, }, "Rectangle::placed:hovered": { "background_color": 0xFFFF6E00, "border_color": 0xFF111111, "border_width": 2, }, "Rectangle::section": {"background_color": cl.ui_docs_h1_bg}, "Rectangle::selection_h2": {"background_color": cl.ui_docs_catalog_bg}, "Rectangle::selection_h2:hovered": {"background_color": 0xFF4A4A4E}, "Rectangle::selection_h2:pressed": {"background_color": 0xFFB98029}, "Rectangle::selection_h2:selected": {"background_color": 0xFFFCFCFC}, "Rectangle::selection_h3": {"background_color": 0xFFE3E3E3}, "Rectangle::selection_h3:hovered": {"background_color": 0xFFD6D6D6}, "Rectangle::table": {"background_color": 0x0, "border_color": 0xFFCCCCCC, "border_width": 0.25}, "ScrollingFrame::canvas": {"background_color": cl.ui_docs_bg}, "Triangle::default": {"background_color": 0xFF00FF00, "border_color": 0xFFFFFFFF, "border_width": 1}, "Triangle::orientation": {"background_color": 0xFF444444, "border_color": 0xFFFFFFFF, "border_width": 3}, "VStack::layout": {"margin": 50}, "VStack::layout_md": {"margin": 1}, }) return style def build_window(self, title): """Caled to load the extension""" self._window = ui.Window(title, width=1000, height=600, dockPreference=ui.DockPreference.LEFT_BOTTOM) # Populate UI once the window is visible self._window.frame.set_build_fn(self.build_window_content) # Dock it to the same space where Layers is docked if ui.Workspace.get_window("Content"): self._window.deferred_dock_in("Content") def rebuild(self): """Rebuild all the content""" self._window.frame.rebuild() def build_window_content(self): global_style = self.get_style() with ui.HStack(): # Side panel with the table of contents with ui.ScrollingFrame( width=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.ZStack(height=0): ui.Rectangle(style={"background_color": 0xFF313134}) with ui.VStack(style=global_style, height=0): # Omniverse logo and version with ui.ZStack(): ui.Rectangle(style={"background_color": 0xFF000000}) with ui.VStack(style=global_style, height=0): ui.Image(height=250, alignment=ui.Alignment.CENTER, name="omniverse_image") # Cut the end of the version. It's enough to print: # "Omniverse Version: 103.0+master..." text = f"Omniverse Version: {self.omniverse_version}" if len(text) > 32: text = text[:32] + "..." ui.Label( text, alignment=ui.Alignment.CENTER, name="omniverse_version", tooltip=self.omniverse_version, # elided_text=True, content_clipping=True, ) # The table of contents with ui.VStack(): for entry in self.index_list: if len(entry) == 1: # If entry has nothing, it's a h1 title ui.Label(entry[0], name="index_h1") else: # Otherwise it's h2 title and it has h3 subtitles title = entry[0] sub_titles = entry[2] if len(entry) < 4: entry.append(None) entry.append(None) # Draw h2 title stack = ui.ZStack() entry[3] = stack with stack: ui.Rectangle( name="selection_h2", mouse_pressed_fn=lambda x, y, b, a, e=entry: self.show_a_doc(e), ) with ui.HStack(): ui.Spacer(width=10) with ui.VStack(width=0): ui.Spacer() ui.Image(name="index_h2", width=10, height=10) ui.Spacer() ui.Label(title, name="index_h2") # Draw h3 titles, they appear only if h2 is selected stack = ui.VStack(visible=False) entry[4] = stack with stack: for sub in sub_titles: with ui.ZStack(): ui.Rectangle( name="selection_h3", mouse_pressed_fn=lambda x, y, b, a, e=entry, n=sub: self.show_a_doc( e, n ), ) ui.Label(sub, name="index_h3") ui.Label("WINDOW EXAMPLES", name="index_h1") with ui.VStack(): for entry in self._window_list: with ui.ZStack(): ui.Rectangle( name="selection_h2", mouse_pressed_fn=lambda x, y, b, a, n=entry[0], w=entry[1]: self._show_a_window( n, w ), ) with ui.HStack(): ui.Spacer(width=20) ui.Label(entry[0], name="index_h2") ui.Spacer(height=10) # The document if self.vertical_scrollbar_on: vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON else: vertical_scrollbar_policy = ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF self._doc_scrolling_frame = ui.ScrollingFrame( style=global_style, name="canvas", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=vertical_scrollbar_policy, ) self._add_all_docs() def clean_entries(self): """Should be called when the extesion is reloaded to destroy the items, that can't be auto destroyed.""" for entry in self.index_list: if len(entry) > 1 and entry[1]: entry[1].clean() def shutdown(self): """Should be called when the extesion us unloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. for page in self._mvd_pages: page.destroy() self._mvd_pages = [] self.clean_entries() self._window = None def show_a_doc(self, entry, navigate_to=None): """ show a single doc """ # Unselect/uncheck everything on the side panel for index_entry in self.index_list: if len(index_entry) == 5: _, _, _, item, sub_items = index_entry item.selected = False sub_items.visible = False self.clean_entries() # Select and show the given title _, doc, _, item, sub_items = entry item.selected = True sub_items.visible = True if isinstance(doc, MdDoc): style = "layout_md" else: style = "layout" with self._doc_scrolling_frame: # The page itself with ui.VStack(height=0, spacing=20, name=style): doc.create_doc(navigate_to) if not navigate_to: # Scroll up if there is nothing to jump to because scrolling frame remembers the scrolling position of # the previous page self._doc_scrolling_frame.scroll_y = 0 def _show_a_window(self, name, window_class): """ window an example window """ if name not in self._example_windows: self._example_windows[name] = window_class.build_window() self._example_windows[name].visible = True def _add_all_docs(self): """The body of the document""" self.clean_entries() with self._doc_scrolling_frame: # The page itself with ui.VStack(height=0, spacing=20, name="layout"): self._section_title("What is Omni::UI?") self._text( "Omni::UI is Omniverse's UI toolkit for creating beautiful and flexible graphical user interfaces " "in the Kit extensions. Omni::UI provides the basic types necessary to create rich extensions with " "a fluid and dynamic user interface in Omniverse Kit. It gives a layout system and includes " "widgets for creating visual components, receiving user input, and creating data models. It allows " "user interface components to be built around their behavior and enables a declarative flavor of " "describing the layout of the application. Omni::UI gives a very flexible styling system that " "allows for deep customizing of the final look of the application." ) for entry in self.index_list: if len(entry) > 1 and entry[1] is not None: entry[1].create_doc()
20,840
Python
46.151584
120
0.518042
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/workspace_doc.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. # """The documentation for Workspaces""" from omni import ui from .doc_page import DocPage import json SPACING = 5 class WorkspaceDoc(DocPage): """document Workspace class""" def _undock(self, selection): if not selection: return for item in selection: item.window.undock() def _dock(self, left, right, position): if not left or not right: return target = right[0].window for item in left: item.window.dock_in(target, position) def _left(self, selection): if not selection: return for item in selection: item.window.position_x -= 100 def _right(self, selection): if not selection: return for item in selection: item.window.position_x += 100 def _set_visibility(self, selection, visible): if not selection: return for item in selection: if visible is not None: item.window.visible = visible else: item.window.visible = not item.window.visible def _dock_reorder(self, selection): if not selection: return docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection] for group in docking_groups: # Reverse order for i, window in enumerate(reversed(group)): window.dock_order = i def _tabs(self, selection, visible): if not selection: return for item in selection: item.window.dock_tab_bar_visible = visible def _focus(self, selection): if not selection: return for item in selection: item.window.focus() break def create_doc(self, navigate_to=None): self._section_title("Workspace") self._caption("Controlling Windows", navigate_to) class WindowItem(ui.AbstractItem): def __init__(self, window): super().__init__() # Don't keep the window because it prevents the window from closing. self._window_title = window.title self.title_model = ui.SimpleStringModel(self._window_title) self.type_model = ui.SimpleStringModel(type(window).__name__) @property def window(self): return ui.Workspace.get_window(self._window_title) class WindowModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = ui.SimpleStringModel("Windows") self.update() def update(self): self._children = [WindowItem(i) for i in ui.Workspace.get_windows()] self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._children def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item is None: return self._root if column_id == 0: return item.title_model if column_id == 1: return item.type_model self._window_model = WindowModel() self._tree_left = None self._tree_right = None with ui.VStack(style=self._style_system): ui.Button("Refresh", clicked_fn=lambda: self._window_model.update()) with ui.HStack(): ui.Button("Clear", clicked_fn=ui.Workspace.clear) ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection)) with ui.HStack(): ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True)) ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False)) ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None)) with ui.HStack(): ui.Button( "Dock Right", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT ), ) ui.Button( "Dock Left", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT ), ) ui.Button( "Dock Top", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP ), ) ui.Button( "Dock Bottom", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM ), ) ui.Button( "Dock Same", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME ), ) ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection)) with ui.HStack(): ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection)) ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection)) with ui.HStack(): ui.Button( "Reverse Docking Tabs of Neighbours", clicked_fn=lambda: self._dock_reorder(self._tree_left.selection), ) ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False)) ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True)) with ui.HStack(height=400): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) self._caption("Capture Layout", navigate_to) def generate(label): dump = ui.Workspace.dump_workspace() label.text = json.dumps(dump, sort_keys=True, indent=4) def restore(label): dump = label.text ui.Workspace.restore_workspace(json.loads(dump)) with ui.HStack(style=self._style_system): ui.Button("Generate", clicked_fn=lambda: generate(self._label)) ui.Button("Restore", clicked_fn=lambda: restore(self._label)) self._label = self._code("Press Generate to dump layout") # some padding at the bottom ui.Spacer(height=100)
8,098
Python
35.813636
120
0.551988
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_bar_doc.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. # """The documentation for the MenuBar""" from omni import ui from .doc_page import DocPage SPACING = 5 class MenuBarDoc(DocPage): """ document MenuBar classes""" def __init__(self, extension_path): super().__init__(extension_path) self._window_menu_example = None def create_and_show_window_with_menu(self): if not self._window_menu_example: self._window_menu_example = ui.Window( "Window Menu Example", width=300, height=300, flags=ui.WINDOW_FLAGS_MENU_BAR | ui.WINDOW_FLAGS_NO_BACKGROUND, ) menu_bar = self._window_menu_example.menu_bar with menu_bar: with ui.Menu("File"): ui.MenuItem("Load") ui.MenuItem("Save") ui.MenuItem("Export") with ui.Menu("Window"): ui.MenuItem("Hide") with self._window_menu_example.frame: with ui.VStack(): ui.Button("This Window has a Menu") def show_hide_menu(menubar): menubar.visible = not menubar.visible ui.Button("Click here to show/hide Menu", clicked_fn=lambda m=menu_bar: show_hide_menu(m)) def add_menu(menubar): with menubar: with ui.Menu("New Menu"): ui.MenuItem("I don't do anything") ui.Button("Add New Menu", clicked_fn=lambda m=menu_bar: add_menu(m)) self._window_menu_example.visible = True def create_doc(self, navigate_to=None): self._section_title("MenuBar") self._text( "All the Windows in Omni.UI can have a MenuBar. To add a MenuBar to your window add this flag to your " "constructor - omni.ui.Window(flags=ui.WINDOW_FLAGS_MENU_BAR). The MenuBar object can then be accessed " "through the menu_bar read-only property on your window\n" "A MenuBar is a container so it is built like a Frame or Stack but only takes Menu objects as children. " "You can leverage the 'priority' property on the Menu to order them. They will automatically be sorted " "when they are added, but if you change the priority of an item then you need to explicitly call sort()." ) self._caption("MenuBar", navigate_to) self._text("This class is used to construct a MenuBar for the Window") with ui.HStack(width=0): ui.Button("window with MenuBar Example", width=180, clicked_fn=self.create_and_show_window_with_menu) ui.Label("this populates the menuBar", name="text", width=180, style={"margin_width": 10})
3,237
Python
41.051948
117
0.599629
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/checkbox_doc.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. # """The documentation for CheckBox""" from omni import ui from .doc_page import DocPage SPACING = 5 class CheckBoxDoc(DocPage): """ document for CheckBox""" def create_doc(self, navigate_to=None): self._section_title("CheckBox") self._text( "A CheckBox is an option button that can be switched on (checked) or off (unchecked). Checkboxes are " "typically used to represent features in an application that can be enabled or disabled without affecting " "others." ) self._text( "The checkbox is implemented using the model-delegate-view pattern. The model is the central component of this " "system. It is the application's dynamic data structure independent of the widget. It directly manages the " "data, logic, and rules of the checkbox. If the model is not specified, the simple one is created " "automatically when the object is constructed." ) self._text( "In the following example, the models of two checkboxes are connected, and if one checkbox is changed, it " "makes another checkbox be changed as well." ) with ui.HStack(width=0, spacing=SPACING): # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() # Connect one to another first.model.add_value_changed_fn(lambda a, b=second: b.model.set_value(not a.get_value_as_bool())) second.model.add_value_changed_fn(lambda a, b=first: b.model.set_value(not a.get_value_as_bool())) # Set the first one to True first.model.set_value(True) self._text("One of two") self._code( """ # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() # Connect one to another first.model.add_value_changed_fn( lambda a, b=second: b.model.set_value(not a.get_value_as_bool())) second.model.add_value_changed_fn( lambda a, b=first: b.model.set_value(not a.get_value_as_bool())) """ ) self._text("In the following example, that is a bit more complicated, only one checkbox can be enabled.") with ui.HStack(width=0, spacing=SPACING): # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() third = ui.CheckBox() def like_radio(model, first, second): """Turn on the model and turn off two checkboxes""" if model.get_value_as_bool(): model.set_value(True) first.model.set_value(False) second.model.set_value(False) # Connect one to another first.model.add_value_changed_fn(lambda a, b=second, c=third: like_radio(a, b, c)) second.model.add_value_changed_fn(lambda a, b=first, c=third: like_radio(a, b, c)) third.model.add_value_changed_fn(lambda a, b=first, c=second: like_radio(a, b, c)) # Set the first one to True first.model.set_value(True) self._text("Almost like radio box") self._code( """ # Create two checkboxes first = ui.CheckBox() second = ui.CheckBox() third = ui.CheckBox() def like_radio(model, first, second): '''Turn on the model and turn off two checkboxes''' if model.get_value_as_bool(): model.set_value(True) first.model.set_value(False) second.model.set_value(False) # Connect one to another first.model.add_value_changed_fn( lambda a, b=second, c=third: like_radio(a, b, c)) second.model.add_value_changed_fn( lambda a, b=first, c=third: like_radio(a, b, c)) third.model.add_value_changed_fn( lambda a, b=first, c=second: like_radio(a, b, c)) """ ) with ui.HStack(width=0, spacing=SPACING): ui.CheckBox(enabled=False).model.set_value(True) ui.CheckBox(enabled=False) self._text("Disabled") self._code( """ ui.CheckBox(enabled=False).model.set_value(True) ui.CheckBox(enabled=False) """ ) ui.Spacer(height=10)
4,949
Python
36.786259
124
0.578299
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/combobox_doc.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. # """The documentation for ComboBox""" from omni import ui from .doc_page import DocPage class ComboBoxDoc(DocPage): """ document for ComboBox""" def create_doc(self, navigate_to=None): self._section_title("ComboBox") self._text("The ComboBox widget is a combined button and a drop-down list.") self._text( "A combo box is a selection widget that displays the current item and can pop up a list of selectable " "items." ) self._exec_code( """ ui.ComboBox(1, "Option 1", "Option 2", "Option 3") """ ) self._text("The following example demonstrates how to add items to the combo box.") self._exec_code( """ editable_combo = ui.ComboBox() ui.Button( "Add item to combo", clicked_fn=lambda m=editable_combo.model: m.append_child_item( None, ui.SimpleStringModel("Hello World")), ) """ ) self._text("The minimal model implementation. It requires to hold the value models and reimplement two methods.") self._exec_code( """ class MinimalItem(ui.AbstractItem): def __init__(self, text): super().__init__() self.model = ui.SimpleStringModel(text) class MinimalModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn( lambda a: self._item_changed(None)) self._items = [ MinimalItem(text) for text in ["Option 1", "Option 2"] ] def get_item_children(self, item): return self._items def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model self._minimal_model = MinimalModel() ui.ComboBox(self._minimal_model, style={"font_size": 22}) """ ) self._text( "The example of communication between widgets. Type anything in the field and it will appear in the combo " "box." ) self._exec_code( """ editable_combo = None class StringModel(ui.SimpleStringModel): ''' String Model activated when editing is finished. Adds item to combo box. ''' def __init__(self): super().__init__("") def end_edit(self): combo_model = editable_combo.model # Get all the options ad list of strings all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] # Get the current string of this model fieldString = self.as_string if fieldString: if fieldString in all_options: index = all_options.index(fieldString) else: # It's a new string in the combo box combo_model.append_child_item( None, ui.SimpleStringModel(fieldString) ) index = len(all_options) combo_model.get_item_value_model().set_value(index) self._field_model = StringModel() def combo_changed(combo_model, item): all_options = [ combo_model.get_item_value_model(child).as_string for child in combo_model.get_item_children() ] current_index = combo_model.get_item_value_model().as_int self._field_model.as_string = all_options[current_index] with ui.HStack(): ui.StringField(self._field_model) editable_combo = ui.ComboBox(width=0, arrow_only=True) editable_combo.model.add_item_changed_fn(combo_changed) """ ) ui.Spacer(height=10) # TODO omni.ui: restore functionality for Kit Next if True: return self._text("The USD example. It tracks the stage cameras and can assign the current camera.") self._exec_code( """ class CamerasItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model class CamerasModel(ui.AbstractItemModel): def __init__(self): super().__init__() # Omniverse interfaces self._viewport = omni.kit.viewport.utility.get_active_viewport() self._stage_update = \\ omni.stageupdate.get_stage_update_interface() self._usd_context = omni.usd.get_context() self._stage_subscription = \\ self._stage_update.create_stage_update_node( "CamerasModel", None, None, None, self._on_prim_created, None, self._on_prim_removed ) # The list of the cameras is here self._cameras = [] # The current index of the editable_combo box self._current_index = ui.SimpleIntModel() self._current_index.add_value_changed_fn( self._current_index_changed) # Iterate the stage and get all the cameras stage = self._usd_context.get_stage() for prim in Usd.PrimRange(stage.GetPseudoRoot()): if prim.IsA(UsdGeom.Camera): self._cameras.append( CamerasItem( ui.SimpleStringModel( prim.GetPath().pathString))) def get_item_children(self, item): return self._cameras def get_item_value_model(self, item, column_id): if item is None: return self._current_index return item.model def _on_prim_created(self, path): self._cameras.append( CamerasItem(ui.SimpleStringModel(path))) self._item_changed(None) def _on_prim_removed(self, path): cameras = [cam.model.as_string for cam in self._cameras] if path in cameras: index = cameras.index(path) del self._cameras[index] self._current_index.as_int = 0 self._item_changed(None) def _current_index_changed(self, model): index = model.as_int self.self._viewport.camera_path = self._cameras[index].model.as_string self._item_changed(None) self._combo_model = CamerasModel() ui.ComboBox(self._combo_model) """ )
7,786
Python
34.076576
121
0.509504
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/slider_doc.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. # """The documentation for Sliders""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import re SPACING = 5 class SliderDoc(DocPage): """ document for Slider""" def create_doc(self, navigate_to=None): self._section_title("Drag & Slider") self._text( "There are 2 main kind of Sliders, <Type>Slider and <Type>Drag. The Sliders are more like traditionalal " "slider that can be drag and snap where you click, the value can be shown on the slider or not but can not " "be edited directly by double clicking" ) self._text( "The Drags are more like Field in the way that they behave like a Field, you can double clic to edit the " "value but they also have a mean to be 'Dragged' to increase / decrease the value" ) self._text( "They currently support minimal styling, simple background color (background_color) and text color (color)." ) self._caption("FloatSlider", navigate_to) def build_slider_table(label, slider_command): def mystrip(line: str, number: int) -> str: """Remove `number` spaces from the begin of the line""" n = 0 l = len(line) while n < number and n < l and line[n] == " ": n += 1 return line[n:] # Remove whitespaces from the command but keep the newline symbols code = "\n".join(mystrip(line, 16) for line in slider_command.split("\n") if line) with ui.HStack(): with ui.ZStack(width=130): ui.Rectangle(name="table") ui.Label(label, name="text", alignment=ui.Alignment.RIGHT, style={"margin": SPACING}) with ui.ZStack(): ui.Rectangle(name="table") with ui.HStack(name="margin", style={"HStack::margin": {"margin": SPACING / 2}}, spacing=SPACING): exec(code) with ui.ZStack(width=ui.Fraction(2)): ui.Rectangle(name="table") with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}): ui.Rectangle(name="code") ui.Label(code, name="code") with ui.VStack(): build_slider_table( "Default", """ ui.FloatSlider() """, ) build_slider_table( "Min/Max", """ ui.FloatSlider(min=0, max=10) """, ) build_slider_table( "Hard Min/Max", """ model = ui.SimpleFloatModel(1.0, min=0, max=100) ui.FloatSlider(model, min=0, max=10) """, ) build_slider_table( "With Style", """ ui.FloatSlider( min=-180, max=180, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl("#BBBBBB"), "color": cl.black } ) """, ) build_slider_table( "Transparent bg", """ ui.FloatSlider( min=-180, max=180, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl.transparent, "color": cl.black, "font_size":20.0 } ) """, ) build_slider_table( "different slider color", """ ui.FloatSlider( min=0, max=1, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl.transparent, "color": cl.black, "font_size":20.0, "secondary_color": cl.red, "secondary_selected_color": cl("#FF00FF") } ) """, ) build_slider_table( "Field & Slider", """ field = ui.FloatField(height=15, width=50) ui.FloatSlider( min=0, max=20, step=.1, model=field.model, style={"color":cl.transparent} ) # default value field.model.set_value(12.0) """, ) build_slider_table( "Filled Mode Slider", """ ui.FloatSlider( height=20, style={"background_color": cl("#DDDDDD"), "secondary_color": cl("#AAAAAA"), "color": cl("#111111")} ).model.set_value(0.5) """, ) build_slider_table( "Rounded Slider", """ ui.FloatSlider( height=20, style={"border_radius": 20, "background_color": cl.black, "secondary_color": cl("#DDDDDD"), "color": cl("#AAAAAA")} ).model.set_value(0.5) """, ) build_slider_table( "Slider Step", """ slider = ui.FloatSlider( step=0.25, height=0, style={"border_radius": 20, "background_color": cl.black, "secondary_color": cl("#DDDDDD"), "color": cl("#AAAAAA")}) slider.model.set_value(0.5) """, ) build_slider_table( "Handle Step", """ slider = ui.FloatSlider( step=0.2, height=0, style={"draw_mode": ui.SliderDrawMode.HANDLE}) slider.model.set_value(0.4) """, ) self._caption("IntSlider", navigate_to) with ui.VStack(): build_slider_table( "Default", """ ui.IntSlider() """, ) build_slider_table( "Min/Max", """ ui.IntSlider(min=0, max=20) """, ) build_slider_table( "With Style", """ ui.IntSlider( min=0, max=20, style={ "draw_mode": ui.SliderDrawMode.HANDLE, "background_color": cl("#BBFFBB"), "color": cl("#FF00FF"), "font_size": 14.0 } ) """, ) self._caption("FloatDrag", navigate_to) with ui.VStack(): build_slider_table("Default", "ui.FloatDrag()") build_slider_table("Min/Max", "ui.FloatDrag(min=-10, max=10, step=0.01)") self._caption("IntDrag", navigate_to) with ui.VStack(): build_slider_table("Default", "ui.IntDrag()") build_slider_table("Min/Max", "ui.IntDrag(min=0, max=50)") ui.Spacer(height=10)
8,360
Python
33.407407
120
0.417105
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/length_doc.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. # """The documentation for Length""" from omni import ui from .doc_page import DocPage SPACING = 5 class LengthDoc(DocPage): """ document for Length classes""" def create_doc(self, navigate_to=None): self._section_title("Lengths") self._text( "The Framework UI offers several different units for expressing length: Pixel, Percent and Fraction." ) self._text("There is no restriction on which units can be used where.") self._caption("Pixel", navigate_to) self._text("Pixel is the size in pixels and scaled with the HiDPI scale factor.") with ui.HStack(): ui.Button("40px", width=ui.Pixel(40)) ui.Button("60px", width=ui.Pixel(60)) ui.Button("100px", width=100) ui.Button("120px", width=120) ui.Button("150px", width=150) self._code( """ with ui.HStack(): ui.Button("40px", width=ui.Pixel(40)) ui.Button("60px", width=ui.Pixel(60)) ui.Button("100px", width=100) ui.Button("120px", width=120) ui.Button("150px", width=150) """ ) self._caption("Percent", navigate_to) self._text("Percent and Fraction units make it possible to specify sizes relative to the parent size.") self._text("Percent is 1/100th of the parent size.") with ui.HStack(): ui.Button("5%", width=ui.Percent(5)) ui.Button("10%", width=ui.Percent(10)) ui.Button("15%", width=ui.Percent(15)) ui.Button("20%", width=ui.Percent(20)) ui.Button("25%", width=ui.Percent(25)) self._code( """ with ui.HStack(): ui.Button("5%", width=ui.Percent(5)) ui.Button("10%", width=ui.Percent(10)) ui.Button("15%", width=ui.Percent(15)) ui.Button("20%", width=ui.Percent(20)) ui.Button("25%", width=ui.Percent(25)) """ ) self._caption("Fraction", navigate_to) self._text( "Fraction length is made to take the available space of the parent widget and then divide it among all the " "child widgets with Fraction length in proportion to their Fraction factor." ) with ui.HStack(): ui.Button("One", width=ui.Fraction(1)) ui.Button("Two", width=ui.Fraction(2)) ui.Button("Three", width=ui.Fraction(3)) ui.Button("Four", width=ui.Fraction(4)) ui.Button("Five", width=ui.Fraction(5)) self._code( """ with ui.HStack(): ui.Button("One", width=ui.Fraction(1)) ui.Button("Two", width=ui.Fraction(2)) ui.Button("Three", width=ui.Fraction(3)) ui.Button("Four", width=ui.Fraction(4)) ui.Button("Five", width=ui.Fraction(5)) """ ) ui.Spacer(height=10)
3,405
Python
34.479166
120
0.576799
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/shape_doc.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. # """The documentation for Shapes""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect SPACING = 5 def editable_curve(): with ui.ZStack(height=400): # The Bezier tangents tangents = [(50, 50), (-50, -50)] # Four draggable rectangles that represent the control points placer1 = ui.Placer(draggable=True, offset_x=0, offset_y=0) with placer1: rect1 = ui.Rectangle(width=20, height=20) placer2 = ui.Placer(draggable=True, offset_x=50, offset_y=50) with placer2: rect2 = ui.Rectangle(width=20, height=20) placer3 = ui.Placer(draggable=True, offset_x=100, offset_y=100) with placer3: rect3 = ui.Rectangle(width=20, height=20) placer4 = ui.Placer(draggable=True, offset_x=150, offset_y=150) with placer4: rect4 = ui.Rectangle(width=20, height=20) # The bezier curve curve = ui.FreeBezierCurve(rect1, rect4) curve.start_tangent_width = ui.Pixel(tangents[0][0]) curve.start_tangent_height = ui.Pixel(tangents[0][1]) curve.end_tangent_width = ui.Pixel(tangents[1][0]) curve.end_tangent_height = ui.Pixel(tangents[1][1]) # The logic of moving the control points def left_moved(_): x = placer1.offset_x y = placer1.offset_y tangent = tangents[0] placer2.offset_x = x + tangent[0] placer2.offset_y = y + tangent[1] def right_moved(_): x = placer4.offset_x y = placer4.offset_y tangent = tangents[1] placer3.offset_x = x + tangent[0] placer3.offset_y = y + tangent[1] def left_tangent_moved(_): x1 = placer1.offset_x y1 = placer1.offset_y x2 = placer2.offset_x y2 = placer2.offset_y tangent = (x2 - x1, y2 - y1) tangents[0] = tangent curve.start_tangent_width = ui.Pixel(tangent[0]) curve.start_tangent_height = ui.Pixel(tangent[1]) def right_tangent_moved(_): x1 = placer4.offset_x y1 = placer4.offset_y x2 = placer3.offset_x y2 = placer3.offset_y tangent = (x2 - x1, y2 - y1) tangents[1] = tangent curve.end_tangent_width = ui.Pixel(tangent[0]) curve.end_tangent_height = ui.Pixel(tangent[1]) # Callback for moving the control points placer1.set_offset_x_changed_fn(left_moved) placer1.set_offset_y_changed_fn(left_moved) placer2.set_offset_x_changed_fn(left_tangent_moved) placer2.set_offset_y_changed_fn(left_tangent_moved) placer3.set_offset_x_changed_fn(right_tangent_moved) placer3.set_offset_y_changed_fn(right_tangent_moved) placer4.set_offset_x_changed_fn(right_moved) placer4.set_offset_y_changed_fn(right_moved) def editable_rect(): with ui.ZStack(height=200): # Four draggable rectangles that represent the control points with ui.Placer(draggable=True, offset_x=0, offset_y=0): control1 = ui.Circle(width=10, height=10, name="default") with ui.Placer(draggable=True, offset_x=150, offset_y=150): control2 = ui.Circle(width=10, height=10, name="default") # The rectangle that fits to the control points ui.FreeRectangle(control1, control2) class ShapeDoc(DocPage): """ document for Shapes""" def create_doc(self, navigate_to=None): """ descriptions for the shapes widgets""" self._section_title("Shape") self._text("Shape enable you to build custom widget with specific look") self._text("There are many shape you can use, Rectangle, Circle, Triangle, Line, etc") self._text( "In most case those Shape will fit into the Widget size and scale accoringly to the layout they are in " "For some of them you can fix the size to enable to have more precise control over they size" ) self._caption("Rectangle", navigate_to) self._text( "You can use Rectable to draw rectangle shape, you can have backgroundColor, borderColor, " "borderWidth, border_radius. mixed it with other controls using ZStack to create advance look" ) with ui.VStack(): self._shape_table(f"""ui.Rectangle(name="default")""", "(Default) The rectangle is scaled to fit") self._shape_table( """ui.Rectangle( style={"background_color": cl("#888888"), "border_color": cl("#222222"), "border_width": 2.0, "border_radius": 5.0} )""", "this rectangle use its own style to control colors and shape", ) self._shape_table( """ui.Rectangle( width=20, height=20, style={"background_color": cl("#888888"), "border_color": cl("#222222")} )""", "using fixed width and height", ) self._shape_table( """with ui.ZStack(height=20): ui.Rectangle(height=20, style={"background_color": cl("#888888"), "border_color": cl("#111111"), "border_width": .5, "border_radius": 8.0} ) with ui.HStack(): ui.Spacer(width=10) ui.Image( "resources/icons/Cloud.png", width=20, height=20 ) ui.Label( "Search Field", style={"color": cl("#DDDDDD")} )""", "Compose with ZStack for advanced control", ) self._text("Support for specific Rounded Corner") corner_flags = { "NONE": ui.CornerFlag.NONE, "TOP_LEFT": ui.CornerFlag.TOP_LEFT, "TOP_RIGHT": ui.CornerFlag.TOP_RIGHT, "BOTTOM_LEFT": ui.CornerFlag.BOTTOM_LEFT, "BOTTOM_RIGHT": ui.CornerFlag.BOTTOM_RIGHT, "TOP": ui.CornerFlag.TOP, "BOTTOM": ui.CornerFlag.BOTTOM, "LEFT": ui.CornerFlag.LEFT, "RIGHT": ui.CornerFlag.RIGHT, "ALL": ui.CornerFlag.ALL, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in corner_flags.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}): ui.Rectangle( style={"background_color": cl("#AA4444"), "border_radius": 20.0, "corner_flag": value} ) ui.Spacer(height=10) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Circle", navigate_to) self._text("You can use Circle to draw circular shape, you can have backgroundColor, borderColor, borderWidth") with ui.VStack(): self._shape_table( f"""ui.Circle(name="default")""", "(Default) The circle is scaled to fit, the alignment is centered" ) self._shape_table( f"""ui.Circle(name="default")""", "This circle, is scaled to Fit too with the Row 100 height", 100 ) self._shape_table( f"""ui.Circle( name="blue", radius=20, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_CENTER)""", "This circle has a fixed radius of 20, the alignment is LEFT_CENTER", ) self._shape_table( f"""ui.Circle( name="red", radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.RIGHT_CENTER)""", "This circle has a fixed radius of 10, the alignment is RIGHT_CENTER", ) self._shape_table( """ui.Circle( style={"background_color": cl("#00FFFF"),}, size_policy=ui.CircleSizePolicy.STRETCH, alignment=ui.Alignment.CENTER_TOP)""", "This circle has a radius to fill the bound, with an alignment is CENTER_TOP", ) self._shape_table( """ui.Circle( style={"background_color": cl.green, "border_color": cl.blue, "border_width": 5}, radius=10, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.CENTER_BOTTOM)""", "This circle has a fixed radius of 5, the alignment is CENTER_BOTTOM, and a custom style ", ) self._text("Supported Alignment value for the Circle") alignments = { "CENTER": ui.Alignment.CENTER, "LEFT_TOP": ui.Alignment.LEFT_TOP, "LEFT_CENTER": ui.Alignment.LEFT_CENTER, "LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "CENTER_TOP": ui.Alignment.CENTER_TOP, "CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "RIGHT_TOP": ui.Alignment.RIGHT_TOP, "RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } with ui.ScrollingFrame( height=150, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): with ui.ZStack(): ui.Rectangle(name="table") ui.Circle( radius=10, size_policy=ui.CircleSizePolicy.FIXED, name="orientation", alignment=value, style={"background_color": cl("#AA4444")}, ) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Triangle", navigate_to) self._text( "You can use Triangle to draw Triangle shape, you can have backgroundColor, borderColor, borderWidth" ) with ui.VStack(): self._shape_table( f"""ui.Triangle(name="default")""", "(Default) The triange is scaled to fit, base on the left and tip on the center right", 100, ) self._shape_table( """ui.Triangle( style={"border_color": cl.black, "border_width": 2}, alignment=ui.Alignment.CENTER_TOP)""", "Default triange with custom color and border", 100, ) self._text("the Alignment define where is the Tip of the Triangle, base will be at the oposite side") alignments = { "LEFT_TOP": ui.Alignment.LEFT_TOP, "LEFT_CENTER": ui.Alignment.LEFT_CENTER, "LEFT_BOTTOM": ui.Alignment.LEFT_BOTTOM, "CENTER_TOP": ui.Alignment.CENTER_TOP, "CENTER_BOTTOM": ui.Alignment.CENTER_BOTTOM, "RIGHT_TOP": ui.Alignment.RIGHT_TOP, "RIGHT_CENTER": ui.Alignment.RIGHT_CENTER, "RIGHT_BOTTOM": ui.Alignment.RIGHT_BOTTOM, } colors = [cl.red, cl("#FFFF00"), cl("#FF00FF"), cl("#FF0FF0"), cl.green, cl("#F00FFF"), cl("#FFF000"), cl("#AA3333")] index = 0 with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): color = colors[index] index = index + 1 ui.Triangle(name="orientation", alignment=value, style={"background_color": color}) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("Line", navigate_to) self._text("You can use Line to draw Line shape, you can use color, border_width") with ui.VStack(): self._shape_table( f"""ui.Line(name="default")""", "(Default) The Line is scaled to fit, base on the left and tip on the center right", 100, ) self._shape_table( """ui.Line(name="default", alignment=ui.Alignment.H_CENTER, style={"border_width":1, "color": cl.blue})""", "The Line is scaled to fit, centered top to bottom, color red and line width 1", 100, ) self._shape_table( """ui.Line(name="default", alignment=ui.Alignment.LEFT, style={"border_width":5, "color": cl("#880088")})""", "The Line is scaled to fit, Aligned Left , color purple and line width 5", 100, ) self._text("the Alignment define where is the line is in the Widget, always fit") alignments = { "LEFT": ui.Alignment.LEFT, "RIGHT": ui.Alignment.RIGHT, "H_CENTER": ui.Alignment.H_CENTER, "TOP": ui.Alignment.TOP, "BOTTOM": ui.Alignment.BOTTOM, "V_CENTER": ui.Alignment.V_CENTER, } with ui.ScrollingFrame( height=100, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, style={"ScrollingFrame": {"background_color": cl.transparent}}, ): with ui.HStack(height=100): for key, value in alignments.items(): with ui.ZStack(): ui.Rectangle(name="table") with ui.VStack(style={"VStack": {"margin": SPACING * 2}}, spacing=SPACING * 2): ui.Line(name="demo", alignment=value) ui.Label(key, style={"color": cl.black, "font_size": 8}, alignment=ui.Alignment.CENTER) self._caption("FreeRectangle", navigate_to) self._text( "The free widget is the widget that is independent of the layout. It means it can be stuck to other " "widgets." ) editable_rect() self._code(inspect.getsource(editable_rect).split("\n", 1)[-1]) self._caption("FreeBezierCurve", navigate_to) self._text("Bezier curves are used to model smooth curves that can be scaled infinitely.") self._text( "FreeBezierCurve is using two widgets to get the position of the curve ends. It means it's possible to " "stick the curve to the layout's widgets, and the curve will follow the changes of the layout " "automatically." ) editable_curve() self._code(inspect.getsource(editable_curve).split("\n", 1)[-1]) ui.Spacer(height=10)
16,893
Python
41.661616
125
0.524063
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/scrolling_frame_doc.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. # """The documentation for Scrolling Frame""" from omni import ui from .doc_page import DocPage SPACING = 5 class ScrollingFrameDoc(DocPage): """ document for Menu""" def create_doc(self, navigate_to=None): self._section_title("ScrollingFrame") self._text( "The ScrollingFrame class provides the ability to scroll onto another widget. ScrollingFrame is used to " "display the contents of a child widget within a frame. If the widget exceeds the size of the frame, the " "frame can provide scroll bars so that the entire area of the child widget can be viewed." ) with ui.HStack(style=self._style_system): left_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with left_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Left {i}") right_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with right_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Right {i}") # Synchronize the scroll position of two frames def set_scroll_y(frame, y): frame.scroll_y = y left_frame.set_scroll_y_changed_fn(lambda y, frame=right_frame: set_scroll_y(frame, y)) right_frame.set_scroll_y_changed_fn(lambda y, frame=left_frame: set_scroll_y(frame, y)) self._code( """ with ui.HStack(style=style_system): left_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with left_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Left {i}") right_frame = ui.ScrollingFrame( height=250, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ) with right_frame: with ui.VStack(height=0): for i in range(20): ui.Button(f"Button Right {i}") # Synchronize the scroll position of two frames def set_scroll_y(frame, y): frame.scroll_y = y left_frame.set_scroll_y_changed_fn( lambda y, frame=right_frame: set_scroll_y(frame, y)) right_frame.set_scroll_y_changed_fn( lambda y, frame=left_frame: set_scroll_y(frame, y) """ ) ui.Spacer(height=10)
3,595
Python
38.086956
118
0.596106
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/treeview_doc.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. # """The documentation for Widget""" from .doc_page import DocPage from pathlib import Path import asyncio import omni.ui as ui import time class TreeViewDoc(DocPage): """Document for TreeView""" def __init__(self, extension_path): super().__init__(extension_path) self._selection = None self._model = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. if self._selection: self._selection._stage_event_sub = None self._selection._tree_view = None self._selection = None if self._model: self._model.stage_subscription = None self._model = None self._command_model = None self._list_model = None self._name_value_model = None self._name_value_delegate = None def create_doc(self, navigate_to=None): self._section_title("TreeView") self._text( "TreeView is a widget that presents a hierarchical view of information. Each item can have a number of " "subitems. An indentation often visualizes this in a list. An item can be expanded to reveal subitems, if " "any exist, and collapsed to hide subitems." ) self._text( "TreeView can be used in file manager applications, where it allows the user to navigate the file system " "directories. They are also used to present hierarchical data, such as the scene object hierarchy." ) self._text( "TreeView uses a model-delegate-view pattern to manage the relationship between data and the way it is presented. " "The separation of functionality gives developers greater flexibility to customize the presentation of " "items and provides a standard interface to allow a wide range of data sources to be used with other " "widgets." ) self._text("The following example demonstrates how to make a single level tree appear like a simple list.") class CommandItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) class CommandModel(ui.AbstractItemModel): """ Represents the list of commands registered in Kit. It is used to make a single level tree appear like a simple list. """ def __init__(self): super().__init__() self._commands = [] try: import omni.kit.commands except ModuleNotFoundError: return omni.kit.commands.subscribe_on_change(self._commands_changed) self._commands_changed() def _commands_changed(self): """Called by subscribe_on_change""" self._commands = [] import omni.kit.commands for cmd_list in omni.kit.commands.get_commands().values(): for k in cmd_list.values(): self._commands.append(CommandItem(k.__name__)) self._item_changed(None) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._commands def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ if item and isinstance(item, CommandItem): return item.name_model with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._command_model = CommandModel() tree_view = ui.TreeView( self._command_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}} ) self._text("The following example demonstrates reordering with drag and drop.") class ListItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return f'"{self.name_model.as_string}"' class ListModel(ui.AbstractItemModel): """ Represents the model for lists. It's very easy to initialize it with any string list: string_list = ["Hello", "World"] model = ListModel(*string_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() self._children = [ListItem(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model class ListModelWithReordering(ListModel): """ Represents the model for the list with the ability to reorder the list with drag and drop. """ def __init__(self, *args): super().__init__(*args) def get_drag_mime_data(self, item): """Returns Multipurpose Internet Mail Extensions (MIME) data for be able to drop this item somewhere""" # As we don't do Drag and Drop to the operating system, we return the string. return item.name_model.as_string def drop_accepted(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called to highlight target when drag and drop.""" # If target_item is None, it's the drop to root. Since it's # list model, we support reorganizetion of root only and we # don't want to create tree. return not target_item and drop_location >= 0 def drop(self, target_item, source, drop_location=-1): """Reimplemented from AbstractItemModel. Called when dropping something to the item.""" try: source_id = self._children.index(source) except ValueError: # Not in the list. This is the source from another model. return if source_id == drop_location: # Nothing to do return self._children.remove(source) if drop_location > len(self._children): # Drop it to the end self._children.append(source) else: if source_id < drop_location: # Becase when we removed source, the array became shorter drop_location = drop_location - 1 self._children.insert(drop_location, source) self._item_changed(None) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._list_model = ListModelWithReordering("Simplest", "List", "Model", "With", "Reordering") tree_view = ui.TreeView( self._list_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, drop_between_items=True, ) self._text("The following example demonstrates the ability to edit TreeView items.") class FloatModel(ui.AbstractValueModel): """An example of custom float model that can be used for formatted string output""" def __init__(self, value: float): super().__init__() self._value = value def get_value_as_float(self): """Reimplemented get float""" return self._value or 0.0 def get_value_as_string(self): """Reimplemented get string""" # This string gors to the field. if self._value is None: return "" # General format. This prints the number as a fixed-point # number, unless the number is too large, in which case it # switches to 'e' exponent notation. return "{0:g}".format(self._value) def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() class NameValueItem(ui.AbstractItem): """Single item of the model""" def __init__(self, text, value): super().__init__() self.name_model = ui.SimpleStringModel(text) self.value_model = FloatModel(value) def __repr__(self): return f'"{self.name_model.as_string} {self.value_model.as_string}"' class NameValueModel(ui.AbstractItemModel): """ Represents the model for name-value table. It's very easy to initialize it with any string-float list: my_list = ["Hello", 1.0, "World", 2.0] model = NameValueModel(*my_list) ui.TreeView(model) """ def __init__(self, *args): super().__init__() # ["Hello", 1.0, "World", 2.0"] -> [("Hello", 1.0), ("World", 2.0)] regrouped = zip(*(iter(args),) * 2) self._children = [NameValueItem(*t) for t in regrouped] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: # Since we are doing a flat list, we return the children of root only. # If it's not root we return. return [] return self._children def get_item_value_model_count(self, item): """The number of columns""" return 2 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel for the first column and SimpleFloatModel for the second column. """ return item.value_model if column_id == 1 else item.name_model class EditableDelegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def __init__(self): super().__init__() self.subscription = None def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" pass def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" stack = ui.ZStack(height=20) with stack: value_model = model.get_item_value_model(item, column_id) label = ui.Label(value_model.as_string) if column_id == 1: field = ui.FloatField(value_model, visible=False) else: field = ui.StringField(value_model, visible=False) # Start editing when double clicked stack.set_mouse_double_clicked_fn(lambda x, y, b, m, f=field, l=label: self.on_double_click(b, f, l)) def on_double_click(self, button, field, label): """Called when the user double-clicked the item in TreeView""" if button != 0: return # Make Field visible when double clicked field.visible = True field.focus_keyboard() # When editing is finished (enter pressed of mouse clicked outside of the viewport) self.subscription = field.model.subscribe_end_edit_fn( lambda m, f=field, l=label: self.on_end_edit(m, f, l) ) def on_end_edit(self, model, field, label): """Called when the user is editing the item and pressed Enter or clicked outside of the item""" field.visible = False label.text = model.as_string self.subscription = None with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, ): self._name_value_model = NameValueModel("First", 0.2, "Second", 0.3, "Last", 0.4) self._name_value_delegate = EditableDelegate() tree_view = ui.TreeView( self._name_value_model, delegate=self._name_value_delegate, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) class AsyncQueryModel(ListModel): """ This is an example of async filling the TreeView model. It's collecting only as many as it's possible of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage is extremely big. """ def __init__(self): super().__init__() self._stop_event = None def destroy(self): self.stop() def stop(self): """Stop traversing the stage""" if self._stop_event: self._stop_event.set() def reset(self): """Traverse the stage and keep materials""" self.stop() self._stop_event = asyncio.Event() self._children.clear() self._item_changed(None) asyncio.ensure_future(self.__get_all(self._stop_event)) def __push_collected(self, collected): """Add given array to the model""" for c in collected: self._children.append(c) self._item_changed(None) async def __get_all(self, stop_event): """Traverse the stage portion at time, so it doesn't freeze""" stop_event.clear() start_time = time.time() # The widget will be updated not faster than 60 times a second update_every = 1.0 / 60.0 import omni.usd from pxr import Usd from pxr import UsdShade context = omni.usd.get_context() stage = context.get_stage() if not stage: return # Buffer to keep the portion of the items before sending to the # widget collected = [] for p in stage.Traverse( Usd.TraverseInstanceProxies(Usd.PrimIsActive and Usd.PrimIsDefined and Usd.PrimIsLoaded) ): if stop_event.is_set(): break if p.IsA(UsdShade.Material): # Collect materials only collected.append(ListItem(str(p.GetPath()))) elapsed_time = time.time() # Loop some amount of time so fps will be about 60FPS if elapsed_time - start_time > update_every: start_time = elapsed_time # Append the portion and update the widget if collected: self.__push_collected(collected) collected = [] # Wait one frame to let other tasks go await omni.kit.app.get_app().next_update_async() self.__push_collected(collected) try: import omni.usd from pxr import Usd usd_available = True except ModuleNotFoundError: usd_available = False if usd_available: self._text( "This is an example of async filling the TreeView model. It's collecting only as many as it's possible " "of USD prims for 0.016s and waits for the next frame, so the UI is not locked even if the USD Stage " "is extremely big." ) with ui.ScrollingFrame( height=400, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", style={"Field": {"background_color": 0xFF000000}}, ): self._async_query_model = AsyncQueryModel() ui.TreeView( self._async_query_model, root_visible=False, header_visible=False, style={"TreeView.Item": {"margin": 4}}, ) self._loaded_label = ui.Label("Press Button to Load Materials", name="text") with ui.HStack(): ui.Button("Traverse All", clicked_fn=self._async_query_model.reset) ui.Button("Stop Traversing", clicked_fn=self._async_query_model.stop) def _item_changed(model, item): if item is None: count = len(model._children) self._loaded_label.text = f"{count} Materials Traversed" self._async_query_sub = self._async_query_model.subscribe_item_changed_fn(_item_changed) self._text("For the example code please see the following file:") current_file_name = Path(__file__).resolve() self._code(f"{current_file_name}", elided_text=True) ui.Spacer(height=10)
20,987
Python
39.130019
127
0.532377
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/dnd_doc.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. # """The documentation of the omni.ui aka UI Framework""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect def simple_dnd(): def drag(url): """Called for the drag operation. Returns drag data.""" return url def drop_accept(url): """Called to check the drag data is acceptable.""" return True def drop(widget, event): """Called when dropping the data.""" widget.source_url = event.mime_data def drag_area(url): """Create a draggable image.""" image = ui.Image(url, width=64, height=64) image.set_drag_fn(lambda: drag(url)) def drop_area(): """A drop area that shows image when drop.""" with ui.ZStack(width=64, height=64): ui.Rectangle() image = ui.Image() image.set_accept_drop_fn(drop_accept) image.set_drop_fn(lambda a, w=image: drop(w, a)) with ui.HStack(): drag_area("resources/icons/Nav_Flymode.png") drag_area("resources/icons/Move_64.png") ui.Spacer(width=64) drop_area() def complex_dnd(): def drag(url): # Draw the image and the image name in the drag tooltip with ui.VStack(): ui.Image(url, width=32, height=32) ui.Label(url) return url def drop_accept(url, ext): # Accept drops of specific extension only return url.endswith(ext) def drop(widget, event): widget.source_url = event.mime_data def drag_area(url): image = ui.Image(url, width=64, height=64) image.set_drag_fn(lambda: drag(url)) def drop_area(ext): # If drop is acceptable, the rectangle is blue style = {} style["Rectangle"] = {"background_color": cl("#999999")} style["Rectangle:drop"] = {"background_color": cl("#004499")} stack = ui.ZStack(width=64, height=64) with stack: ui.Rectangle(style=style) ui.Label(f"Accepts {ext}") image = ui.Image(style={"margin": 2}) stack.set_accept_drop_fn(lambda d, e=ext: drop_accept(d, e)) stack.set_drop_fn(lambda a, w=image: drop(w, a)) with ui.HStack(): drag_area("resources/icons/sound.png") drag_area("resources/icons/stage.png") drag_area("resources/glyphs/menu_audio.svg") drag_area("resources/glyphs/menu_camera.svg") ui.Spacer(width=64) drop_area(".png") ui.Spacer(width=64) drop_area(".svg") class DNDDoc(DocPage): """The document for Drag and Drop""" def create_doc(self, navigate_to=None): self._section_title("Drag and Drop") self._caption("Minimal Example", navigate_to) self._text( "Omni::UI includes methods to perform Drag and Drop operations quickly. Drag and Drop with Omni::UI is " "straightforward." ) self._text( "A drag and drop operation consists of three parts: the drag, accept the drop, and the drop. For drag, " "Widget has a single callback drag_fn. By adding this function to a widget, you set the callback attached " "to the drag operation. The function should return the string data to drag." ) self._text( "To accept the drop Widget has a callback accept_drop_fn. It's called when the mouse enters the widget " "area. It takes the drag string data and should return either the widget can accept this data for the " "drop." ) self._text( "For the drop part, Widget has a callback drop_fn. With this method, we specify if Widget accepts drops. " "And it's called when the user drops the string data to the widget." ) simple_dnd() self._code(inspect.getsource(simple_dnd).split("\n", 1)[-1]) self._caption("Styling and Tooltips", navigate_to) self._text("It's possible to customize the drag tooltip with creating widgets in drag_fn.") self._text( "To show the drop widget accepts drops visually, there is a style 'drop', and it's propagated to the " "children widgets." ) complex_dnd() self._code(inspect.getsource(complex_dnd).split("\n", 1)[-1]) ui.Spacer(height=10)
4,786
Python
32.711267
119
0.616172
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/web_doc.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. # """The documentation for Web features such as WebViewWidget implementations""" from .doc_page import DocPage from typing import List import json import omni.kit.widget.webview as webview import omni.ui as ui _BASE_STYLE = { "WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}, "Label": {"color": 0xFF000000, "margin": 5.0}, "CheckBox": {"margin": 5.0}, } class WebViewWidgetDoc(DocPage): """ Document for WebViewWidget""" def __init__(self): self._sections = [ ("Displaying an url", self.create_displaying_an_url), ("Styling", self.create_styling), ("Content loading", self.create_content_loading), ("Non-opaque contents", self.create_non_opaque_contents), ("Communication", self.create_js_host_communication), ("Web page debugging", self.create_web_page_debugging), ] def get_sections(self) -> List[str]: return [t for (t, _) in self._sections] def create_doc(self, navigate_to=None): self._section_title("WebViewWidget") for (title, create_func) in self._sections: self._caption(title, navigate_to) create_func() def create_displaying_an_url(self): self._text( """The WebViewWidget type displays web pages. The url can be loaded with 'load_url()'. The load progress can be observed with 'loading_changed_fn' and 'progress_changed_fn' as well as the WebViewWidget properties 'loading' and 'progress'. """ ) with ui.VStack(style=_BASE_STYLE): loading_label = ui.Label("Load label") def update_progress(progress: float): loading_label.text = f"Loading {(progress * 100.0):.0f}% ..." def update_loading(loading: bool): if not loading: loading_label.text = "Loading done." web_view = webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(500), loading_changed_fn=update_loading, progress_changed_fn=update_progress, ) urls = ["https://www.nvidia.com", "https://news.ycombinator.com", "http://google.com"] web_view.load_url(urls[0]) def change_url(model, _item): url = urls[model.get_item_value_model().as_int] web_view.load_url(url) url_selector = ui.ComboBox(0, *urls) url_selector.model.add_item_changed_fn(change_url) def create_styling(self): self._text( """The WebViewWidget can be styled normally. Here we create a web view with rounded corners and wider borders. In this example, we also use 'url' constructor property to start the load.""" ) style = { "WebViewWidget": { "border_width": 3, "border_radius": 7, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D, } } with ui.VStack(style=_BASE_STYLE): webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(500), url="https://www.google.com") def create_content_loading(self): self._text( """The WebViewWidget can be populated with static html with the 'html' constructor property. In this case, the 'url' property describes the base url of the document.""" ) style = {"WebViewWidget": {"border_width": 0.5, "margin": 5.0, "padding": 5.0, "border_color": 0xFFFD761D}} with ui.VStack(style=style): webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(500), html='<body><h1>Hello from web page</h1><p>This is web content. Here\'s a link <a href="http://wwf.org">into the wild.</a></p></body>', url="http://example.com/content_loading", ) def create_non_opaque_contents(self): self._text( """The WebViewWidget can be marked non-opaque so transparent or translucent contents work. The magenta circles are omni.ui widgets and can be seen beneath and on top of the WebViewWidget. The web page is marked as transparent with 'contents_is_opaque=False' and then with HTML body css property 'background: transparent'. """ ) html = """<body style="background: transparent"> <h3 style="background: rgba(255, 0, 0, 0.4)">Web page input</h3> <input type="text" value="..text 1.." /> <br/> <input type="text" value="..text 2.." style="background: rgba(255,255,255,0.5)"/> <br/> <input type="text" value="..text 3.." /> <br/> <input type="text" value="..text 4.." style="background: rgba(255,255,255,0.5)"/> <br/> <input type="text" value="..text last.." /> <br/> </body> """ with ui.VStack(style=_BASE_STYLE): ui.Circle( radius=100, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_BOTTOM, style={"background_color": 0xDDFF00AA}, ) webview.WebViewWidget( width=ui.Percent(100), height=ui.Pixel(200), contents_is_opaque=False, html=html, url="http://example.com/non_opaque_contents", style={"background_color": 0}, ) ui.Circle( radius=100, size_policy=ui.CircleSizePolicy.FIXED, alignment=ui.Alignment.LEFT_TOP, style={"background_color": 0xDDFFAAAA}, ) def create_js_host_communication(self): self._text( """The WebViewWidget can control the JavaScript application by using WebViewWidget.evaluate_javascript. The JavaScript application can send data to the host application by using window.nvwebview.messageHandlers.<name>.postMessage("msg"). """ ) html = """<body> <script> function sendToHost() { var v = document.getElementById("toHost"); window.nvwebview.messageHandlers.hostApp.postMessage(v.value); } function receiveFromHost(data) { document.getElementById('fromHost').value = data; } </script> <h3>From JS application to host application</h3> Text to send: <input id="toHost" type="text" value="Hello from &quot;JS&quot; application" size="75" /> <br/> <input type="button" value="Send message to host application" onclick="javascript: sendToHost();" /> <br/> <h3>From host application to JS application</h3> <input id="fromHost" type="text" value="Message from host application comes here" readonly size="75"/> <br/> </body> """ message_to_send = 'Hello from "host" application \U0001f600.' webview_widget = None message_from_js_label = None send_to_js_button = None with ui.VStack(style=_BASE_STYLE): send_to_js_button = ui.Button("Send hello to JS application", width=0) message_from_js_label = ui.Label("Message from JS application comes here") webview_widget = webview.WebViewWidget(width=ui.Percent(100), height=ui.Pixel(300)) def send_to_js(): webview_widget.evaluate_javascript(f"receiveFromHost({json.dumps(message_to_send)})") send_to_js_button.set_clicked_fn(send_to_js) def update_message_from_js_label(msg: str): message_from_js_label.text = msg webview_widget.set_user_script_message_handler_fn("hostApp", update_message_from_js_label) webview_widget.load_html_from_url(html, "https://example.com/js_host_communication") def create_web_page_debugging(self): self._text( """The WebViewWidget.set_remote_web_page_debugging_enabled(true) can be used to enable Chrome Web Inspector debugging for all the WebViewWidget instances. Enable the web page debugging below. Using the desktop Chrome browser, navigate to chrome://inspect to see list of WebViewWidget instances in the process. """ ) webview.WebViewWidget.set_remote_web_page_debugging_enabled(False) checkbox = None def update_remote_debugging(value_model): webview.WebViewWidget.set_remote_web_page_debugging_enabled(value_model.get_value_as_bool()) with ui.HStack(style=_BASE_STYLE): ui.Label("Remote web page debugging enabled", width=0, style={"color": 0xFF000000}) checkbox = ui.CheckBox() checkbox.model.add_value_changed_fn(update_remote_debugging) with ui.VStack(): ui.Spacer() ui.Spacer()
9,073
Python
39.150442
166
0.616665
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/attribute_editor_demo.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. # """an example of creating a custom attribute Editor window""" from omni import ui from pathlib import Path ICON_PATH = Path(__file__).parent.parent.joinpath("icons") LIGHT_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFFCACACA}, "Frame::main_frame": {"background_color": 0xFFCACACA}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFFCACACA}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFFCACACA}, "Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFFBBBBBB, "border_color": 0xFF888888, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF888888}, "Circle::slider": {"background_color": 0xFFBBBBBB}, "Circle::slider:hovered": {"background_color": 0xFFCCCCCC}, "Circle::slider:pressed": {"background_color": 0xFFAAAAAA}, "Triangle::selector": {"background_color": 0xFF888888}, "Triangle::selector:hovered": {"background_color": 0xFF999999}, "Triangle::selector:pressed": {"background_color": 0xFF777777}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } KIT_GREEN = 0xFF8A8777 LABEL_PADDING = 120 DARK_WINDOW_STYLE = { "Window": {"background_color": 0xFF444444}, "Button": {"background_color": 0xFF292929, "margin": 3, "padding": 3, "border_radius": 2}, "Button.Label": {"color": 0xFFCCCCCC}, "Button:hovered": {"background_color": 0xFF9E9E9E}, "Button:pressed": {"background_color": 0xC22A8778}, "VStack::main_v_stack": {"secondary_color": 0x0, "margin_width": 10, "margin_height": 0}, "VStack::frame_v_stack": {"margin_width": 15}, "Rectangle::frame_background": {"background_color": 0xFF343432, "border_radius": 5}, "Field::models": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 4.0}, "Frame": {"background_color": 0xFFAAAAAA}, "Label::transform": {"font_size": 12, "color": 0xFF8A8777}, "Circle::transform": {"background_color": 0x558A8777}, "Field::transform": { "background_color": 0xFF23211F, "border_radius": 3, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 12, }, "Slider::transform": { "background_color": 0xFF23211F, "border_radius": 3, "draw_mode": ui.SliderDrawMode.DRAG, "corner_flag": ui.CornerFlag.RIGHT, "font_size": 14, }, "Label::transform_label": {"font_size": 12, "color": 0xFFDDDDDD}, "Label": {"font_size": 12, "color": 0xFF8A8777}, "Label::label": {"font_size": 14, "color": 0xFF8A8777}, "Label::title": {"font_size": 14, "color": 0xFFAAAAAA}, "Triangle::title": {"background_color": 0xFFAAAAAA}, "ComboBox::path": {"font_size": 12, "secondary_color": 0xFF23211F, "color": 0xFFAAAAAA}, "ComboBox::choices": { "font_size": 12, "color": 0xFFAAAAAA, "background_color": 0xFF23211F, "secondary_color": 0xFF23211F, }, "ComboBox:hovered:choices": {"background_color": 0xFF33312F, "secondary_color": 0xFF33312F}, "Slider::value_less": { "font_size": 12, "color": 0x0, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, "border_color": 0xFFAAFFFF, "border_width": 0, }, "Slider::value": { "font_size": 14, "color": 0xFFAAAAAA, "border_radius": 5, "background_color": 0xFF23211F, "secondary_color": KIT_GREEN, }, "Rectangle::add": {"background_color": 0xFF23211F}, "Rectangle:hovered:add": {"background_color": 0xFF73414F}, "CheckBox::greenCheck": {"font_size": 10, "background_color": KIT_GREEN, "color": 0xFF23211F}, "CheckBox::whiteCheck": {"font_size": 10, "background_color": 0xFFDDDDDD, "color": 0xFF23211F}, "Slider::colorField": {"background_color": 0xFF23211F, "font_size": 14, "color": 0xFF8A8777}, # Frame "CollapsableFrame::standard_collapsable": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "font_size": 16, "border_radius": 2.0, "border_color": 0x0, "border_width": 0, }, "CollapsableFrame:hovered:standard_collapsable": {"secondary_color": 0xFFFBF1E5}, "CollapsableFrame:pressed:standard_collapsable": {"secondary_color": 0xFFF7E4CC}, } CollapsableFrame_style = { "CollapsableFrame": { "background_color": 0xFF343432, "secondary_color": 0xFF343432, "color": 0xFFAAAAAA, "border_radius": 4.0, "border_color": 0x0, "border_width": 0, "font_size": 14, "padding": 0, }, "HStack::header": {"margin": 5}, "CollapsableFrame:hovered": {"secondary_color": 0xFF3A3A3A}, "CollapsableFrame:pressed": {"secondary_color": 0xFF343432}, } class AttributeEditorWindow: """ example of an Attribute Editor Window using Omni::UI """ def __init__(self): self._editor_window = None self._window_Frame = None def set_style_light(self, button): """ """ self._window_Frame.set_style(LIGHT_WINDOW_STYLE) def set_style_dark(self, button): """ """ self._window_Frame.set_style(DARK_WINDOW_STYLE) def shutdown(self): """Should be called when the extesion us unloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. self._editor_window = None def _create_object_selection_frame(self): with ui.Frame(): with ui.ZStack(): ui.Rectangle(name="frame_background") with ui.VStack(spacing=5, name="this", style={"VStack::this": {"margin": 5, "margin_width": 15}}): with ui.HStack(height=0): ui.StringField(name="models").model.set_value("(9 models selected)") with ui.VStack(width=0, height=0): ui.Spacer(width=0, height=3) ui.Image( "resources/glyphs/lock_open.svg", width=25, height=12, style={"color": KIT_GREEN, "marging_width": 5}, ) ui.Spacer(width=0) with ui.VStack(width=0, height=0): ui.Spacer(width=0, height=3) ui.Image("resources/glyphs/settings.svg", width=25, height=12, style={"color": KIT_GREEN}) ui.Spacer(width=0) with ui.HStack(height=0): with ui.ZStack(width=60): ui.Image(f"{ICON_PATH}/Add.svg", width=60, height=30) with ui.HStack(name="this", style={"HStack::this": {"margin_height": 0}}): ui.Spacer(width=15) ui.Label("Add", style={"font_size": 16, "color": 0xFFAAAAAA, "margin_width": 10}) ui.Spacer(width=50) with ui.ZStack(): ui.Rectangle(style={"background_color": 0xFF23211F, "border_radius": 4.0}) with ui.HStack(): with ui.VStack(width=0): ui.Spacer(width=0) ui.Image("resources/glyphs/sync.svg", width=25, height=12) ui.Spacer(width=0) ui.StringField(name="models").model.set_value("Search") def _create_control_state(self, state=0): control_type = [ f"{ICON_PATH}/Expression.svg", f"{ICON_PATH}/Mute Channel.svg", f"{ICON_PATH}/mixed properties.svg", f"{ICON_PATH}/Default value.svg", f"{ICON_PATH}/Changed value.svg", f"{ICON_PATH}/Animation Curve.svg", f"{ICON_PATH}/Animation Key.svg", ] if state == 0: ui.Circle(name="transform", width=20, radius=3.5, size_policy=ui.CircleSizePolicy.FIXED) else: with ui.VStack(width=0): ui.Spacer() ui.Image(control_type[state - 1], width=20, height=12) ui.Spacer() def _create_checkbox_control(self, name, value, label_width=100, line_width=ui.Fraction(1)): with ui.HStack(): ui.Label(name, name="label", width=0) ui.Spacer(width=10) ui.Line(style={"color": 0x338A8777}, width=line_width) ui.Spacer(width=5) with ui.VStack(width=10): ui.Spacer() ui.CheckBox(width=10, height=0, name="greenCheck").model.set_value(value) ui.Spacer() self._create_control_state(0) def _create_path_combo(self, name, paths): with ui.HStack(): ui.Label(name, name="label", width=LABEL_PADDING) with ui.ZStack(): ui.StringField(name="models").model.set_value(paths) with ui.HStack(): ui.Spacer() ui.Circle(width=10, height=20, style={"background_color": 0xFF555555}) ui.ComboBox(0, paths, paths, name="path", width=0, height=0, arrow_only=True) ui.Spacer(width=5) ui.Image("resources/icons/folder.png", width=15) ui.Spacer(width=5) ui.Image("resources/icons/find.png", width=15) self._create_control_state(2) def _build_transform_frame(self): # Transform Frame with ui.CollapsableFrame(title="Transform", style=CollapsableFrame_style): with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=0) components = ["Position", "Rotation", "Scale"] for component in components: with ui.HStack(): with ui.HStack(width=LABEL_PADDING): ui.Label(component, name="transform", width=50) self._create_control_state() ui.Spacer() # Field (X) all_axis = ["X", "Y", "Z"] colors = {"X": 0xFF5555AA, "Y": 0xFF76A371, "Z": 0xFFA07D4F} for axis in all_axis: with ui.HStack(): with ui.ZStack(width=15): ui.Rectangle( width=15, height=20, style={ "background_color": colors[axis], "border_radius": 3, "corner_flag": ui.CornerFlag.LEFT, }, ) ui.Label(axis, name="transform_label", alignment=ui.Alignment.CENTER) ui.FloatDrag(name="transform", min=-1000000, max=1000000, step=0.01) self._create_control_state(0) ui.Spacer(height=0) def _build_checked_header(self, collapsed, title): triangle_alignment = ui.Alignment.RIGHT_CENTER if not collapsed: triangle_alignment = ui.Alignment.CENTER_BOTTOM with ui.HStack(style={"HStack": {"margin_width": 15, "margin_height": 5}}): with ui.VStack(width=20): ui.Spacer() ui.Triangle( alignment=triangle_alignment, name="title", width=8, height=8, style={"background_color": 0xFFCCCCCC}, ) ui.Spacer() ui.Label(title, name="title", width=0) ui.Spacer() ui.CheckBox(width=10, name="whiteCheck").model.set_value(True) self._create_control_state() def _build_custom_callapsable_frame(self): with ui.CollapsableFrame( title="Light Property", style=CollapsableFrame_style, build_header_fn=self._build_checked_header ): with ui.VStack(spacing=12, name="frame_v_stack"): ui.Spacer(height=5) with ui.HStack(): ui.Label("Slider", name="label", width=LABEL_PADDING) ui.IntSlider(name="value_less", min=0, max=100, usingGauge=True).model.set_value(30) self._create_control_state() self._create_checkbox_control("Great UI", True) self._create_checkbox_control("Hard To Build", False) self._create_checkbox_control("Support very very very long checkbox label", True) ui.Spacer(height=0) def _build_dropdown_frame(self): with ui.Frame(): with ui.ZStack(): ui.Rectangle(name="frame_background") with ui.VStack(height=0, spacing=10, name="frame_v_stack"): ui.Spacer(height=5) for index in range(3): with ui.HStack(): ui.Label("Drop Down", name="label", width=LABEL_PADDING) ui.ComboBox(0, "Choice 1", "Choice 2", "Choice 3", height=10, name="choices") self._create_control_state() self._create_checkbox_control("Check Box", False) ui.Spacer(height=0) def _build_scale_and_bias_frame(self): with ui.CollapsableFrame(title="Scale And Bias Output", collapsed=False, style=CollapsableFrame_style): with ui.VStack(name="frame_v_stack"): with ui.HStack(): ui.Spacer(width=100) ui.Label("Scale", name="label", alignment=ui.Alignment.CENTER) ui.Spacer(width=10) ui.Label("Bias", name="label", alignment=ui.Alignment.CENTER) with ui.VStack(spacing=8): colors = ["Red", "Green", "Blue", "Alpha"] for color in colors: with ui.HStack(): ui.Label(color, name="label", width=LABEL_PADDING) ui.FloatSlider(name="value", min=0, max=2).model.set_value(1.0) self._create_control_state(6) ui.Spacer(width=20) ui.FloatSlider(name="value", min=-1.0, max=1.0).model.set_value(0.0) state = None if color == "Red": state = 2 elif color == "Blue": state = 5 else: state = 3 self._create_control_state(state) ui.Spacer(height=0) ui.Spacer(height=5) with ui.VStack(spacing=14): self._create_checkbox_control("Warp to Output Range", True) ui.Line(style={"color": KIT_GREEN}) self._create_checkbox_control("Border Color", True) self._create_checkbox_control("Zero Alpha Border", False) with ui.HStack(): self._create_checkbox_control("Cutout Alpha", False, label_width=20, line_width=20) self._create_checkbox_control("Scale Alpha For Mi Pmap Coverage", True) self._create_checkbox_control("Border Color", True) ui.Spacer(height=0) def _build_color_picker_frame(self): def color_drag(args): with ui.HStack(spacing=2): color_model = ui.MultiFloatDragField( args[0], args[1], args[2], width=200, h_spacing=5, name="colorField" ).model ui.ColorWidget(color_model, width=10, height=10) def color4_drag(args): with ui.HStack(spacing=2): color_model = ui.MultiFloatDragField( args[0], args[1], args[2], args[3], width=200, h_spacing=5, style={"color": 0xFFAAAAAA, "background_color": 0xFF000000, "draw_mode": ui.SliderDrawMode.HANDLE}, ).model ui.ColorWidget(color_model, width=10, height=10) with ui.CollapsableFrame(title="Color Controls", collapsed=False, style=CollapsableFrame_style): with ui.VStack(name="frame_v_stack"): with ui.VStack(spacing=8): colors = [("Red", [1.0, 0.0, 0.0]), ("Green", [0.0, 1.0, 0.0]), ("Blue", [0.0, 0.0, 1.0])] for color in colors: with ui.HStack(): ui.Label(color[0], name="label", width=LABEL_PADDING) if len(color[1]) == 4: color4_drag(color[1]) else: color_drag(color[1]) self._create_control_state(0) ui.Line(style={"color": 0x338A8777}) color = ("RGBA", [1.0, 0.0, 1.0, 0.5]) with ui.HStack(): ui.Label(color[0], name="label", width=LABEL_PADDING) color4_drag(color[1]) self._create_control_state(0) ui.Spacer(height=0) def _build_frame_with_radio_button(self): with ui.CollapsableFrame(title="Compression Quality", collapsed=False, style=CollapsableFrame_style): with ui.VStack(spacing=8, name="frame_v_stack"): ui.Spacer(height=5) with ui.HStack(): with ui.VStack(width=LABEL_PADDING): ui.Label(" Select One...", name="label", width=100, height=0) ui.Spacer(width=100) with ui.VStack(spacing=10): values = ["Faster", "Normal", "Production", "Highest"] for value in values: with ui.HStack(): with ui.ZStack(width=20): outer_style = { "border_width": 1, "border_color": KIT_GREEN, "background_color": 0x0, "border_radius": 2, } ui.Rectangle(width=12, height=12, style=outer_style) if value == "Faster": outer_style = {"background_color": KIT_GREEN, "border_radius": 2} with ui.Placer(offset_x=3, offset_y=3): ui.Rectangle(width=10, height=10, style=outer_style) ui.Label(value, name="label", aligment=ui.Alignment.LEFT) ui.Spacer(height=0) def build_window(self): """ build the window for the Class""" self._editor_window = ui.Window("Attribute Editor", width=450, height=800) self._editor_window.deferred_dock_in("Layers") self._editor_window.setPosition(0, 0) self._editor_window.frame.set_style(DARK_WINDOW_STYLE) with self._editor_window.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER) ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b)) ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b)) ui.Spacer() ui.Spacer(height=10) self._window_Frame = ui.ScrollingFrame( name="canvas", horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) with self._window_Frame: with ui.VStack(height=0, name="main_v_stack", spacing=6): # create object selection Frame self._create_object_selection_frame() # create build transform Frame self._build_transform_frame() # DropDown Frame self._build_dropdown_frame() # Custom Collapsable Frame self._build_custom_callapsable_frame() # Custom Collapsable Frame with ui.CollapsableFrame(title="Files", style=CollapsableFrame_style): with ui.VStack(spacing=10, name="frame_v_stack"): ui.Spacer(height=0) self._create_path_combo("UI Path", "omni:/Project/Cool_ui.usd") self._create_path_combo("Texture Path", "omni:/Project/cool_texture.png") ui.Spacer(height=0) # Custom Collapsable Frame with ui.CollapsableFrame(title="Images Options", collapsed=True, style=CollapsableFrame_style): with ui.VStack(spacing=10, name="frame_v_stack"): self._create_path_combo("Images Path", "omni:/Library/Images/") ui.Spacer(height=0) # Custom Collapsable Frame self._build_frame_with_radio_button() # Scale And Bias self._build_scale_and_bias_frame() # Color Pickrs self._build_color_picker_frame() return self._editor_window
23,430
Python
45.582505
119
0.509902
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/progressbar_doc.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. # """The documentation for ProgressBar""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage SPACING = 5 class CustomProgressValueModel(ui.AbstractValueModel): """An example of custom float model that can be used for progress bar""" def __init__(self, value: float): super().__init__() self._value = value def set_value(self, value): """Reimplemented set""" try: value = float(value) except ValueError: value = None if value != self._value: # Tell the widget that the model is changed self._value = value self._value_changed() def get_value_as_float(self): return self._value def get_value_as_string(self): return "Custom Overlay" class ProgressBarDoc(DocPage): """ document for ProgressBar""" def create_doc(self, navigate_to=None): self._section_title("ProgressBar") self._text("A progressbar is widget that indicates the progress of an operation.") self._text("In the following example, it shows how to use progress bar and override the overlay text.") with ui.VStack(spacing=SPACING): # Create progressbars first = ui.ProgressBar() # Range is [0.0, 1.0] first.model.set_value(0.5) second = ui.ProgressBar() second.model.set_value(1.0) # Overrides the overlay of progressbar model = CustomProgressValueModel(0.8) third = ui.ProgressBar(model) third.model.set_value(0.1) # Styling its color fourth = ui.ProgressBar(style={"color": cl("#0000DD")}) fourth.model.set_value(0.3) # Styling its border width ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7) # Styling its border radius ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6) # Styling its background color ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6) # Styling the text color ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6) # Two progress bars in a row with padding with ui.HStack(): ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0) ui.ProgressBar().model.set_value(0.0) self._code( """ # Create progressbars first = ui.ProgressBar() # Range is [0.0, 1.0] first.model.set_value(0.5) second = ui.ProgressBar() second.model.set_value(1.0) # Overrides the overlay of progressbar model = CustomProgressValueModel(0.8) third = ui.ProgressBar(model) third.model.set_value(0.1) # Styling its color fourth = ui.ProgressBar(style={"color": cl("#0000DD")}) fourth.model.set_value(0.3) # Styling its border width ui.ProgressBar(style={"border_width": 2, "color": cl("#0000DD")}).model.set_value(0.7) # Styling its border radius ui.ProgressBar(style={"border_radius": 100, "color": cl("#0000DD")}).model.set_value(0.6) # Styling its background color ui.ProgressBar(style={"border_radius": 100, "background_color": cl("#0000DD")}).model.set_value(0.6) # Styling the text color ui.ProgressBar(style={"border_radius": 100, "secondary_color": cl("#00DDDD")}).model.set_value(0.6) # Two progress bars in a row with padding with ui.HStack(): ui.ProgressBar(style={"color": cl("#0000DD"), "padding": 100}).model.set_value(1.0) ui.ProgressBar().model.set_value(0.0) """ ) ui.Spacer(height=10)
4,492
Python
34.377952
112
0.592164
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/menu_doc.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. # """The documentation for Menu""" from omni import ui from .doc_page import DocPage class MenuDoc(DocPage): """ document for Menu""" def __init__(self, extension_path): super().__init__(extension_path) self._context_menu = ui.Menu( "Context menu", name="this", style={ "Menu": {"background_color": 0xFFAA0000, "color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00}, "MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFF00AA00}, "Separator": {"color": 0xFFFFFFFF}, }, ) self._pushed_menu = ui.Menu( "Pushed menu", style={ "Menu": {"background_color": 0xFF000000, "color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA}, "MenuItem": {"color": 0xFFFFFFFF, "background_selected_color": 0xFFAAAAAA}, }, ) def _show_context_menu(self, x, y, button, modifier): """The context menu example""" # Display context menu only if the right button is pressed if button != 1: return # Reset the previous context popup self._context_menu.clear() with self._context_menu: ui.MenuItem("Delete Shot") ui.Separator() ui.MenuItem("Attach Selected Camera") with ui.Menu("Sub-menu"): ui.MenuItem("One") ui.MenuItem("Two") ui.MenuItem("Three") ui.Separator() ui.MenuItem("Four") with ui.Menu("Five"): ui.MenuItem("Six") ui.MenuItem("Seven") # Show it self._context_menu.show() def _show_pushed_menu(self, x, y, button, modifier, widget): """The Pushed menu example""" # Display context menu only if the left mouse button is pressed if button != 0: return # Reset the previous context popup self._pushed_menu.clear() with self._pushed_menu: ui.MenuItem("Camera 1") ui.MenuItem("Camera 2") ui.MenuItem("Camera 3") ui.Separator() with ui.Menu("More Cameras"): ui.MenuItem("This Menu is Pushed") ui.MenuItem("and Aligned with a widget") # Show it self._pushed_menu.show_at( (int)(widget.screen_position_x), (int)(widget.screen_position_y + widget.computed_content_height) ) def create_doc(self, navigate_to=None): self._section_title("Menu") self._text( "The Menu class provides a menu widget for use in menu bars, context menus, and other popup menus. It can " "be either a pull-down menu in a menu bar or a standalone context menu. Pull-down menus are shown by the " "menu bar when the user clicks on the respective item. Context menus are usually invoked by some special " "keyboard key or by right-clicking." ) with ui.HStack(style=self._style_system): ui.Button("Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu) self._code( """ def _on_startup(self): .... with ui.HStack(style=style_system): ui.Button( "Right click to context menu", width=0, mouse_pressed_fn=self._show_context_menu ) .... def _show_context_menu(self, x, y, button, modifier): # Display context menu only if the right button is pressed if button != 1: return # Reset the previous context popup self._context_menu.clear() with self._context_menu: with ui.Menu("Sub-menu"): ui.MenuItem("One") ui.MenuItem("Two") ui.MenuItem("Three") ui.MenuItem("Four") with ui.Menu("Five"): ui.MenuItem("Six") ui.MenuItem("Seven") ui.MenuItem("Delete Shot") ui.MenuItem("Attach Selected Camera") """ ) with ui.HStack(style=self._style_system): bt = ui.Button("Pushed Button Menu", width=0, style={"background_color": 0xFF000000, "color": 0xFFFFFFFF}) bt.set_mouse_pressed_fn(lambda x, y, b, m, widget=bt: self._show_pushed_menu(x, y, b, m, widget)) ui.Spacer(height=100)
5,068
Python
36
119
0.547948
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/md_doc.py
# Copyright (c) 2018-2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .doc_page import DocPage from omni.kit.documentation.builder import DocumentationBuilderMd from omni.kit.documentation.builder import DocumentationBuilderPage class MdDoc(DocPage): def __init__(self, extension_path, md: DocumentationBuilderMd): super().__init__(extension_path) self.__md = md self.__page = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" if self.__page: self.__page.destroy() self.__page = None def create_doc(self, navigate_to=None): """Issue the UI""" self.__page = DocumentationBuilderPage(self.__md, navigate_to)
1,108
Python
35.966665
76
0.710289
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/abstract_model_doc.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. # """The documentation for Abstract Model """ from omni import ui from pxr import UsdGeom import omni.kit.commands import omni.usd from .doc_page import DocPage SPACING = 5 class VisibilityWatchModel(ui.AbstractValueModel): """The value model that is reimplemented in Python to watch the visibility of the selection""" def __init__(self): super(VisibilityWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._selection = None self._events = None self._stage_event_sub = None if self._usd_context is not None: self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui abstract model stage update" ) self.prim = None def clean(self): """Should be called when the extesion us unloaded or reloaded""" self._usd_context = None self._selection = None self._events = None self._stage_event_sub = None self.prim = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() # When TC runs tests, it's possible that stage is None if selection and stage: self.prim = stage.GetPrimAtPath(selection[0]) # Say to the widgets that the model value is changed self._value_changed() def get_value_as_bool(self): """Reimplemented get bool""" if self.prim: if self.prim.HasAttribute(UsdGeom.Tokens.visibility): attribute = self.prim.GetAttribute(UsdGeom.Tokens.visibility) if attribute: return attribute.Get() == UsdGeom.Tokens.inherited def set_value(self, value): """Reimplemented set bool""" if self.prim: omni.kit.commands.execute("ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()]) # Say to the widgets that the model value is changed self._value_changed() class AbstractModelDoc(DocPage): """ document for CheckBox""" def __init__(self, extension_path): super().__init__(extension_path) self._visibility_model = VisibilityWatchModel() def clean(self): """Should be called when the extesion us unloaded or reloaded""" # Unfortunatley, the member variables are not destroyed when the extension is unloaded. We need to do it # automatically. Usually, it's OK because the Python garbage collector will eventually destroy everythigng. But # we need the images to be destroyed right now because Kit know nothing about Python garbage collector and it # will fire warning that texture is not destroyed. if self._visibility_model: self._visibility_model.clean() self._visibility_model = None def create_doc(self, navigate_to=None): self._section_title("AbstractValueModel") self._text( "The AbstractValueModel class provides an abstract interface for the model that holds a single value. It's " "a central component of the model-delegate-view pattern used in many widgets like CheckBox, StringField(TODO), " "Slider(TODO), RadioBox(TODO). It's a dynamic data structure independent of the widget implementation. And " "it holds the data, logic, and rules of the widgets and defines the standard interface that widgets must " "use to be able to interoperate with the data model. It is not supposed to be instantiated directly. " "Instead, the user should subclass it to create new models." ) self._text( "In the next example, AbstractValueModel class is reimplemented to provide control over the visibility of " "the selected object." ) with ui.HStack(width=0, spacing=SPACING): ui.CheckBox(self._visibility_model) self._text("Visibility of Selected Prim") self._code( """ class VisibilityWatchModel(ui.AbstractValueModel): ''' The value model that is reimplemented in Python to watch the visibility of the selection. ''' def __init__(self): super(VisibilityWatchModel, self).__init__() self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = \\ self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui visibilitywatch stage update") self.prim = None def _on_stage_event(self, event): if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() if selection and stage: self.prim = stage.GetPrimAtPath(selection[0]) # Say to the widgets that the model value is changed self._value_changed() def get_value_as_bool(self): '''Reimplemented get bool''' if self.prim: attribute = \\ UsdGeom.Imageable(self.prim).GetVisibilityAttr() inherited = \\ attribute.Get() == UsdGeom.Tokens.inherited return inherited if attribute else False def set_value(self, value): '''Reimplemented set bool''' if self.prim: omni.kit.commands.execute( "ToggleVisibilitySelectedPrims", selected_paths=[self.prim.GetPath()]) # Say to the widgets that the model value is changed self._value_changed() """ ) ui.Spacer(height=10)
6,940
Python
41.32317
124
0.610375
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/field_doc.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. # """The documentation for Field """ from .doc_page import DocPage from omni import ui import inspect SPACING = 5 def field_callbacks(): def on_value(label): label.text = "Value is changed" def on_begin(label): label.text = "Editing is started" def on_end(label): label.text = "Editing is finished" label = ui.Label("Nothing happened", name="text") model = ui.StringField().model model.add_value_changed_fn(lambda m, l=label: on_value(l)) model.add_begin_edit_fn(lambda m, l=label: on_begin(l)) model.add_end_edit_fn(lambda m, l=label: on_end(l)) def multiline_field(): initial_text = inspect.getsource(field_callbacks) model = ui.SimpleStringModel(initial_text) field = ui.StringField(model, multiline=True) class FieldDoc(DocPage): """ document for Field""" def create_doc(self, navigate_to=None): self._section_title("Field") self._caption("StringField", navigate_to) self._text( "The StringField widget is a one-line text editor. A field allows the user to enter and edit a single line " "of plain text. It's implemented using the model-delegate-view pattern and uses AbstractValueModel as the central " "component of the system." ) self._text("The following example demonstrates the way how to connect a StringField and a Label.") field_style = { "Field": { "background_color": 0xFFFFFFFF, "background_selected_color": 0xFFD77800, "border_color": 0xFF444444, "border_radius": 1, "border_width": 0.5, "color": 0xFF444444, "font_size": 16.0, }, "Field:hovered": {"border_color": 0xFF000000}, "Field:pressed": {"background_color": 0xFFFFFFFF, "border_color": 0xFF995400, "border_width": 0.75}, } def setText(label, text): """Sets text on the label""" # This function exists because lambda cannot contain assignment label.text = f"You wrote '{text}'" with ui.HStack(): field = ui.StringField(style=field_style) ui.Spacer(width=SPACING) label = ui.Label("", name="text") field.model.add_value_changed_fn(lambda m, label=label: setText(label, m.get_value_as_string())) self._code( """ def setText(label, text): '''Sets text on the label''' # This function exists because lambda cannot contain assignment label.text = f"You wrote '{text}'" with ui.HStack(): field = ui.StringField(style=field_style) label = ui.Label("") field.model.add_value_changed_fn( lambda m, label=label: setText(label, m.get_value_as_string())) """ ) self._text( "The following example demonstrates that the model decides the content of the field. The field can have " "only one of two options, either 'True' or 'False' because the model supports only those two possibilities." ) with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() field.model = checkbox.model self._code( """ with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() field.model = checkbox.model """ ) self._text( "In this example, the field can have anything because the model accepts any string, but the model returns " "bool for checkbox, and the checkbox is off when the string is empty or 'False'." ) with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() checkbox.model = field.model self._code( """ with ui.HStack(): checkbox = ui.CheckBox(width=0) field = ui.StringField() checkbox.model = field.model """ ) self._caption("FloatField and IntField", navigate_to) self._text( "There are fields for string, float and int models. The following example shows how they interact with " "each other:" ) self._text("All three fields share the same SimpleFloatModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() center.model = left.model right.model = left.model self._text("All three fields share the same SimpleIntModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() left.model = center.model right.model = center.model self._text("All three fields share the same SimpleStringModel:") with ui.HStack(): self._text("FloatField") self._text("IntField") self._text("StringField") with ui.HStack(): left = ui.FloatField() center = ui.IntField() right = ui.StringField() left.model = right.model center.model = right.model self._text( "The widget doesn't keep the data due to the model-delegate-view pattern. However, there are two ways to track the " "state of the widget. It's possible to reimplement AbstractValueModel, for details see the chapter " "`AbstractValueModel`. The second way is using the callbacks of the model. This is a minimal example " "of callbacks." ) field_callbacks() self._code(inspect.getsource(field_callbacks).split("\n", 1)[-1]) self._caption("Multiline StringField", navigate_to) self._text( "Property `multiline` of `StringField` allows to press enter and create a new line. It's possible to " "finish editing with Ctrl-Enter." ) with ui.Frame(style=field_style, height=300): multiline_field() self._code(inspect.getsource(multiline_field).split("\n", 1)[-1]) ui.Spacer(height=10)
7,030
Python
34.155
128
0.582077
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/multifield_doc.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. # """The documentation for Shapes""" from omni import ui from .doc_page import DocPage import inspect import omni.usd from .colorwidget_doc import USDColorModel SPACING = 5 def simplest_field(): ui.MultiIntField(0, 0, 0, 0) def simplest_drag(): ui.MultiFloatDragField(0.0, 0.0, 0.0, 0.0) def matrix_field(): args = [1.0 if i % 5 == 0 else 0.0 for i in range(16)] ui.MultiFloatField(*args, width=ui.Percent(50), h_spacing=5, v_spacing=2) def usd_field(): with ui.HStack(spacing=SPACING): model = USDColorModel() ui.ColorWidget(model, width=0) ui.MultiFloatField(model) def usd_drag(): with ui.HStack(spacing=SPACING): model = USDColorModel() ui.ColorWidget(model, width=0) ui.MultiFloatDragField(model, min=0.0, max=2.0) class MultiFieldDoc(DocPage): """Document for MultiField""" def create_doc(self, navigate_to=None): """Descriptions for MultiField""" self._section_title("MultiField") self._text( "MultiField widget groups are the widgets that have multiple similar widgets to represent each item in the " "model. It's handy to use them for arrays and multi-component data like float3, matrix, and color." ) simplest_field() self._code(inspect.getsource(simplest_field).split("\n", 1)[-1]) simplest_drag() self._code(inspect.getsource(simplest_drag).split("\n", 1)[-1]) matrix_field() self._code(inspect.getsource(matrix_field).split("\n", 1)[-1]) # TODO omni.ui: restore functionality for Kit Next if False: usd_field() self._code(inspect.getsource(usd_field).split("\n", 1)[-1]) usd_drag() self._code(inspect.getsource(usd_drag).split("\n", 1)[-1])
2,255
Python
28.68421
120
0.659867
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/colorwidget_doc.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. # """The documentation for ColorWidget""" from .doc_page import DocPage from omni import ui from pxr import Gf from pxr import UsdGeom from typing import Any import inspect import omni.kit.commands import omni.usd import weakref SPACING = 5 class SetDisplayColorCommand(omni.kit.commands.Command): """ Change prim display color undoable **Command**. Unlike ChangePropertyCommand, it can undo property creation. Args: gprim (Gprim): Prim to change display color on. value: Value to change to. value: Value to undo to. """ def __init__(self, gprim: UsdGeom.Gprim, color: Any, prev: Any): self._gprim = gprim self._color = color self._prev = prev def do(self): color_attr = self._gprim.CreateDisplayColorAttr() color_attr.Set([self._color]) def undo(self): color_attr = self._gprim.GetDisplayColorAttr() if self._prev is None: color_attr.Clear() else: color_attr.Set([self._prev]) class FloatModel(ui.SimpleFloatModel): def __init__(self, parent): super().__init__() self._parent = weakref.ref(parent) def begin_edit(self): parent = self._parent() parent.begin_edit(None) def end_edit(self): parent = self._parent() parent.end_edit(None) class USDColorItem(ui.AbstractItem): def __init__(self, model): super().__init__() self.model = model class USDColorModel(ui.AbstractItemModel): def __init__(self): super().__init__() # Create root model self._root_model = ui.SimpleIntModel() self._root_model.add_value_changed_fn(lambda a: self._item_changed(None)) # Create three models per component self._items = [USDColorItem(FloatModel(self)) for i in range(3)] for item in self._items: item.model.add_value_changed_fn(lambda a, item=item: self._on_value_changed(item)) # Omniverse contexts self._usd_context = omni.usd.get_context() self._selection = self._usd_context.get_selection() self._events = self._usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="omni.example.ui colorwidget stage update" ) # Privates self._subscription = None self._gprim = None self._prev_color = None self._edit_mode_counter = 0 def _on_stage_event(self, event): """Called with subscription to pop""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_selection_changed() def _on_selection_changed(self): """Called when the user changes the selection""" selection = self._selection.get_selected_prim_paths() stage = self._usd_context.get_stage() self._subscription = None self._gprim = None # When TC runs tests, it's possible that stage is None if selection and stage: self._gprim = UsdGeom.Gprim.Get(stage, selection[0]) if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() usd_watcher = omni.usd.get_watcher() self._subscription = usd_watcher.subscribe_to_change_info_path( color_attr.GetPath(), self._on_usd_changed ) # Change the widget color self._on_usd_changed() def _on_value_changed(self, item): """Called when the submodel is chaged""" if not self._gprim: return if self._edit_mode_counter > 0: # Change USD only if we are in the edit mode. color_attr = self._gprim.CreateDisplayColorAttr() color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) color_attr.Set([color]) self._item_changed(item) def _on_usd_changed(self, path=None): """Called with UsdWatcher when something in USD is changed""" color = self._get_current_color() or Gf.Vec3f(0.0) for i in range(len(self._items)): self._items[i].model.set_value(color[i]) def _get_current_color(self): """Returns color of the current object""" if self._gprim: color_attr = self._gprim.GetDisplayColorAttr() if color_attr: color_array = color_attr.Get() if color_array: return color_array[0] def get_item_children(self, item): """Reimplemented from the base class""" return self._items def get_item_value_model(self, item, column_id): """Reimplemented from the base class""" if item is None: return self._root_model return item.model def begin_edit(self, item): """ Reimplemented from the base class. Called when the user starts editing. """ if self._edit_mode_counter == 0: self._prev_color = self._get_current_color() self._edit_mode_counter += 1 def end_edit(self, item): """ Reimplemented from the base class. Called when the user finishes editing. """ self._edit_mode_counter -= 1 if not self._gprim or self._edit_mode_counter > 0: return color = Gf.Vec3f( self._items[0].model.get_value_as_float(), self._items[1].model.get_value_as_float(), self._items[2].model.get_value_as_float(), ) omni.kit.commands.execute("SetDisplayColor", gprim=self._gprim, color=color, prev=self._prev_color) def color_field(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(width=0, height=0).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatField(component) def color_drag(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatDrag(component) def color_combo(): with ui.HStack(spacing=SPACING): color_model = ui.ColorWidget(width=0, height=0).model ui.ComboBox(color_model) def two_usd_color_boxes(): with ui.HStack(spacing=SPACING): ui.ColorWidget(USDColorModel(), width=0) ui.Label("First ColorWidget", name="text") with ui.HStack(spacing=SPACING): ui.ColorWidget(USDColorModel(), width=0) ui.Label("Second ColorWidget has independed model", name="text") class ColorWidgetDoc(DocPage): """Document for ColorWidget""" def create_doc(self, navigate_to=None): self._section_title("ColorWidget") self._text( "The ColorWidget widget is a button that displays the color from the item model and can open a picker " "window. The color dialog's function is to allow users to choose colors." ) self._text("Fields connected to the color model") color_field() self._code(inspect.getsource(color_field).split("\n", 1)[-1]) self._text("Drags connected to the color model") color_drag() self._code(inspect.getsource(color_drag).split("\n", 1)[-1]) self._text("ComboBox connected to the color model.") color_combo() self._code(inspect.getsource(color_combo).split("\n", 1)[-1]) # TODO omni.ui: restore functionality for Kit Next if False: self._text("Two different models that watch USD Stage. Undo/Redo example.") two_usd_color_boxes() with ui.ScrollingFrame(height=250, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON): self._code( inspect.getsource(FloatModel) + "\n" + inspect.getsource(USDColorItem) + "\n" + inspect.getsource(USDColorModel) + "\n" + inspect.getsource(two_usd_color_boxes) ) ui.Spacer(height=20)
8,824
Python
31.806691
115
0.600748
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/widget_doc.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. # """The documentation for Widget""" from .doc_page import DocPage from omni import ui from omni.ui import color as cl from pathlib import Path import inspect import random SPACING = 5 def tooltip_fixed_position(): ui.Button("Fixed-position Tooltip", width=200, tooltip="Hello World", tooltip_offset_y=22) def tooltip_random_position(): button = ui.Button("Random-position Tooltip", width=200, tooltip_offset_y=22) def create_tooltip(button=button): button.tooltip_offset_x = random.randint(0, 200) ui.Label("Hello World") button.set_tooltip_fn(create_tooltip) def image_button(): style = { "Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM}, "Button.Image": { "color": cl("#99CCFF"), "image_url": "resources/icons/Learn_128.png", "alignment": ui.Alignment.CENTER, }, "Button.Label": {"alignment": ui.Alignment.CENTER}, } def direction(model, button, style=style): value = model.get_item_value_model().get_value_as_int() direction = ( ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.BACK_TO_FRONT, ui.Direction.FRONT_TO_BACK, )[value] style["Button"]["stack_direction"] = direction button.set_style(style) def align(model, button, image, style=style): value = model.get_item_value_model().get_value_as_int() alignment = ( ui.Alignment.LEFT_TOP, ui.Alignment.LEFT_CENTER, ui.Alignment.LEFT_BOTTOM, ui.Alignment.CENTER_TOP, ui.Alignment.CENTER, ui.Alignment.CENTER_BOTTOM, ui.Alignment.RIGHT_TOP, ui.Alignment.RIGHT_CENTER, ui.Alignment.RIGHT_BOTTOM, )[value] if image: style["Button.Image"]["alignment"] = alignment else: style["Button.Label"]["alignment"] = alignment button.set_style(style) def layout(model, button, padding, style=style): padding = "padding" if padding else "margin" style["Button"][padding] = model.get_value_as_float() button.set_style(style) def spacing(model, button): button.spacing = model.get_value_as_float() button = ui.Button("Label", style=style, width=64, height=64) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button": {"stack_direction"}', name="text") options = ( 0, "TOP_TO_BOTTOM", "BOTTOM_TO_TOP", "LEFT_TO_RIGHT", "RIGHT_TO_LEFT", "BACK_TO_FRONT", "FRONT_TO_BACK", ) model = ui.ComboBox(*options).model model.add_item_changed_fn(lambda m, i, b=button: direction(m, b)) alignment = ( 4, "LEFT_TOP", "LEFT_CENTER", "LEFT_BOTTOM", "CENTER_TOP", "CENTER", "CENTER_BOTTOM", "RIGHT_TOP", "RIGHT_CENTER", "RIGHT_BOTTOM", ) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Image": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label('"Button.Label": {"alignment"}', name="text") model = ui.ComboBox(*alignment).model model.add_item_changed_fn(lambda m, i, b=button: align(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("padding", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("Button.spacing", name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m, b=button: spacing(m, b)) class WidgetDoc(DocPage): """ document for Widget""" def radio_button(self): style = { "": {"background_color": cl.transparent, "image_url": f"{self._extension_path}/icons/radio_off.svg"}, ":checked": {"image_url": f"{self._extension_path}/icons/radio_on.svg"}, } collection = ui.RadioCollection() for i in range(5): with ui.HStack(style=style): ui.RadioButton(radio_collection=collection, width=30, height=30) ui.Label(f"Option {i}", name="text") ui.IntSlider(collection.model, min=0, max=4) def create_doc(self, navigate_to=None): self._section_title("Widgets") self._text( "The widget provides all the base functionality for most ui elements" "There is a lot of default feature " ) self._caption("Button", navigate_to) self._text( "The Button widget provides a command button. The command button, is perhaps the most commonly used widget " "in any graphical user interface. Click a button to execute a command. It is rectangular and typically " "displays a text label describing its action." ) def make_longer_text(button): """Set the text of the button longer""" button.text = "Longer " + button.text def make_shorter_text(button): """Set the text of the button shorter""" splitted = button.text.split(" ", 1) button.text = splitted[1] if len(splitted) > 1 else splitted[0] with ui.HStack(style=self._style_system): btn_with_text = ui.Button("Text", width=0) ui.Button("Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b)) btn_with_text.set_clicked_fn(lambda b=btn_with_text: make_shorter_text(b)) self._code( """ def make_longer_text(button): '''Set the text of the button longer''' button.text = "Longer " + button.text def make_shorter_text(button): '''Set the text of the button shorter''' splitted = button.text.split(" ", 1) button.text = \\ splitted[1] if len(splitted) > 1 else splitted[0] with ui.HStack(style=style_system): btn_with_text = ui.Button("Text", width=0) ui.Button( "Press me", width=0, clicked_fn=lambda b=btn_with_text: make_longer_text(b) ) btn_with_text.set_clicked_fn( lambda b=btn_with_text: make_shorter_text(b)) """ ) image_button() self._code(inspect.getsource(image_button).split("\n", 1)[-1]) self._caption("RadioButton", navigate_to) self._text( "RadioButton is the widget that allows the user to choose only one of a predefined set of mutually " "exclusive options." ) self._text( "RadioButtons are arranged in collections of two or more with the class RadioGroup, which is the central " "component of the system and controls the behavior of all the RadioButtons in the collection." ) self.radio_button() self._code(inspect.getsource(self.radio_button).split("\n", 1)[-1]) self._caption("Label", navigate_to) self._text( "Labels are used everywhere in omni.ui. They are text-only objects, and don't have a background color" "But you can control the color, font_size and alignment in the styling." ) self._exec_code( """ ui.Label("this is a simple label", style={"color": cl.black}) """ ) self._exec_code( """ ui.Label("label with aligment", style={"color": cl.black}, alignment=ui.Alignment.CENTER) """ ) self._exec_code( """ label_style = {"Label": {"font_size": 16, "color": cl.blue, "alignment":ui.Alignment.RIGHT }} ui.Label("Label with style", style=label_style) """ ) self._exec_code( """ ui.Label( "Label can be elided: Lorem ipsum dolor " "sit amet, consectetur adipiscing elit, sed do " "eiusmod tempor incididunt ut labore et dolore " "magna aliqua. Ut enim ad minim veniam, quis " "nostrud exercitation ullamco laboris nisi ut " "aliquip ex ea commodo consequat. Duis aute irure " "dolor in reprehenderit in voluptate velit esse " "cillum dolore eu fugiat nulla pariatur. Excepteur " "sint occaecat cupidatat non proident, sunt in " "culpa qui officia deserunt mollit anim id est " "laborum.", style={"color":cl.black}, elided_text=True, ) """ ) self._caption("Tooltip", navigate_to) self._text( "All Widget can be augmented with a tooltip, it can take 2 forms, either a simple ui.Label or a callback" "when using the callback, tooltip_fn= or widget.set_tooltip_fn() you can create virtually any widget for " "the tooltip" ) self._exec_code( """ tooltip_style = { "Tooltip": {"background_color": cl("#DDDD00"), "color": cl("#333333"), "margin_width": 3 , "margin_height": 2 , "border_width":3, "border_color": cl.red }} ui.Button("Simple Label Tooltip", name="tooltip", width=200, tooltip=" I am a text ToolTip ", style=tooltip_style) """ ) self._exec_code( """ def create_tooltip(): with ui.VStack(width=200, style=tooltip_style): with ui.HStack(): ui.Label("Fancy tooltip", width=150) ui.IntField().model.set_value(12) ui.Line(height=2, style={"color": cl.white}) with ui.HStack(): ui.Label("Anything is possible", width=150) ui.StringField().model.set_value("you bet") image_source = "resources/desktop-icons/omniverse_512.png" ui.Image( image_source, width=200, height=200, alignment=ui.Alignment.CENTER, style={"margin": 0}, ) tooltip_style = { "Tooltip": {"background_color": cl("#444444"), "border_width":2, "border_radius":5}, } ui.Button("Callback function Tooltip", width=200, style=tooltip_style, tooltip_fn=create_tooltip) """ ) tooltip_fixed_position() self._code(inspect.getsource(tooltip_fixed_position).split("\n", 1)[-1]) tooltip_random_position() self._code(inspect.getsource(tooltip_random_position).split("\n", 1)[-1]) ui.Spacer(height=50) self._caption("Debug Color", navigate_to) self._text("All Widget can be styled to use a debug color that enable you to visualize their frame") self._exec_code( """ style = {"background_color": cl("#DDDD00"), "color": cl("#333333"), "debug_color": cl("#FF000022") } ui.Label("Label with Debug", width=200, style=style) """ ) self._exec_code( """ style = {":hovered": {"debug_color": cl("#00FFFF22") }, "Label": {"padding": 3, "background_color": cl("#DDDD00"), "color": cl("#333333"), "debug_color": cl("#0000FF22") }} with ui.HStack(width=500, style=style): ui.Label("Label 1", width=50) ui.Label("Label 2") ui.Label("Label 3", width=100, alignment=ui.Alignment.CENTER) ui.Spacer() ui.Label("Label 3", width=50) """ ) self._caption("Font", navigate_to) self._text( "It's possible to set the font of the label using styles. The style key 'font' should point to the font " "file, which allows packaging of the font to the extension. We support both TTF and OTF formats. " "All text-based widgets support custom fonts." ) self._exec_code( """ ui.Label( "The quick brown fox jumps over the lazy dog", style={ "font_size": 55, "font": "${fonts}/OpenSans-SemiBold.ttf", "alignment": ui.Alignment.CENTER }, word_wrap=True, ) """ ) ui.Spacer(height=10)
13,547
Python
34.465968
120
0.552668
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/plot_doc.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. # """The documentation for Menu""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import math class PlotDoc(DocPage): """ document for Plot""" def __init__(self, extension_path): super().__init__(extension_path) self._data = [] for i in range(360): self._data.append(math.cos(math.radians(i))) def create_doc(self, navigate_to=None): self._section_title("Plot") self._text("The Plot class displayes a line or histogram image.") self._text("The data of image is specified as a data array or a provider function.") ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red}) self._code( """ self._data = [] for i in range(360): self._data.append(math.cos(math.radians(i))) ui.Plot(ui.Type.LINE, -1.0, 1.0, *self._data, width=360, height=100, style={"color": cl.red}) """ ) plot = ui.Plot( ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue}, ) plot.value_stride = 6 self._code( """ def _on_data_provider(self, index): return math.sin(math.radians(index)) plot = ui.Plot(ui.Type.HISTOGRAM, -1.0, 1.0, self._on_data_provider, 360, width=360, height=100, style={"color": cl.blue}) plot.value_stride = 6 """ ) ui.Spacer(height=100) def _on_data_provider(self, index): return math.sin(math.radians(index))
2,140
Python
29.585714
130
0.590187
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/styling_doc.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. # """The documentation for Styling""" from .doc_page import DocPage from functools import partial from omni import ui from omni.ui import color as cl from omni.ui import constant as fl from omni.ui import url import inspect SPACING = 5 def named_shades(): def set_color(color): cl.example_color = color def set_width(value): fl.example_width = value cl.example_color = cl.green fl.example_width = 1.0 with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.shade( "aqua", orange=cl.orange, another=cl.example_color, transparent=cl.transparent, black=cl.black, ), "border_width": fl.shade(1, orange=4, another=8), "border_radius": fl.one, "border_color": cl.black, }, ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color":\n' "\t\t\tcl.shade(\n" '\t\t\t\t"aqua",\n' "\t\t\t\torange=cl(1, 0.5, 0),\n" "\t\t\t\tanother=cl.example_color),\n" '\t\t"border_width":\n' "\t\t\tfl.shade(1, orange=4, another=8)})", alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.Rectangle( style={ "background_color": cl.example_color, "border_width": fl.example_width, "border_radius": fl.one, "border_color": cl.black, } ) ui.Label( "ui.Rectangle(\n" "\tstyle={\n" '\t\t"background_color": cl.example_color,\n' '\t\t"border_width": fl.example_width)})', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.HStack(): ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, "")) ui.Button('ui.set_shade("orange")', clicked_fn=partial(ui.set_shade, "orange")) ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another")) with ui.HStack(): ui.Button("fl.example_width = 1", clicked_fn=partial(set_width, 1)) ui.Button("fl.example_width = 4", clicked_fn=partial(set_width, 4)) with ui.HStack(): ui.Button('cl.example_color = "green"', clicked_fn=partial(set_color, "green")) ui.Button("cl.example_color = cl(0.8)", clicked_fn=partial(set_color, cl(0.8))) def url_shades(): def set_url(url_path: str): url.example_url = url_path walk = "resources/icons/Nav_Walkmode.png" fly = "resources/icons/Nav_Flymode.png" url.example_url = walk with ui.HStack(height=100, spacing=5): with ui.ZStack(): ui.Image(style={"image_url": url.example_url}) ui.Label( 'ui.Image(\n\tstyle={"image_url": cl.example_url})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.ZStack(): ui.ImageWithProvider( style={ "image_url": url.shade( "resources/icons/Move_local_64.png", another="resources/icons/Move_64.png", orange="resources/icons/Rotate_local_64.png", ) } ) ui.Label( "ui.ImageWithProvider(\n" "\tstyle={\n" '\t\t"image_url":\n' "\t\t\tst.shade(\n" '\t\t\t\t"Move_local_64.png",\n' '\t\t\t\tanother="Move_64.png")})\n', alignment=ui.Alignment.CENTER, word_wrap=True, style={"color": cl.black, "margin": 15}, ) with ui.HStack(): ui.Button("ui.set_shade()", clicked_fn=partial(ui.set_shade, "")) ui.Button('ui.set_shade("another")', clicked_fn=partial(ui.set_shade, "another")) with ui.HStack(): ui.Button("url.example_url = Nav_Walkmode.png", clicked_fn=partial(set_url, walk)) ui.Button("url.example_url = Nav_Flymode.png", clicked_fn=partial(set_url, fly)) def font_size(): def value_changed(label, value): label.style = {"color": ui.color(0), "font_size": value.as_float} slider = ui.FloatSlider(min=1.0, max=150.0) slider.model.as_float = 10.0 label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0}) slider.model.add_value_changed_fn(partial(value_changed, label)) class StylingDoc(DocPage): """ document for Styling workflow""" def create_doc(self, navigate_to=None): self._section_title("Styling") self._caption("The Style Sheet Syntax", navigate_to) self._text( "OMNI.UI Style Sheet rules are almost identical to those of HTML CSS. Style sheets consist of a sequence " "of style rules. A style rule is made up of a selector and a declaration. The selector specifies which " "widgets are affected by the rule; the declaration specifies which properties should be set on the widget. " "For example:" ) with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}): ui.Button("Style Example") self._code( """ with ui.VStack(width=0, style={"Button": {"background_color": cl("#097EFF")}}): ui.Button("Style Example") """ ) self._text( 'In the above style rule, Button is the selector, and { "background_color": cl("#097EFF") } is the ' "declaration. The rule specifies that Button should use blue as its background color." ) with ui.VStack(): self._table("Selector", "Example", "Explanation", cl.black) self._table("Type Selector", "Button", "Matches instances of Button.") self._table( "Name Selector", "Button::okButton", "Matches all Button instances whose object name is okButton." ) self._table( "State Selector", "Button:hovered", "Matches all Button instances whose state is hovered. It means the mouse should be in the widget area. " "Pseudo-states appear at the end of the selector, with a colon (:) in between. The supported states are " "hovered and pressed.", ) self._text("It's possible to omit the selector and override the property in all the widget types:") with ui.VStack(width=0, style={"background_color": cl("#097EFF")}): ui.Button("Style Example") self._code( """ with ui.VStack(width=0, style={"background_color": cl("#097EFF")}): ui.Button("Style Example") """ ) self._text( "The difference with the previous button is that all the colors, including pressed color and hovered " "color, are overridden." ) style1 = { "Button": {"border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0}, "Button::one": { "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA"), "border_color": cl("#1D76FD"), }, "Button.Label::one": {"color": cl.white}, "Button::one:hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}, "Button::one:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}, "Button::two": {"background_color": cl.white, "border_color": cl("#B1B1B1")}, "Button.Label::two": {"color": cl("#272727")}, "Button::three:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF"), "border_color": cl("#1D76FD"), }, "Button::four:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF"), "border_color": cl("#1D76FD"), }, } with ui.HStack(style=style1): ui.Button("One", name="one") ui.Button("Two", name="two") ui.Button("Three", name="three") ui.Button("Four", name="four") ui.Button("Five", name="five") self._code( """ style1 = { "Button": { "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0 }, "Button::one": { "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA"), "border_color": cl("#1D76FD"), }, "Button.Label::one": { "color": cl.white, }, "Button::one:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF") }, "Button::one:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF") }, "Button::two": { "background_color": cl.white, "border_color": cl("#B1B1B1") }, "Button.Label::two": { "color": cl("#272727") }, "Button::three:hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF"), "border_color": cl("#1D76FD"), }, "Button::four:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF"), "border_color": cl("#1D76FD"), }, } with ui.HStack(style=style1): ui.Button("One", name="one") ui.Button("Two", name="two") ui.Button("Three", name="three") ui.Button("Four", name="four") ui.Button("Five", name="five") """ ) self._text( "It's possible to assign any style override to any level of the widget. It can be assigned to both parents " "and children at the same time." ) with ui.HStack(style=self._style_system): ui.Button("One") ui.Button("Two", style={"color": cl("#AAAAAA")}) ui.Button("Three", style={"background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")}) ui.Button( "Four", style={":hovered": {"background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF")}} ) ui.Button( "Five", style={"Button:pressed": {"background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF")}}, ) self._code( """ style_system = { "Button": { "background_color": cl("#E1E1E1"), "border_color": cl("#ADADAD"), "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": { "color": cl.black, }, "Button:hovered": { "background_color": cl("#E5F1FB"), "border_color": cl("#0078D7") }, "Button:pressed": { "background_color": cl("#CCE4F7"), "border_color": cl("#005499"), "border_width": 1.0 }, } with ui.HStack(style=style_system): ui.Button("One") ui.Button("Two", style={"color": cl("#AAAAAA")}) ui.Button("Three", style={ "background_color": cl("#097EFF"), "background_gradient_color": cl("#6DB2FA")} ) ui.Button( "Four", style={ ":hovered": { "background_color": cl("#006EFF"), "background_gradient_color": cl("#5AAEFF") } } ) ui.Button( "Five", style={ "Button:pressed": { "background_color": cl("#6DB2FA"), "background_gradient_color": cl("#097EFF") } }, ) """ ) self._caption("Color Syntax", navigate_to) self._text( "There are many ways that colors can be described with omni.ui.color. If alpha is not specified, it is assumed to be 255 or 1.0." ) self._code( """ from omni.ui import color as cl cl("#CCCCCC") # RGB cl("#CCCCCCFF") # RGBA cl(128, 128, 128) # RGB cl(0.5, 0.5, 0.5) # RGB cl(128, 128, 128, 255) # RGBA cl(0.5, 0.5, 0.5, 1.0) # RGBA cl(128) # RGB all the same cl(0.5) # RGB all the same cl.blue """ ) self._text( "Note: You may see something like this syntax in older code, but that syntax is not suggested anymore:" ) self._code('"background_color": 0xFF886644 # Same as cl("#446688FF")') self._text( "Because of the way bytes are packed with little-endian format in that syntax, the color components appear to be backwards (ABGR). " "Going forward only omni.ui.color syntax should be used." ) self._caption("Shades", navigate_to) self._text( "Shades are used to have multiple named color palettes with the ability to runtime switch. The shade can " "be defined with the following code:" ) self._code('cl.shade(cl("#0066FF"), red=cl.red, green=cl("#00FF66"))') self._text( "It can be assigned to the color style. It's possible to switch the color with the following command " "globally:" ) self._code('cl.set_shade("red")') named_shades() self._code(inspect.getsource(named_shades).split("\n", 1)[-1]) self._caption("URL Shades", navigate_to) self._text("It's also possible to use shades for specifying shortcuts to the images and style-based paths.") url_shades() self._code(inspect.getsource(url_shades).split("\n", 1)[-1]) self._caption("Font Size", navigate_to) self._text("It's possible to set the font size with the style:") font_size() self._code(inspect.getsource(font_size).split("\n", 1)[-1]) ui.Spacer(height=10)
15,870
Python
35.823666
144
0.497669
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/custom_window_example.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. # """an example of creating a custom with shapes and drags window""" # TODO : This need clean up for full documentation from omni import ui EXTENSION_NAME = "Brick Demo Window" LIGHT_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFFCACACA}, "Frame::main_frame": {"background_color": 0xFFCACACA}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFFCACACA}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFFCACACA}, "Label::timeLabel": {"color": 0xFFDDDDDD, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFFBBBBBB, "border_color": 0xFF888888, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF888888}, "Circle::slider": {"background_color": 0xFFBBBBBB}, "Circle::slider:hovered": {"background_color": 0xFFCCCCCC}, "Circle::slider:pressed": {"background_color": 0xFFAAAAAA}, "Triangle::selector": {"background_color": 0xFF888888}, "Triangle::selector:hovered": {"background_color": 0xFF999999}, "Triangle::selector:pressed": {"background_color": 0xFF777777}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } DARK_WINDOW_STYLE = { # main frame style "ScrollingFrame::canvas": {"background_color": 0xFF454545}, "Frame::main_frame": {"background_color": 0xFF454545}, # title bar style "Label::title": {"color": 0xFF777777, "font_size": 16.0}, "Rectangle::titleBar": {"background_color": 0xFF454545}, "Rectangle::timeSelection": {"background_color": 0xFF888888, "border_radius": 5.0}, "Triangle::timeArrows": {"background_color": 0xFF454545}, "Label::timeLabel": {"color": 0xFF454545, "font_size": 16.0}, # custom widget slider "Rectangle::sunStudySliderBackground": { "background_color": 0xFF666666, "border_color": 0xFF333333, "border_width": 1.0, "border_radius": 10.0, }, "Rectangle::sunStudySliderForground": {"background_color": 0xFF333333}, "Circle::slider": {"background_color": 0xFF888888}, "Triangle::selector": {"background_color": 0xFF888888}, # toolbar "Triangle::play_button": {"background_color": 0xFF6E6E6E}, } class BrickSunStudyWindow: """ example of sun study window using Omni::UI """ def __init__(self): self._is_playing = False self._window_Frame = None self._time_selector_left_spacer = None self._slider_spacer = None self._slider_spacer_width = [200] self._start_time_offset = [200] self._start_time_label = None self._start_time = "8:00 AM" self._end_time_offset = [600] self._end_time_label = None self._end_time = "6:00 PM" self._time_of_day_offset = [200] self._mouse_press_position = [0, 0] def _play_pause_fn(self, x, y): """ """ self._is_playing = not self._is_playing self._play_button.visible = not self._is_playing self._pause_button.visible = self._is_playing def _on_object_mouse_pressed(self, position, x, y): position[0] = x position[1] = y def on_placer_mouse_moved_both(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[1] += y - position[1] placer.offset_x = max(offset[0], 0) placer.offset_y = offset[1] self._on_object_mouse_pressed(position, x, y) def on_time_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._current_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def on_start_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] self._time_range_placer.offset_x = offset[0] + 50 self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3) # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._start_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def on_end_placer_mouse_moved_X(self, placer, offset, position, x, y): # TODO: DPI is the problem we need to solve offset[0] += x - position[0] offset[0] = max(offset[0], 0) placer.offset_x = offset[0] self._time_range_rectangle.width = ui.Pixel(self._end_time_offset[0] - self._start_time_offset[0] + 3) # this is not very correct but serve ok for this demo hours = int(offset[0] / 800 * 24) time = "AM" if hours > 12: hours = hours - 12 time = "PM" self._end_time_label.text = f"{hours}:00 {time}" self._on_object_mouse_pressed(position, x, 0) def set_style_light(self, button): """ """ self._window_Frame.set_style(LIGHT_WINDOW_STYLE) def set_style_dark(self, button): """ """ self._window_Frame.set_style(DARK_WINDOW_STYLE) def _build_title_bar(self): """ return the title bar stack""" with ui.VStack(): with ui.ZStack(height=30): ui.Rectangle(name="titleBar") # Title Bar with ui.HStack(): ui.Spacer(width=10, height=0) with ui.VStack(width=0): ui.Spacer(width=0, height=8) ui.Label("Sun Study", name="title", width=0, alignment=ui.Alignment.LEFT) ui.Spacer(width=0, height=ui.Fraction(1)) ui.Spacer(width=ui.Fraction(1)) with ui.VStack(width=0): ui.Spacer(height=5) with ui.HStack(): ui.Spacer(width=10, height=0) ui.Image("resources/icons/[email protected]", width=20, height=20) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20, height=20) ui.Spacer(width=5) ui.Spacer(height=5) # Shadow ui.Image("resources/icons/TitleBarShadow_wAlpha_v2.png", fill_policy=ui.FillPolicy.STRETCH, height=20) def _build_time_arrow(self, arrowAlignment): with ui.VStack(width=0): # remove spacer with Fraction Padding ui.Spacer() ui.Triangle(name="timeArrows", width=12, height=12, alignment=arrowAlignment) ui.Spacer() def _build_start_time_selector(self): """ """ selector_placer = ui.Placer(offset_x=self._start_time_offset[0]) with selector_placer: with ui.VStack( width=80, mouse_pressed_fn=lambda x, y, b, a, c=self._mouse_press_position: self._on_object_mouse_pressed( c, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_start_placer_mouse_moved_X( selector_placer, self._start_time_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ): # SELECTOR START self._start_time_selector_stack = ui.ZStack() with self._start_time_selector_stack: ui.Rectangle(height=25, name="timeSelection") with ui.HStack(height=25): # remove spacer with Padding ui.Spacer(width=5) self._build_time_arrow(ui.Alignment.LEFT_CENTER) ui.Spacer(width=5) self._start_time_label = ui.Label( self._start_time, name="timeLabel", alignment=ui.Alignment.RIGHT_CENTER ) ui.Spacer(width=5) with ui.HStack(height=20): # Selector tip, Spacer will be removed wiht Padding ui.Spacer() def show_hide_start_time_selector(): self._start_time_selector_stack.visible = not self._start_time_selector_stack.visible ui.Triangle( width=10, height=17, name="selector", alignment=ui.Alignment.CENTER_BOTTOM, mouse_pressed_fn=lambda x, y, b, a: show_hide_start_time_selector(), ) ui.Spacer() def _build_end_time_selector(self): self._end_time_placer = ui.Placer(offset_x=self._end_time_offset[0]) with self._end_time_placer: with ui.VStack( width=80, mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed( self._mouse_press_position, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_end_placer_mouse_moved_X( self._end_time_placer, self._end_time_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ): # SELECTOR END self._end_time_selector_stack = ui.ZStack() with self._end_time_selector_stack: ui.Rectangle(height=25, name="timeSelection") with ui.HStack(height=25): ui.Spacer(width=5) self._end_time_label = ui.Label( self._end_time, name="timeLabel", widthalignment=ui.Alignment.RIGHT_CENTER ) ui.Spacer(width=5) self._build_time_arrow(ui.Alignment.RIGHT_CENTER) ui.Spacer(width=5) def show_hide_end_time_selector(): self._end_time_selector_stack.visible = not self._end_time_selector_stack.visible with ui.HStack(height=20): ui.Spacer() ui.Triangle( width=10, height=17, name="selector", alignment=ui.Alignment.CENTER_BOTTOM, mouse_pressed_fn=lambda x, y, b, a: show_hide_end_time_selector(), ) ui.Spacer() def _build_central_slider(self): """ """ # custom slider Widget with ui.VStack(height=70): ui.Spacer(height=40) with ui.HStack(): with ui.ZStack(height=20): ui.Rectangle(name="sunStudySliderBackground") self._time_range_placer = ui.Placer(offset_x=self._start_time_offset[0]) with self._time_range_placer: self._time_range_rectangle = ui.Rectangle(name="sunStudySliderForground", width=500, height=30) circle_placer = ui.Placer(offset_x=self._time_of_day_offset[0]) with circle_placer: ui.Circle( name="slider", width=30, height=30, radius=10, mouse_pressed_fn=lambda x, y, b, a: self._on_object_mouse_pressed( self._mouse_press_position, x, y ), mouse_moved_fn=lambda x, y, b, a: self.on_time_placer_mouse_moved_X( circle_placer, self._time_of_day_offset, self._mouse_press_position, x, y ), opaque_for_mouse_events=True, ) def _build_custom_slider(self): """ return the slider stack""" side_padding = 50 with ui.HStack(height=70): ui.Spacer(width=side_padding) # from Padding (will be removed by Padding on the HStack) with ui.ZStack(): self._build_central_slider() # Selectors with ui.ZStack(height=40): # Selector Height self._build_start_time_selector() self._build_end_time_selector() ui.Spacer(width=side_padding) def _build_control_bar(self): """ """ with ui.HStack(height=40): ui.Spacer(width=50) ui.Image("resources/icons/[email protected]", width=25) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20) ui.Spacer(width=10) ui.Image("resources/icons/[email protected]", width=20) ui.Spacer(width=ui.Fraction(2)) # with ui.ZStack(): self._play_button = ui.Image( "resources/icons/[email protected]", height=30, width=30, mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y), ) self._pause_button = ui.Image( "resources/icons/[email protected]", height=30, width=30, mouse_pressed_fn=lambda x, y, button, modifier: self._play_pause_fn(x, y), ) self._pause_button.visible = False ui.Spacer(width=ui.Fraction(1)) with ui.HStack(width=120): self._current_time_label = ui.Label("9:30 AM", name="title") ui.Label(" October 21, 2019", name="title") ui.Spacer(width=30) def build_window(self): """ build the window for the Class""" self._window = ui.Window("Brick Sun Study", width=800, height=250, flags=ui.WINDOW_FLAGS_NO_TITLE_BAR) with self._window.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Styling : ", alignment=ui.Alignment.RIGHT_CENTER) ui.Button("Light Mode", clicked_fn=lambda b=None: self.set_style_light(b)) ui.Button("Dark Mode", clicked_fn=lambda b=None: self.set_style_dark(b)) ui.Spacer() ui.Spacer(height=10) self._window_Frame = ui.ScrollingFrame( style=LIGHT_WINDOW_STYLE, name="canvas", height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ) with self._window_Frame: with ui.VStack(height=0): # Build the toolbar for the window self._build_title_bar() ui.Spacer(height=10) # build the custom slider self._build_custom_slider() ui.Spacer(height=10) self._build_control_bar() # botton Padding ui.Spacer(height=10) return self._window
16,391
Python
40.498734
119
0.532426
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/window_doc.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. # """The documentation for Windows""" from .doc_page import DocPage from omni import ui from omni.ui import color as cl import inspect import json import carb.settings SPACING = 5 def popup_example(self): class StrModel(ui.AbstractValueModel): def __init__(self, **kwargs): super().__init__() self.__str = "" self.__parent = None self.__window = None self.__frame = None self.__tooltips = ["Hello", "World", "Hello World"] self.__kwargs = kwargs def set_parent(self, parent): self.__parent = parent def set_value(self, value): self.__str = str(value) self._value_changed() self._set_tips() def get_value_as_string(self): return self.__str def begin_edit(self): if self.__window and self.__window.visible: return # Create and show the window with field and list of tips self.__window = ui.Window("0", **self.__kwargs) with self.__window.frame: with ui.VStack(width=0, height=0): width = self.__parent.computed_content_width # Field with the same model field = ui.StringField(self, width=width) field.focus_keyboard() self.__frame = ui.Frame() self.__window.position_x = self.__parent.screen_position_x self.__window.position_y = self.__parent.screen_position_y self._set_tips() def _set_tips(self): """Generates list of tips""" if not self.__frame: return found = False with self.__frame: with ui.VStack(): for t in self.__tooltips: if self.__str and self.__str in t: ui.Button(t) found = True if not found: for t in self.__tooltips: ui.Button(t) def destroy(self): self.__parent = None self.__frame = None self.__window = None window_args = { "flags": ui.WINDOW_FLAGS_POPUP | ui.WINDOW_FLAGS_NO_TITLE_BAR, "auto_resize": True, "padding_x": 0, "padding_y": 0, } self._model = StrModel(**window_args) self._field = ui.StringField(self._model) self._model.set_parent(self._field) class WindowDoc(DocPage): """ document Windows classes""" def __init__(self, extension_path): super().__init__(extension_path) self._window_example = None self._modal_window_example = None self._no_close_window_example = None self._style_window_example = None self._simple_toolbar = None self._rotating_toolbar = None self._toolbar_rotation = ui.DockPosition.BOTTOM self._modal_test = [] self._model = None def clean(self): self._model = None def build_toolbar(self): """Caled to load the extension""" def top_toolbar_changeAxis(frame, axis): with frame: stack = None if axis == ui.ToolBarAxis.X: stack = ui.HStack(spacing=15, height=24) else: stack = ui.VStack(spacing=15, height=24) with stack: ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._top_toolbar = ui.ToolBar("UI ToolBar", noTabBar=False, padding_x=0, padding_y=0) self._top_toolbar.set_axis_changed_fn( lambda axis, frame=self._top_toolbar.frame: top_toolbar_changeAxis(frame, axis) ) top_toolbar_changeAxis(self._top_toolbar.frame, ui.ToolBarAxis.X) self._right_toolbar = ui.ToolBar("Right Size ToolBar", noTabBar=True, padding_x=5, padding_y=0) with self._right_toolbar.frame: with ui.VStack(spacing=15, width=25): ui.Spacer(height=1) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Image("resources/icons/SunStudy_64.png", width=20, height=20) ui.Spacer() self._left_toolbar = ui.ToolBar("Left Size ToolBar", noTabBar=True, padding_x=5, padding_y=0) with self._left_toolbar.frame: with ui.VStack(spacing=0): ui.Spacer(height=10) ui.Image("resources/icons/Toolbars/[email protected]", width=20, height=20) ui.Spacer() self._bottom_toolbar = ui.ToolBar("Bottom ToolBar", noTabBar=True, padding_x=0, padding_y=0) with self._bottom_toolbar.frame: with ui.HStack(height=18): ui.Spacer() with ui.ZStack(width=200, height=15): ui.Rectangle( width=120, style={"background_color": cl("#809EAB"), "corner_flag": ui.CornerFlag.LEFT, "border_radius": 2}, ) ui.Rectangle( width=200, style={ "background_color": cl.transparent, "border_color": cl("#222222"), "border_width": 1.0, "border_radius": 2, }, ) ui.Label("FPS 30", style={"color": cl.white, "margin_width": 10, "font_size": 8}) ui.Spacer() self._bottom_toolbar.dock_in_window("Viewport", ui.DockPosition.BOTTOM) self._top_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP) self._left_toolbar.dock_in_window("Viewport", ui.DockPosition.LEFT) self._right_toolbar.dock_in_window("Viewport", ui.DockPosition.RIGHT) # TODO omni.ui: restore functionality for Kit Next self._settings = carb.settings.get_settings() self._settings.set("/app/docks/autoHideTabBar", True) self._settings.set("/app/docks/noWindowMenuButton", False) self._settings.set("app/window/showStatusBar", False) self._settings.set("app/window/showStatusBar", False) self._settings.set("/app/viewport/showSettingsMenu", True) self._settings.set("/app/viewport/showCameraMenu", False) self._settings.set("/app/viewport/showRendererMenu", True) self._settings.set("/app/viewport/showHideMenu", True) self._settings.set("/app/viewport/showLayerMenu", False) def create_and_show_window(self): if not self._window_example: self._window_example = ui.Window("Example Window", width=300, height=300) button_size = None button_dock = None with self._window_example.frame: with ui.VStack(): ui.Button("click me") button_size = ui.Button("") def move_me(window): window.setPosition(200, 200) def size_me(window): window.width = 300 window.height = 300 ui.Button("move to 200,200", clicked_fn=lambda w=self._window_example: move_me(w)) ui.Button("set size 300,300", clicked_fn=lambda w=self._window_example: size_me(w)) button_dock = ui.Button("Undocked") def update_button(window, button): computed_width = (int)(button.computed_width) computed_height = (int)(button.computed_height) button.text = ( "Window size is {:.1f} x {:.1f}\n".format(window.width, window.height) + "Window position is {:.1f} x {:.1f}\n".format(window.position_x, window.position_y) + "Button size is {:.1f} x {:.1f}".format(computed_width, computed_height) ) def update_docking(docked, button): button.text = "Docked" if docked else "Undocked" for fn in [ self._window_example.set_width_changed_fn, self._window_example.set_height_changed_fn, self._window_example.set_position_x_changed_fn, self._window_example.set_position_y_changed_fn, ]: fn(lambda value, b=button_size, w=self._window_example: update_button(w, b)) self._window_example.set_docked_changed_fn(lambda value, b=button_dock: update_docking(value, b)) self._window_example.visible = True def close_modal_window_me(self): if self._modal_window_example: self._modal_window_example.visible = False def create_and_show_modal_window(self): if not self._modal_window_example: window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL self._modal_window_example = ui.Window("Example Modal Window", width=200, height=200, flags=window_flags) with self._modal_window_example.frame: with ui.VStack(): ui.Button("I am Modal") ui.Button("You Can't Click outsite ") ui.Button("click here to close me", height=100, clicked_fn=self.close_modal_window_me) self._modal_window_example.visible = True def create_and_show_window_no_close(self): if not self._no_close_window_example: window_flags = ui.WINDOW_FLAGS_NO_CLOSE self._no_close_window_example = ui.Window( "Example Modal Window", width=400, height=200, flags=window_flags, visibility_changed_fn=self._update_window_visible, ) with self._no_close_window_example.frame: with ui.VStack(): ui.Button("I dont have Close button") ui.Button("my Size is 400x200 ") def close_me(window): if window: window.visible = False ui.Button( "click here to close me", height=100, clicked_fn=lambda w=self._no_close_window_example: close_me(w), ) self._no_close_window_example.visible = True def create_styled_window(self): if not self._style_window_example: self._style_window_example = ui.Window("Styled Window Example", width=300, height=300) self._style_window_example.frame.set_style( { "Window": { "background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red, } } ) with self._style_window_example.frame: with ui.VStack(): ui.Button("I am a Styled Window") ui.Spacer(height=10) ui.Button( """Style is attached to 'Window' {"Window": {"background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red}""", height=200, ) self._style_window_example.visible = True def _update_window_visible(self, value): self._window_checkbox.model.set_value(value) def create_simple_toolbar(self): if self._simple_toolbar: self._simple_toolbar.visible = not self._simple_toolbar.visible else: self._simple_toolbar = ui.ToolBar("simple toolbar", noTabBar=True) with self._simple_toolbar.frame: with ui.HStack(spacing=15, height=28): ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._simple_toolbar.dock_in_window("Viewport", ui.DockPosition.TOP) self._simple_toolbar.frame.set_style({"Window": {"background_color": cl("#DDDDDD")}}) def create_rotating_toolbar(self): if not self._rotating_toolbar: def toolbar_changeAxis(frame, axis): with frame: stack = None if axis == ui.ToolBarAxis.X: stack = ui.HStack(spacing=15, height=30) else: stack = ui.VStack(spacing=15, width=30) with stack: ui.Spacer() ui.Image("resources/icons/Select_model_64.png", width=24, height=24) ui.Image("resources/icons/Move_64.png", width=24, height=24) ui.Image("resources/icons/Rotate_global.png", width=24, height=24) ui.Image("resources/icons/Scale_64.png", width=24, height=24) ui.Image("resources/icons/Snap_64.png", width=24, height=24) ui.Spacer() self._rotating_toolbar = ui.ToolBar("Rotating ToolBar", noTabBar=False, padding_x=5, padding_y=5, margin=5) self._rotating_toolbar.set_axis_changed_fn( lambda axis, frame=self._rotating_toolbar.frame: toolbar_changeAxis(frame, axis) ) toolbar_changeAxis(self._rotating_toolbar.frame, ui.ToolBarAxis.X) if self._toolbar_rotation == ui.DockPosition.RIGHT: self._toolbar_rotation = ui.DockPosition.BOTTOM else: self._toolbar_rotation = ui.DockPosition.RIGHT self._rotating_toolbar.dock_in_window("Viewport", self._toolbar_rotation) def create_doc(self, navigate_to=None): self._section_title("Windows") self._text( "With omni ui you can create a varierty of Window type and style" " the main Window type are floating window that can optionally be docked into the Main Window.\n" "There are also other type of window like ToolBar, DialogBox, Etc that you can use" ) self._caption("Window", navigate_to) self._text("This class is used to construct a regular Window") with ui.ScrollingFrame(height=350, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): with ui.HStack(width=0): ui.Button("click for window Example", width=180, clicked_fn=self.create_and_show_window) ui.Label("this create a regular Window", name="text", width=180, style={"margin_width": 10}) ui.Label( """ ui.Window("Example Window", position_x=100, position_y=100)""", name="text", ) with ui.HStack(width=0): ui.Button("Window without close", width=180, clicked_fn=self.create_and_show_window_no_close) self._window_checkbox = ui.CheckBox(style={"margin": 5}) # this Tie the window visibility with the checkox def update_check_box(value, self): self._no_close_window_example.visible = value self._window_checkbox.model.add_value_changed_fn( lambda a, this=self: update_check_box(a.get_value_as_bool(), self) ) ui.Label("this create a regular Window", name="text", width=150, style={"margin_width": 10}) ui.Label('ui.Window("Example Window", )', name="text") # Modal example is off because there are few issue but this MR need to go in with ui.HStack(width=0): ui.Button("click for Custom Window", width=180, clicked_fn=self.create_and_show_modal_window) ui.Label("this create a custom Window", name="text", width=180, style={"margin_width": 10}) ui.Label( "window_flags = ui.WINDOW_FLAGS_NO_COLLAPSE\n" "window_flags |= ui.WINDOW_FLAGS_NO_RESIZE\n" "window_flags |= ui.WINDOW_FLAGS_NO_CLOSE\n" "window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR\n" "window_flags |= ui.WINDOW_FLAGS_NO_TITLE_BAR\n\n" "ui.Window('Example Window', flags=window_flags", name="text", ) with ui.HStack(width=0): ui.Button("click for Styled Window", width=180, clicked_fn=self.create_styled_window) ui.Spacer(width=20) ui.Label( """ self._style_window_example = ui.Window("Styled Window Example", width=300, height=300) self._style_window_example.frame.set_style({"Window": {"background_color": cl.blue, "border_radius": 10, "border_width": 5, "border_color": cl.red}) with self._style_window_example.frame: with ui.VStack(): ui.Button("I am a Styled Window") ui.Button("Style is attached to 'Window'", height=200)""", name="text", ) self._text("All the Window Flags") self._text( """ WINDOW_FLAGS_NONE WINDOW_FLAGS_NO_TITLE_BAR WINDOW_FLAGS_NO_RESIZE WINDOW_FLAGS_NO_MOVE WINDOW_FLAGS_NO_SCROLLBAR WINDOW_FLAGS_NO_COLLAPSE WINDOW_FLAGS_NO_SAVED_SETTINGS WINDOW_FLAGS_SHOW_HORIZONTAL_SCROLLBAR WINDOW_FLAGS_FORCE_VERTICAL_SCROLLBAR WINDOW_FLAGS_FORCE_HORIZONTAL_SCROLLBAR WINDOW_FLAGS_NO_FOCUS_ON_APPEARING WINDOW_FLAGS_NO_CLOSE """ ) self._text("Available Window Properties, call can be used in the constructor") self._text( """ title : set the title for the window visible: set the window to be visible or not frame: read only property to get the frame of the window padding_x: padding on the window around the Frame padding_y: padding on the window around the Frame flags: the window flags, not that you can pass then on the constructor but also change them after ! """ ) self._caption("ToolBar", navigate_to) with ui.ScrollingFrame(height=60, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF): with ui.VStack(height=0): with ui.HStack(width=0): ui.Button("ToolBar Example", width=180, clicked_fn=self.create_simple_toolbar) ui.Label("this create a ToolBar Docked at the top", name="text", width=280) ui.Label("""ui.ToolBar("Awesome ToolBar", noTabBar=True)""", name="text") with ui.HStack(width=0): ui.Button("Axis changing ToolBar Example", width=180, clicked_fn=self.create_rotating_toolbar) ui.Label("see how the orientation of the toolbar can change", name="text", width=280) ui.Label("""ui.ToolBar("Awesome ToolBar")""", name="text") self._text( "This file contain a very complete example of many type of toolbar\n" "location is " + __file__ + "\n" ) self._caption("Multiple Modal Windows", navigate_to) self._text( "Omni::UI supports the conception of multiple modal windows. When the new modal window is created, it " "makes other modal windows inactive. And when it's destroyed, the previous modal window becomes active, " "blocking all other windows." ) ui.Button("Multiple Modal Windows", clicked_fn=self._on_modal_in_modal_clicked) self._caption("Overlay Other Windows", navigate_to) self._text( "When creating two windows with the same title, only one window will be displayed, and it will contain " "the widgets from both windows. This ability allows for overlaying omni.ui Widgets to any ImGui window. " "For example, it's possible to add a button to the viewport with creating a new window with the title " '"Viewport".' ) def overlay_viewport(self): self._overlay_window = None def create_overlay_window(self): if self._overlay_window: self._overlay_window = None else: self._overlay_window = ui.Window("Viewport") with self._overlay_window.frame: with ui.HStack(): ui.Spacer() ui.Label("Hello World", width=0) ui.Spacer() self._overaly_button = ui.Button( "Create or Remove Viewport Label", style=self._style_system, clicked_fn=lambda: create_overlay_window(self), ) overlay_viewport(self) self._code(inspect.getsource(overlay_viewport).split("\n", 1)[-1]) self._caption("Workspace", navigate_to) class WindowItem(ui.AbstractItem): def __init__(self, window): super().__init__() # Don't keep the window because it prevents the window from closing. self._window_title = window.title self.title_model = ui.SimpleStringModel(self._window_title) self.type_model = ui.SimpleStringModel(type(window).__name__) @property def window(self): return ui.Workspace.get_window(self._window_title) class WindowModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = ui.SimpleStringModel("Windows") self.update() def update(self): self._children = [WindowItem(i) for i in ui.Workspace.get_windows()] self._item_changed(None) def get_item_children(self, item): if item is not None: return [] return self._children def get_item_value_model_count(self, item): return 2 def get_item_value_model(self, item, column_id): if item is None: return self._root if column_id == 0: return item.title_model if column_id == 1: return item.type_model self._window_model = WindowModel() self._tree_left = None self._tree_right = None with ui.VStack(style=self._style_system): ui.Button("Refresh", clicked_fn=lambda: self._window_model.update()) with ui.HStack(): ui.Button("Clear", clicked_fn=ui.Workspace.clear) ui.Button("Focus", clicked_fn=lambda: self._focus(self._tree_left.selection)) with ui.HStack(): ui.Button("Visibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, True)) ui.Button("Invisibile", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, False)) ui.Button("Toggle Visibility", clicked_fn=lambda: self._set_visibility(self._tree_left.selection, None)) with ui.HStack(): ui.Button( "Dock Right", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.RIGHT ), ) ui.Button( "Dock Left", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.LEFT ), ) ui.Button( "Dock Top", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.TOP ), ) ui.Button( "Dock Bottom", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.BOTTOM ), ) ui.Button( "Dock Same", clicked_fn=lambda: self._dock( self._tree_left.selection, self._tree_right.selection, ui.DockPosition.SAME ), ) ui.Button("Undock", clicked_fn=lambda: self._undock(self._tree_left.selection)) with ui.HStack(): ui.Button("Move Left", clicked_fn=lambda: self._left(self._tree_left.selection)) ui.Button("MoveRight", clicked_fn=lambda: self._right(self._tree_left.selection)) with ui.HStack(): ui.Button( "Reverse Docking Tabs of Neighbours", clicked_fn=lambda: self._dock_reorder(self._tree_left.selection), ) ui.Button("Hide Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, False)) ui.Button("Show Tabs", clicked_fn=lambda: self._tabs(self._tree_left.selection, True)) with ui.HStack(height=400): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_left = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._tree_right = ui.TreeView(self._window_model, column_widths=[ui.Fraction(1), 80]) self._caption("Popup", navigate_to) self._text( "The Popup window is a window that disappears when the user clicks outside of the window. To create a popup " "window, it's necessary to use the flag ui.WINDOW_FLAGS_POPUP. It's very useful for creating a menu with " "custom widgets inside." ) self._text("Start typing for popup") popup_example(self) self._code(inspect.getsource(popup_example).split("\n", 1)[-1]) # some padding at the bottom ui.Spacer(height=100) def _undock(self, selection): if not selection: return for item in selection: item.window.undock() def _dock(self, left, right, position): if not left or not right: return target = right[0].window for item in left: item.window.dock_in(target, position) def _left(self, selection): if not selection: return for item in selection: item.window.position_x -= 100 def _right(self, selection): if not selection: return for item in selection: item.window.position_x += 100 def _set_visibility(self, selection, visible): if not selection: return for item in selection: if visible is not None: item.window.visible = visible else: item.window.visible = not item.window.visible def _dock_reorder(self, selection): if not selection: return docking_groups = [ui.Workspace.get_docked_neighbours(item.window) for item in selection] for group in docking_groups: # Reverse order for i, window in enumerate(reversed(group)): window.dock_order = i def _on_modal_in_modal_clicked(self): def close_me(id): self._modal_test[id].visible = False def put_on_front(id): if not self._modal_test[id]: return self._modal_test[id].set_top_modal() def toggle(id): if not self._modal_test[id]: return self._modal_test[id].visible = not self._modal_test[id].visible window_id = len(self._modal_test) prev_id = max(0, window_id - 1) window_flags = ui.WINDOW_FLAGS_NO_RESIZE window_flags |= ui.WINDOW_FLAGS_NO_SCROLLBAR window_flags |= ui.WINDOW_FLAGS_MODAL modal_window = ui.Window(f"Modal Window #{window_id}", width=200, height=200, flags=window_flags) self._modal_test.append(modal_window) with modal_window.frame: with ui.VStack(height=0): ui.Label(f"This is the window #{window_id}") ui.Button("One Modal More", clicked_fn=self._on_modal_in_modal_clicked) ui.Button(f"Bring #{prev_id} To Top", clicked_fn=lambda id=prev_id: put_on_front(id)) ui.Button(f"Toggle visibility of #{prev_id}", clicked_fn=lambda id=prev_id: toggle(id)) ui.Button("Close", clicked_fn=lambda id=window_id: close_me(id))
31,379
Python
40.618037
121
0.541445
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/image_doc.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. # """The documentation for Images""" from omni import ui from .doc_page import DocPage import inspect SPACING = 5 def image_hot_switch(): styles = [ { "": {"image_url": "resources/icons/Nav_Walkmode.png"}, ":hovered": {"image_url": "resources/icons/Nav_Flymode.png"}, }, { "": {"image_url": "resources/icons/Move_local_64.png"}, ":hovered": {"image_url": "resources/icons/Move_64.png"}, }, { "": {"image_url": "resources/icons/Rotate_local_64.png"}, ":hovered": {"image_url": "resources/icons/Rotate_global.png"}, }, ] def set_image(model, image): value = model.get_item_value_model().get_value_as_int() image.set_style(styles[value]) image = ui.Image(width=64, height=64, style=styles[0]) with ui.HStack(width=ui.Percent(50)): ui.Label("Select a texture to display", name="text") model = ui.ComboBox(0, "Navigation", "Move", "Rotate").model model.add_item_changed_fn(lambda m, i, im=image: set_image(m, im)) class ImageDoc(DocPage): """ document for Image""" def create_doc(self, navigate_to=None): self._section_title("Image") self._text("The Image type displays an image.") self._text("The source of the image is specified as a URL using the source property.") self._text( "By default, specifying the width and height of the item causes the image to be scaled to that size. This " "behavior can be changed by setting the fill_mode property, allowing the image to be stretched or scaled " "instead. The property alignment controls where to align the scaled image." ) code_width = 320 image_source = "resources/desktop-icons/omniverse_512.png" with ui.VStack(): self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.STRETCH)""", "(Default) The image is scaled to fit, the alignment is ignored", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.LEFT_CENTER)""", "The image is scaled uniformly to fit without cropping and aligned to the left", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER)""", "The image is scaled uniformly to fit without cropping and aligned to the center", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.RIGHT_CENTER)""", "The image is scaled uniformly to fit without croppingt and aligned to right", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_TOP)""", "The image is scaled uniformly to fill, cropping if necessary and aligned to the top", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER)""", "The image is scaled uniformly to fill, cropping if necessary and centered", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_CROP, alignment=ui.Alignment.CENTER_BOTTOM)""", "The image is scaled uniformly to fill, cropping if necessary and aligned to the bottom", code_width=code_width, ) self._image_table( f"""ui.Image( '{image_source}', fill_policy=ui.FillPolicy.PRESERVE_ASPECT_FIT, alignment=ui.Alignment.CENTER, style={{'border_radius': 10}})""", "The image has rounded corners", code_width=code_width, ) ui.Spacer(height=20) ui.Line() ui.Spacer(height=10) self._text("The Image can use style image_url") ui.Spacer(height=10) ui.Line() ui.Spacer(height=20) code_width = 470 self._image_table( f"""ui.Image(style={{'image_url': 'resources/desktop-icons/omniverse_128.png'}})""", "The image has a styled URL", code_width=code_width, ) self._image_table( f"""with ui.HStack(spacing =5, style={{"Image":{{'image_url': 'resources/desktop-icons/omniverse_128.png'}}}}): ui.Image() ui.Image() ui.Image() """, "The image has a styled URL", code_width=code_width, ) self._image_table( f"""ui.Image(style={{ 'image_url': 'resources/desktop-icons/omniverse_128.png', 'alignment': ui.Alignment.RIGHT_CENTER}})""", "The image has styled Alignment", code_width=code_width, ) self._image_table( f"""ui.Image(style={{ 'image_url': 'resources/desktop-icons/omniverse_256.png', 'fill_policy': ui.FillPolicy.PRESERVE_ASPECT_CROP, 'alignment': ui.Alignment.RIGHT_CENTER}})""", "The image has styled fill_policy", code_width=code_width, ) self._text( "It's possible to set a different image per style state. And switch them depending on the mouse hovering, " "selection state, etc." ) image_hot_switch() self._code(inspect.getsource(image_hot_switch).split("\n", 1)[-1]) ui.Spacer(height=10)
7,160
Python
39.005586
119
0.525978
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/layout_doc.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. # """The documentation for Layouts""" from omni import ui from omni.ui import color as cl from .doc_page import DocPage import inspect import asyncio import omni.kit.app SPACING = 5 def collapsable_simple(): with ui.CollapsableFrame("Header"): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def collapsable_custom(style_system): def custom_header(collapsed, title): with ui.HStack(style=style_system): with ui.ZStack(width=30): ui.Circle(name="title") with ui.HStack(): ui.Spacer() align = ui.Alignment.V_CENTER ui.Line(name="title", width=6, alignment=align) ui.Spacer() if collapsed: with ui.VStack(): ui.Spacer() align = ui.Alignment.H_CENTER ui.Line(name="title", height=6, alignment=align) ui.Spacer() ui.Label(title, name="title") style = { "CollapsableFrame": { "background_color": cl.transparent, "secondary_color": cl.transparent, "border_radius": 0, "border_color": cl("#B2B2B2"), "border_width": 0.5, }, "CollapsableFrame:hovered": {"secondary_color": cl("#E5F1FB")}, "CollapsableFrame:pressed": {"secondary_color": cl("#CCE4F7")}, "Label::title": {"color": cl.black}, "Circle::title": { "color": cl.black, "background_color": cl.transparent, "border_color": cl("#B2B2B2"), "border_width": 0.75, }, "Line::title": {"color": cl("#666666"), "border_width": 1}, } style.update(style_system) with ui.CollapsableFrame("Header", build_header_fn=custom_header, style=style): with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def collapsable_layout(style_system): style = { "CollapsableFrame": { "border_color": cl("#005B96"), "border_radius": 4, "border_width": 2, "padding": 0, "margin": 0, } } frame = ui.CollapsableFrame("Header", style=style) with frame: with ui.VStack(height=0): ui.Button("Hello World") ui.Button("Hello World") def set_style(field, model, style=style, frame=frame): frame_style = style["CollapsableFrame"] frame_style[field] = model.get_value_as_float() frame.set_style(style) with ui.HStack(): ui.Label("Padding:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("padding", m)) with ui.HStack(): ui.Label("Margin:", width=ui.Percent(10), name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m: set_style("margin", m)) def direction(): def rotate(dirs, stack, label): dirs[0] = (dirs[0] + 1) % len(dirs[1]) stack.direction = dirs[1][dirs[0]] label.text = str(stack.direction) dirs = [ 0, [ ui.Direction.LEFT_TO_RIGHT, ui.Direction.RIGHT_TO_LEFT, ui.Direction.TOP_TO_BOTTOM, ui.Direction.BOTTOM_TO_TOP, ], ] stack = ui.Stack(ui.Direction.LEFT_TO_RIGHT, width=0, height=0) with stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) with ui.HStack(): with ui.HStack(): ui.Label("Current direcion is ", name="text", width=0) label = ui.Label("", name="text") button = ui.Button("Change") button.set_clicked_fn(lambda d=dirs, s=stack, l=label: rotate(d, s, l)) rotate(dirs, stack, label) def recreate(self): self._recreate_ui = ui.Frame(height=40) def changed(model, recreate_ui=self._recreate_ui): with recreate_ui: with ui.HStack(): for i in range(model.get_value_as_int()): ui.Button(f"Button #{i}") model = ui.IntDrag(min=0, max=10).model self._sub_recreate = model.subscribe_value_changed_fn(changed) def clipping(self): self._clipping_frame = ui.Frame() with self._clipping_frame: ui.Button("Hello World") def set_width(model): self._clipping_frame.width = ui.Pixel(model.as_float) def set_height(model): self._clipping_frame.height = ui.Pixel(model.as_float) def set_hclipping(model): self._clipping_frame.horizontal_clipping = model.as_bool def set_vclipping(model): self._clipping_frame.horizontal_clipping = model.as_bool width = ui.FloatDrag(min=50, max=1000).model height = ui.FloatDrag(min=50, max=1000).model hclipping = ui.ToolButton(text="HClipping").model vclipping = ui.ToolButton(text="VClipping").model self._width = width.subscribe_value_changed_fn(set_width) self._height = height.subscribe_value_changed_fn(set_height) self._hclipping = hclipping.subscribe_value_changed_fn(set_hclipping) self._vclipping = vclipping.subscribe_value_changed_fn(set_vclipping) width.set_value(100) height.set_value(100) def visibility(): def invisible(button): button.visible = False def visible(buttons): for button in buttons: button.visible = True buttons = [] with ui.HStack(): for n in ["One", "Two", "Three", "Four", "Five"]: button = ui.Button(n, width=0) button.set_clicked_fn(lambda b=button: invisible(b)) buttons.append(button) ui.Spacer() button = ui.Button("Visible all", width=0) button.set_clicked_fn(lambda b=buttons: visible(b)) def vgrid(): with ui.ScrollingFrame( height=425, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.black, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) def hgrid(): with ui.ScrollingFrame( height=425, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.HGrid(column_width=100, row_height=100): for i in range(100): with ui.ZStack(): ui.Rectangle( style={ "border_color": cl.black, "background_color": cl.white, "border_width": 1, "margin": 0, } ) ui.Label(f"{i}", style={"margin": 5}) def placer_track(self, id): # Initial size BEGIN = 50 + 100 * id END = 120 + 100 * id HANDLE_WIDTH = 10 class EditScope: """The class to avoid circular event calling""" def __init__(self): self.active = False def __enter__(self): self.active = True def __exit__(self, type, value, traceback): self.active = False def __bool__(self): return not self.active class DoLater: """A helper to collect data and process it one frame later""" def __init__(self): self.__task = None self.__data = [] def do(self, data): # Collect data self.__data.append(data) # Update in the next frame. We need it because we want to accumulate the affected prims if self.__task is None or self.__task.done(): self.__task = asyncio.ensure_future(self.__delayed_do()) async def __delayed_do(self): # Wait one frame await omni.kit.app.get_app().next_update_async() print(f"In the previous frame the user clicked the rectangles: {self.__data}") self.__data.clear() self.edit = EditScope() self.dolater = DoLater() def start_moved(start, body, end): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) def body_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: start.offset_x = body.offset_x end.offset_x = body.offset_x + rect.width.value - HANDLE_WIDTH def end_moved(start, body, end, rect): if not self.edit: # Something already edits it return with self.edit: body.offset_x = start.offset_x rect.width = ui.Pixel(end.offset_x - start.offset_x + HANDLE_WIDTH) with ui.ZStack(height=30): # Body body = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with body: rect = ui.Rectangle(width=END - BEGIN + HANDLE_WIDTH) rect.set_mouse_pressed_fn(lambda x, y, b, m, id=id: self.dolater.do(id)) # Left handle start = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=BEGIN) with start: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Right handle end = ui.Placer(draggable=True, drag_axis=ui.Axis.X, offset_x=END) with end: ui.Rectangle(width=HANDLE_WIDTH, style={"background_color": cl("#FF660099")}) # Connect them together start.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end: start_moved(s, b, e)) body.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: body_moved(s, b, e, r)) end.set_offset_x_changed_fn(lambda _, s=start, b=body, e=end, r=rect: end_moved(s, b, e, r)) def placer_percents(self): # The size of the rectangle SIZE = 20.0 with ui.ZStack(height=300): # Background ui.Rectangle(style={"background_color": cl("#999999")}) # Small rectangle p = ui.Percent(50) placer = ui.Placer(draggable=True, offset_x=p, offset_y=p) with placer: ui.Rectangle(width=SIZE, height=SIZE) def clamp_x(offset): if offset.value < 0: placer.offset_x = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_width * 100.0 if offset.value > max_per: placer.offset_x = ui.Percent(max_per) def clamp_y(offset): if offset.value < 0: placer.offset_y = ui.Percent(0) max_per = 100.0 - SIZE / placer.computed_height * 100.0 if offset.value > max_per: placer.offset_y = ui.Percent(max_per) # Calbacks placer.set_offset_x_changed_fn(clamp_x) placer.set_offset_y_changed_fn(clamp_y) class LayoutDoc(DocPage): """ document Layout classes""" def create_doc(self, navigate_to=None): self._section_title("Layout") self._text("We have three main components: VStack, HStack, and ZStack.") self._caption("HStack", navigate_to) self._text("This class is used to construct horizontal layout objects.") with ui.HStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") self._text("The simplest use of the class is like this:") self._code( """ with ui.HStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") """ ) self._caption("VStack", navigate_to) self._text("The VStack class lines up widgets vertically.") with ui.VStack(width=100.0): with ui.VStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") self._text("The simplest use of the class is like this:") self._code( """ with ui.VStack(): ui.Button("One") ui.Button("Two") ui.Button("Three") ui.Button("Four") ui.Button("Five") """ ) self._caption("ZStack", navigate_to) self._text("A view that overlays its children, aligning them on top of each other.") with ui.VStack(width=100.0): with ui.ZStack(): ui.Button("Very Long Text to See How Big it Can Be", height=0) ui.Button("Another\nMultiline\nButton", width=0) self._code( """ with ui.ZStack(): ui.Button("Very Long Text to See How Big it Can Be", height=0) ui.Button("Another\\nMultiline\\nButton", width=0) """ ) self._caption("Spacing", navigate_to) self._text("Spacing is a non-stretchable space in pixels between child items of the layout.") def set_spacing(stack, spacing): stack.spacing = spacing spacing_stack = ui.HStack(style={"margin": 0}) with spacing_stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) with ui.HStack(spacing=SPACING): with ui.HStack(width=100): ui.Spacer() ui.Label("spacing", width=0, name="text") with ui.HStack(width=ui.Percent(20)): field = ui.FloatField(width=50) slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent}) # Link them together slider.model = field.model slider.model.add_value_changed_fn(lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float())) self._code( """ def set_spacing(stack, spacing): stack.spacing = spacing ui.Spacer(height=SPACING) spacing_stack = ui.HStack(style={"margin": 0}) with spacing_stack: for name in ["One", "Two", "Three", "Four"]: ui.Button(name) ui.Spacer(height=SPACING) with ui.HStack(spacing=SPACING): with ui.HStack(width=100): ui.Spacer() ui.Label("spacing", width=0, name="text") with ui.HStack(width=ui.Percent(20)): field = ui.FloatField(width=50) slider = ui.FloatSlider(min=0, max=50, style={"color": cl.transparent}) # Link them together slider.model = field.model slider.model.add_value_changed_fn( lambda m, s=spacing_stack: set_spacing(s, m.get_value_as_float())) """ ) self._caption("VGrid", navigate_to) self._text( "Grid is a container that arranges its child views in a grid. The grid vertical/horizontal direction is " "the direction the grid size growing with creating more children." ) self._text("It has two modes for cell width.") self._text(" - If the user set column_count, the column width is computed from the grid width.") self._text(" - If the user sets column_width, the column count is computed.") self._text("It also has two modes for height.") self._text( " - If the user sets row_height, VGrid uses it to set the height for all the cells. It's the fast mode " "because it's considered that the cell height never changes. VGrid easily predict which cells are visible." ) self._text( " - If the user sets nothing, VGrid computes the size of the children. This mode is slower than the " "previous one, but the advantage is that all the rows can be different custom sizes. VGrid still draws " "only visible items, but to predict it, it uses cache, which can be big if VGrid has hundreds of " "thousands of items." ) vgrid() self._code(inspect.getsource(vgrid).split("\n", 1)[-1]) self._caption("HGrid", navigate_to) self._text("HGrid works exactly like VGrid, but with swapped width and height..") hgrid() self._code(inspect.getsource(hgrid).split("\n", 1)[-1]) self._caption("Frame", navigate_to) self._text( "Frame is a container that can keep only one child. Each child added to Frame overrides the previous one. " "This feature is used for creating dynamic layouts. The whole layout can be easily recreated with a " "simple callback. In the following example, the buttons are recreated each time the slider changes." ) recreate(self) self._code(inspect.getsource(recreate).split("\n", 1)[-1]) self._text( "Another feature of Frame is the ability to clip its child. When the content of Frame is bigger than " "Frame itself, the exceeding part is not drawn if the clipping is on." ) clipping(self) self._code(inspect.getsource(clipping).split("\n", 1)[-1]) self._caption("CollapsableFrame", navigate_to) self._text( "CollapsableFrame is a frame widget that can hide or show its content. It has two states expanded and " "collapsed. When it's collapsed, it looks like a button. If it's expanded, it looks like a button and a " "frame with the content. It's handy to group properties, and temporarily hide them to get more space for " "something else." ) collapsable_simple() self._code(inspect.getsource(collapsable_simple).split("\n", 1)[-1]) self._text("It's possible to use a custom header.") collapsable_custom(self._style_system) self._code(inspect.getsource(collapsable_custom).split("\n", 1)[-1]) self._text("The next example demonstrates how padding and margin work in the collapsable frame.") collapsable_layout(self._style_system) self._code(inspect.getsource(collapsable_layout).split("\n", 1)[-1]) self._caption("Examples", navigate_to) with ui.VStack(style=self._style_system): for i in range(2): with ui.HStack(): ui.Spacer(width=50) with ui.VStack(height=0): ui.Button("Left {}".format(i), height=0) ui.Button("Vertical {}".format(i), height=50) with ui.HStack(width=ui.Fraction(2)): ui.Button("Right {}".format(i)) ui.Button("Horizontal {}".format(i), width=ui.Fraction(2)) ui.Spacer(width=50) self._code( """ with ui.VStack(): for i in range(2): with ui.HStack(): ui.Spacer() with ui.VStack(height=0): ui.Button("Left {}".format(i), height=0) ui.Button("Vertical {}".format(i), height=50) with ui.HStack(width=ui.Fraction(2)): ui.Button("Right {}".format(i)) ui.Button("Horizontal {}".format(i), width=ui.Fraction(2)) ui.Spacer() """ ) self._caption("Placer", navigate_to) self._text( "Enable you to place a widget presisely with offset. Placer's property `draggable` allows changing " "the position of the child widget with dragging it with the mouse." ) with ui.ScrollingFrame( height=170, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, ): with ui.ZStack(): with ui.HStack(): for index in range(60): ui.Line(width=10, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.LEFT) with ui.VStack(): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) for index in range(15): ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) ui.Line( height=10, width=600, style={"color": cl.black, "border_width": 0.5}, alignment=ui.Alignment.TOP, ) with ui.Placer(offset_x=100, offset_y=10): ui.Button("moved 100px in X, and 10px in Y", width=0, height=20, name="placed") with ui.Placer(offset_x=200, offset_y=50): ui.Button("moved 200px X , and 50 Y", width=0, height=0) def set_text(widget, text): widget.text = text with ui.Placer(draggable=True, offset_x=300, offset_y=100): ui.Circle(radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed") placer = ui.Placer(draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120) with placer: with ui.ZStack(width=150, height=40): ui.Rectangle(name="placed") with ui.HStack(spacing=5): ui.Circle( radius=3, width=15, size_policy=ui.CircleSizePolicy.FIXED, style={"background_color": cl.white}, ) ui.Label("UP / Down", style={"color": cl.white, "font_size": 16.0}) offset_label = ui.Label("120", style={"color": cl.white}) placer.set_offset_y_changed_fn(lambda o: set_text(offset_label, str(o))) self._code( """ with ui.Placer( draggable=True, offset_x=300, offset_y=100): ui.Circle( radius=50, width=50, height=50, size_policy=ui.CircleSizePolicy.STRETCH, name="placed" ) placer = ui.Placer( draggable=True, drag_axis=ui.Axis.Y, offset_x=400, offset_y=120) with placer: with ui.ZStack( width=150, height=40, ): ui.Rectangle(name="placed") with ui.HStack(spacing=5): ui.Circle( radius=3, width=15, size_policy=ui.CircleSizePolicy.FIXED, style={"background_color": cl.white}, ) ui.Label( "UP / Down", style={ "color": cl.white, "font_size": 16.0 } ) offset_label = ui.Label( "120", style={"color": cl.white}) placer.set_offset_y_changed_fn( lambda o: set_text(offset_label, str(o))) """ ) self._text( "The following example shows the way to interact between three Placers to create a resizable rectangle. " "The rectangle can be moved on X-axis and can be resized with small side handles." ) self._text( "When multiple widgets fire the callbacks simultaneously, it's possible to collect the event data and " "process them one frame later using asyncio." ) with ui.ZStack(): placer_track(self, 0) placer_track(self, 1) self._code(inspect.getsource(placer_track).split("\n", 1)[-1]) self._text( "It's possible to set `offset_x` and `offset_y` in percents. It allows stacking the children to the " "proportions of the parent widget. If the parent size is changed, then the offset is updated accordingly." ) placer_percents(self) self._code(inspect.getsource(placer_percents).split("\n", 1)[-1]) self._caption("Visibility", navigate_to) self._text( "This property holds whether the widget is visible. Invisible widget is not rendered, and it doesn't take " "part in the layout. The layout skips it." ) self._text("In the following example click the button to hide it.") visibility() self._code(inspect.getsource(visibility).split("\n", 1)[-1]) self._caption("Direction", navigate_to) self._text( "It's possible to determine the direction of a stack with the property direction. The stack is able to " "change its direction dynamically." ) direction() self._code(inspect.getsource(direction).split("\n", 1)[-1]) ui.Spacer(height=50)
26,307
Python
34.647696
119
0.541415
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/canvas_frame_doc.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. # """The documentation for Scrolling Frame""" from omni import ui from .doc_page import DocPage import inspect SPACING = 5 TEXT = ( "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut " "labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco " "laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in " "voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." ) def simple_canvasframe(): IMAGE = "resources/icons/ov_logo_square.png" with ui.CanvasFrame(height=256): with ui.VStack(height=0, spacing=10): ui.Label(TEXT, name="text", word_wrap=True) ui.Button("Button") ui.Image(IMAGE, width=128, height=128) class CanvasFrameDoc(DocPage): """ document for Menu""" def create_doc(self, navigate_to=None): self._section_title("CanvasFrame") self._text( "CanvasFrame is the widget that allows the user to pan and zoom its children with a mouse. It has the layout " "that can be infinitely moved in any direction." ) with ui.Frame(style=self._style_system): simple_canvasframe() self._code(inspect.getsource(simple_canvasframe).split("\n", 1)[-1]) ui.Spacer(height=10)
1,903
Python
35.615384
122
0.705202
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/scripts/doc_page.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. # """The documentation of the omni.ui aka UI Framework""" # Add imports here that are needed in the _exec_code calls. from omni import ui from omni.ui import color as cl import omni.usd from pxr import Usd from pxr import UsdGeom import subprocess import sys SPACING = 5 class DocPage: """The Demo extension""" def __init__(self, extension_path): self._extension_path = extension_path self._style_system = { "Button": { "background_color": 0xFFE1E1E1, "border_color": 0xFFADADAD, "border_width": 0.5, "border_radius": 0.0, "margin": 5.0, "padding": 5.0, }, "Button.Label": {"color": 0xFF000000}, "Button:hovered": {"background_color": 0xFFFBF1E5, "border_color": 0xFFD77800}, "Button:pressed": {"background_color": 0xFFF7E4CC, "border_color": 0xFF995400, "border_width": 1.0}, } self._copy_context_menu = ui.Menu("Copy Context menu", name="this") def clean(self): """Should be called when the extesion us unloaded or reloaded""" pass def _show_copy_menu(self, x, y, button, modifier, text): """The context menu to copy the text""" # Display context menu only if the right button is pressed if button != 1: return def copy_text(text_value): # we need to find a cross plartform way currently Window Only subprocess.run(["clip.exe"], input=text_value.strip().encode("utf-8"), check=True) # Reset the previous context popup self._copy_context_menu.clear() with self._copy_context_menu: ui.MenuItem("Copy Code", triggered_fn=lambda t=text: copy_text(t)) # Show it self._copy_context_menu.show() def create_doc(self, navigate_to=None): """ Class should overide this methods. Args: navigate_to: The chapter it's necessary to navigate the scrollbar. """ pass def _text(self, text): """Create a formated paragraph of the text""" ui.Label(text, name="text", word_wrap=True, skip_draw_when_clipped=True) def _section_title(self, text): """Create a title separator""" with ui.ZStack(): ui.Rectangle(name="section") ui.Label(text, name="section", alignment=ui.Alignment.CENTER) def _caption(self, text, navigate_to=None): """Create a formated heading""" with ui.ZStack(): background = ui.Rectangle(name="caption") if navigate_to == text: background.scroll_here_y(0.0) ui.Label(text, name="caption", alignment=ui.Alignment.LEFT_CENTER) def _code(self, text, elided_text=False): """Create a code snippet""" stack = ui.ZStack() with stack: ui.Rectangle(name="code") label = ui.Label(text, name="code", skip_draw_when_clipped=True, elided_text=elided_text) if not sys.platform == "linux": stack.set_mouse_pressed_fn(lambda x, y, b, m, text=text: self._show_copy_menu(x, y, b, m, text)) return label def _exec_code(self, code): """Execute the code and create a snippet""" # Python magic to capture output of exec locals_from_execution = {} exec(f"class Execution():\n def __init__(self):\n{code}", None, locals_from_execution) self._first = locals_from_execution["Execution"]() self._code(code) def _image_table(self, code, description, description_width=ui.Fraction(1), code_width=ui.Fraction(1)): """Create a row of the table that demostrates images""" # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(): with ui.ZStack(width=140): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) with ui.VStack(): ui.Spacer(height=SPACING / 2) # Execute the provided code exec(code) ui.Spacer(height=SPACING / 2) ui.Spacer(width=SPACING / 2) with ui.ZStack(width=description_width): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) ui.Label(description, style={"margin": 5}, name="text", word_wrap=True) ui.Spacer(width=SPACING / 2) with ui.ZStack(width=code_width): ui.Rectangle(name="table") with ui.HStack(): ui.Spacer(width=SPACING / 2) with ui.VStack(): ui.Spacer(height=SPACING / 2) with ui.ZStack(): ui.Rectangle(name="code") ui.Label(f"\n\t{code}\n\n", name="code") ui.Spacer(height=SPACING / 2) ui.Spacer(width=SPACING / 2) def _shape_table(self, code, description, row_height=0): """Create a row of the table that demostrates images""" # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(height=row_height): with ui.ZStack(): ui.Rectangle(name="table") # Execute the provided code with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING * 2}}): ui.Rectangle(name="code") exec(code) with ui.ZStack(width=ui.Fraction(2)): ui.Rectangle(name="table") ui.Label(description, name="text", style={"margin": SPACING}, word_wrap=True) with ui.ZStack(width=300): ui.Rectangle(name="table") with ui.ZStack(name="margin", style={"ZStack::margin": {"margin": SPACING / 2}}): ui.Rectangle(name="code") ui.Label(f"\n\t{code}\n\n", name="code") def _table(self, selector, example, explanatoin, color=None): """Create a one row of a table""" localStyle = {} if color is not None: localStyle = {"color": color} # TODO: We need to use style padding instead of thousands of spacers with ui.HStack(height=0, style=localStyle): with ui.ZStack(width=100): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(selector, name="text") ui.Spacer(width=SPACING) with ui.ZStack(width=120): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(example, name="text") ui.Spacer(width=SPACING) with ui.ZStack(): ui.Rectangle(name="table") with ui.HStack(height=0): ui.Spacer(width=SPACING) ui.Label(explanatoin, name="text", word_wrap=True) ui.Spacer(width=SPACING)
7,721
Python
39.857143
112
0.553685
omniverse-code/kit/exts/omni.example.ui/omni/example/ui/tests/__init__.py
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .example_ui_test import TestExampleUi
471
Python
46.199995
76
0.81104
omniverse-code/kit/exts/omni.example.ui/docs/treeview.md
# TreeView ## Selection ## Drag-and-drop
44
Markdown
5.428571
16
0.636364
omniverse-code/kit/exts/omni.example.ui/docs/model.md
# Model The central component of the TreeView widget. It is the application's dynamic data structure, independent of the user interface, and it directly manages the nested data. It follows the Model-Dlegate-View pattern closely. It's abstract, and it defines the standard interface to be able to interoperate with the components of the model-view architecture. It is not supposed to be instantiated directly. Instead, the user should subclass it to create a new model. The item model doesn't return the data itself. Instead, it returns the value model that can contain any data type and supports callbacks. Thus, the model client can track the changes in both the item model and any value it holds. The item model can get both the value model and the nested items from any item. Therefore, the model is flexible to represent anything from color to complicated tree-table construction. ## Item Item is the object that is associated with the data entity of the model. The item should be created and stored by the model implementation. And can contain any data in it. Another option would be to use it as a raw pointer to the data. In any case, it's the choice of the model how to manage this class. ## Hierarchial Model Usually, the model is a hierarchical system where the item can have any number of child items. The model can be populated at the moment the user expands the item to save resources. The following example demonstrates that the model can be infinitely long. ```execute 200 class Item(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) self.children = None class Model(ui.AbstractItemModel): def __init__(self, *args): super().__init__() self._children = [Item(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: if not item.children: item.children = [Item(f"Child #{i}") for i in range(5)] return item.children return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._model = Model("Root", "Items") ui.TreeView(self._model, root_visible=False, style={"margin": 0.5}) ``` ## Nested Model Since the model doesn't keep any data and serves as an API protocol, sometimes it's very helpful to merge multiple models into one single model. The parent model should redirect the calls to the children. In the following example, three different models are merged into one. ```execute 200 class Item(ui.AbstractItem): def __init__(self, text, name, d=5): super().__init__() self.name_model = ui.SimpleStringModel(text) self.children = [Item(f"Child {name}{i}", name, d - 1) for i in range(d)] class Model(ui.AbstractItemModel): def __init__(self, name): super().__init__() self._children = [Item(f"Model {name}", name)] def get_item_children(self, item): return item.children if item else self._children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): return item.name_model class NestedItem(ui.AbstractItem): def __init__(self, source_item, source_model): super().__init__() self.source = source_item self.model = source_model self.children = None class NestedModel(ui.AbstractItemModel): def __init__(self): super().__init__() models = [Model("A"), Model("B"), Model("C")] self.children = [ NestedItem(i, m) for m in models for i in m.get_item_children(None)] def get_item_children(self, item): if item is None: return self.children if item.children is None: m = item.model item.children = [ NestedItem(i, m) for i in m.get_item_children(item.source)] return item.children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): return item.model.get_item_value_model(item.source, column_id) with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._model = NestedModel() ui.TreeView(self._model, root_visible=False, style={"margin": 0.5}) ``` ## Drag and Drop ### Drag If the model has the item to drag, the method `get_drag_mime_data` should be reimplemented. This method should return the string with the drag and drop payload. This data can be dropped to any model or to any `omni.ui` widget that accepts this data. ``` def get_drag_mime_data(self, item): ``` ### Drop The model supports drag and drop. The drag source can be an item from any model or any draggable data from omni.ui. When the cursor with draggable data enters the area of the model's item, the method `drop_accepted` is called where the model needs to decide if the data is compatible with the model. If the model can accept the drop, it should return `True`. After that if the user drops the data to the item, the method `drop` will be called. ``` def drop_accepted(self, target_item, source): ``` ``` def drop(self, target_item, source): ``` ```execute 200 class Item(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) def __repr__(self): return self.name_model.as_string class Model(ui.AbstractItemModel): def __init__(self, label, *args): super().__init__() self._children = [Item(t) for t in args] self._label = label def get_item_children(self, item): if item is not None: return [] return self._children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): return item.name_model def get_drag_mime_data(self, item): """Returns data for be able to drop this item somewhere""" return item.name_model.as_string def drop_accepted(self, target_item, source): """Return true to accept the current drop""" # Accept anything return True def drop(self, target_item, source): """Called when the user releases the mouse""" # Change text on the label self._label.text = f"Dropped {source} to {target_item}" label = ui.Label("Drop something to the following TreeView") with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._model = Model(label, *[f"Item #{i}" for i in range(50)]) ui.TreeView(self._model, root_visible=False, style={"margin": 0.5}) ```
7,577
Markdown
31.805195
81
0.671902
omniverse-code/kit/exts/omni.example.ui/docs/CHANGELOG.md
# Changelog The documentation for omni.example.ui ## [1.2.3] - 2023-01-27 ### Fixed - Fixed config. Removed "omni.example.ui.tests" ## [1.2.2] - 2022-10-18 ### Added - A note about color syntax ### Changed - Old hex color syntax to new omni.ui.color syntax ## [1.2.1] - 2022-06-27 ### Added - A small note about fonts ## [1.2.0] - 2021-12-17 ### Added - Dependency to `omni.kit.documentation.builder` to show md files - Model-Delegate-View docs ## [1.1.1] - 2021-12-06 ### Fixed - The bug in the logo alignment - Removed a warning of AbstractValueModel ### Changed - Color scheme
586
Markdown
18.566666
65
0.672355
omniverse-code/kit/exts/omni.example.ui/docs/overview.md
# Overview MDV (Model-Delegate-View) is a pattern commonly used in `omni.ui` to implement user interfaces with data-controlling logic. It highlights a separation between the data and the display logic. This separation of concepts provides for better maintenance of the code. It closely follows the MVC pattern with a slightly different separation of components. Unlike MVC, the View component of MDV takes responsibility of Controller, takes control of the layout, and routes the Delegate component that controls the look. The three parts of the MDV software-design pattern can be described as follows: 1. Model: The central component of the system. Manages data and logic. It creates items that are used as pointers to the specific parts of the data layer. 2. Delegate: Creates widgets and defines the look. 3. View: Handles layout, holds the widgets, and coordinates Model and Delegate. ## Model-Delegate-View in TreeView TreeView is the MDV widget that takes advantage of the MDV pattern. For simplicity, this document describes how the pattern applies to TreeView, and it can be similarly applied to any MDV-based widget. The three parts are needed to create a nice TreeView. ![](../data/mvd.png) 1. Model: it's necessary to reimplement the class `ui.AbstractItemModel`. 2. Delegate: it's necessary to reimplement the class `ui.AbstractItemDelegate`. 3. View: it's necessary to provide the model and the delegate components to `ui.TreeView`. There is no way to reimplement it. ## MDV pipeline in Stage Widget To describe the MDV pipeline in production, let's focus on the "visibility" button of Stage Widget. Stage Widget is a part of the extension `omni.kit.widget.stage`. It uses a model that is watching the stage, the delegate that is written to match the design document, and a standard TreeView that coordinates the model and the delegate. ![](../data/mdv-stage-pipeline.png) The main idea is that the model doesn't keep the data (visibility value). The model is an API protocol that is the bridge between UsdStage and TreeView. When the user changes the visibility, the model changes it in UsdStage, which triggers UsdNotice. And if something is changed in UsdStage, UsdNotice makes the model dirty. When TreeView recognizes the model is dirty, it calls the delegate to recreate the specific piece of layout. And the delegate creates a new widget and queries the model for visibility, and the model queries it from UsdStage.
2,458
Markdown
42.910714
88
0.78926
omniverse-code/kit/exts/omni.example.ui/docs/delegate.md
# Delegate Delegate is the representation layer. Delegate is called by the view to create a specific piece of the user interface. TreeView calls the delegate to create the widgets for the header and per item in the column. To ## Item ![](../data/mdv-delegate-items.png) Each row in TreeView is the representation of the model's item. ## Column ![](../data/mdv-delegate-columns.png) Each model's item can have multiple data fields. To display them, TreeView uses columns. ## Level ![](../data/mdv-delegate-level.png) The level is the number of parent items for the given item. ## Branch Widget Header ![](../data/mdv-delegate-widget.png) The branch is the widget that makes TreeView expand or collapse the current item. ## Example To reimplement a delegate, it's necessary to reimplement the following methods of `ui.AbstractItemDelegate`: ``` def build_branch(self, model, item, column_id, level, expanded): ``` ``` def build_widget(self, model, item, column_id, level, expanded): ``` ``` def build_header(self, column_id): ``` ```execute 200 ## class Item(ui.AbstractItem): """Single item of the model""" def __init__(self, text): super().__init__() self.name_model = ui.SimpleStringModel(text) self.children = None class Model(ui.AbstractItemModel): def __init__(self, *args): super().__init__() self._children = [Item(t) for t in args] def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is not None: if not item.children: item.children = [Item(f"Child #{i}") for i in range(5)] return item.children return self._children def get_item_value_model_count(self, item): """The number of columns""" return 1 def get_item_value_model(self, item, column_id): """ Return value model. It's the object that tracks the specific value. In our case we use ui.SimpleStringModel. """ return item.name_model ## class Delegate(ui.AbstractItemDelegate): """ Delegate is the representation layer. TreeView calls the methods of the delegate to create custom widgets for each item. """ def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" # Offset depents on level text = " " * (level + 1) # > and v symbols depending on the expanded state if expanded: text += "v " else: text += "> " ui.Label(text, height=22, alignment=ui.Alignment.CENTER, tooltip="Branch") def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" ui.Label( model.get_item_value_model(item, column_id).as_string, tooltip="Widget" ) def build_header(self, column_id): """Build the header""" ui.Label("Header", tooltip="Header", height=25) with ui.ScrollingFrame( height=200, horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, style_type_name_override="TreeView", ): self._model = Model("Root", "Items") self._delegate = Delegate() ui.TreeView( self._model, delegate=self._delegate, root_visible=False, header_visible=True ) ```
3,476
Markdown
25.746154
85
0.638953
omniverse-code/kit/exts/omni.kit.window.commands/PACKAGE-LICENSES/omni.kit.window.commands-LICENSE.md
Copyright (c) 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.
412
Markdown
57.999992
74
0.839806
omniverse-code/kit/exts/omni.kit.window.commands/config/extension.toml
[package] version = "0.2.4" category = "Core" authors = ["NVIDIA"] title = "Commands Utils" description="Commands history viewer, commands execution script generator and registered commands viewer" repository = "" keywords = ["kit", "commands"] changelog = "docs/CHANGELOG.md" [dependencies] "omni.kit.clipboard" = {} "omni.kit.commands" = {} "omni.kit.pip_archive" = {} "omni.ui" = {} "omni.kit.menu.utils" = {} [[python.module]] name = "omni.kit.window.commands" [settings] exts."omni.kit.window.commands".windowOpenByDefault = false [[test]] args = [ "--/app/window/dpiScaleOverride=1.0", "--/app/window/scaleToMonitor=false", "--no-window" ] dependencies = [ "omni.kit.renderer.capture" ]
715
TOML
19.457142
105
0.678322
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/main.py
from collections import defaultdict from inspect import isclass from functools import partial import omni.kit.commands import omni.kit.undo from omni import ui from .history import HistoryModel, HistoryDelegate, MainItem from .search import SearchModel, SearchDelegate, CommandItem, Columns class Window: def __init__(self, title, menu_path): self._menu_path = menu_path self._win_history = ui.Window(title, width=700, height=500) self._win_history.set_visibility_changed_fn(self._on_visibility_changed) self._win_search = None self._search_frame = None self._doc_frame = None self._history_delegate = HistoryDelegate() self._search_delegate = SearchDelegate() self._build_ui() omni.kit.commands.subscribe_on_change(self._update_ui) self._update_ui() def on_shutdown(self): self._win_history = None self._win_search = None self._search_frame = None self._doc_frame = None self._history_delegate = None self._search_delegate = None omni.kit.commands.unsubscribe_on_change(self._update_ui) def show(self): self._win_history.visible = True self._win_history.focus() def hide(self): self._win_history.visible = False if self._win_search is not None: self._win_search.visible = False def _on_visibility_changed(self, visible): if not visible: omni.kit.ui.get_editor_menu().set_value(self._menu_path, False) if self._win_search is not None: self._win_search.visible = False def _build_ui(self): with self._win_history.frame: with ui.VStack(): with ui.HStack(height=20): ui.Button("Clear history", width=60, clicked_fn=self._clear_history) ui.Button("Search commands", width=60, clicked_fn=self._show_registered) with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ): self._history_model = HistoryModel() self._history_tree_view = ui.TreeView( self._history_model, delegate=self._history_delegate, root_visible=False, style={"TreeView.Item::error": {"color": 0xFF0000BB}}, column_widths=[ui.Fraction(1)], ) self._history_tree_view.set_mouse_double_clicked_fn(self._on_double_click) with ui.HStack(height=20): ui.Label("Generate script to clipboard from:", width=0) ui.Button("Top-level commands", width=60, clicked_fn=partial(self._copy_to_clipboard, False)) ui.Button("Selected commands", width=60, clicked_fn=partial(self._copy_to_clipboard, True)) def _on_double_click(self, x, y, b, m): if len(self._history_tree_view.selection) <= 0: return item = self._history_tree_view.selection[0] if isinstance(item, MainItem): self._history_tree_view.set_expanded(item, not self._history_tree_view.is_expanded(item), False) def _copy_to_clipboard(self, only_selected): omni.kit.clipboard.copy(self._generate_command_script(only_selected)) def _clear_history(self): omni.kit.undo.clear_history() self._history_model._commands_changed() def _show_registered(self): if self._win_search is None: self._win_search = ui.Window( "Search Commands", width=700, height=500, dockPreference=ui.DockPreference.MAIN ) with self._win_search.frame: with ui.VStack(): with ui.HStack(height=20): ui.Label("Find: ", width=0) self._search_field = ui.StringField() self._search_field.model.add_value_changed_fn(lambda _: self._refresh_list()) with ui.HStack(height=300): self._search_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, style_type_name_override="TreeView", ) with self._search_frame: self._search_tree_model = SearchModel() self._search_tree_view = ui.TreeView( self._search_tree_model, delegate=self._search_delegate, selection_changed_fn=self._on_selection_changed, root_visible=False, header_visible=True, columns_resizable=True, column_widths=[x.width for x in Columns.ORDER], ) self._doc_frame = ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_AS_NEEDED, ) self._refresh_list() self._win_search.visible = True self._win_search.focus() def _on_selection_changed(self, selected_items): with self._doc_frame: with ui.VStack(height=40): for item in selected_items: if isinstance(item, CommandItem): ui.Label(f"{item.command_model.as_string}{item.class_sig}", height=30) ui.Label(f"Documentation:", height=30) if item.doc is None or item.doc == omni.kit.commands.Command.__doc__: ui.Label("\n\t<None>") else: ui.Label(item.doc.strip()) def _update_ui(self): self._history_model._commands_changed() self._refresh_list() # TODO: check if this is called too much def _refresh_list(self): if self._search_frame is None: return search_str = self._search_field.model.get_value_as_string().lower().strip() self._search_tree_model._clear_commands() commands = omni.kit.commands.get_commands() for cmd_list in commands.values(): for command in cmd_list.values(): if search_str == "" or command.__name__.lower().find(search_str) != -1: if self._search_tree_model: class_sig = omni.kit.commands.get_command_class_signature(command.__name__) self._search_tree_model._add_command(CommandItem(command, class_sig)) self._search_tree_view.clear_selection() self._search_tree_model._commands_changed() def _generate_command_script(self, only_selected): history = omni.kit.undo.get_history().values() imports = "import omni.kit.commands\n" code_str = "" arg_imports = defaultdict(set) def parse_module_name(name): if name == "builtins": return nonlocal imports lst = name.split(".") if len(lst) == 1: imports += "import " + name + "\n" else: arg_imports[lst[0]].add(".".join(lst[1:])) def arg_import(val): if isclass(val): parse_module_name(val.__module__) else: parse_module_name(val.__class__.__module__) return val def gen_cmd_str(cmd): if len(cmd.kwargs.items()) > 0: args = ",\n\t".join(["{}={!r}".format(k, arg_import(v)) for k, v in cmd.kwargs.items()]) return f"\nomni.kit.commands.execute('{cmd.name}',\n\t{args})\n" else: return f"\nomni.kit.commands.execute('{cmd.name}')\n" # generate a script executing top-level commands or all selected commands if only_selected: for item in self._history_tree_view.selection: if isinstance(item, MainItem): code_str += gen_cmd_str(item._data) else: for cmd in history: if cmd.level == 0: code_str += gen_cmd_str(cmd) for k, v in arg_imports.items(): imports += f"from {k} import " + ", ".join(v) + "\n" return imports + code_str
8,837
Python
41.085714
113
0.539097
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/search.py
import inspect from pathlib import Path import carb.settings import omni.ext import omni.kit.app from omni import ui class SearchModel(ui.AbstractItemModel): """ Represents the list of commands registered in Kit. It is used to make a single level tree appear like a simple list. """ def __init__(self): super().__init__() self._commands = [] def _clear_commands(self): self._commands = [] def _commands_changed(self): self._item_changed(None) def _add_command(self, item): if item and isinstance(item, CommandItem): self._commands.append(item) def get_item_children(self, item): """Returns all the children when the widget asks it.""" if item is None: return self._commands return item.children def get_item_value_model_count(self, item): """The number of columns""" return Columns.get_count() def get_item_value_model(self, item, column_id): """Return value model.""" if item and isinstance(item, CommandItem): return Columns.get_model(item, column_id) class SearchDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")} def build_widget(self, model, item, column_id, level, expanded): value_model = model.get_item_value_model(item, column_id) text = value_model.as_string ui.Label(text, style_type_name_override="TreeView.Item") def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=16 * (level + 2), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.Image( str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=4) def build_header(self, column_id): label = Columns.get_label(column_id) ui.Label(label, height=30, width=20) class CommandItem(ui.AbstractItem): """Single item of the model""" def __init__(self, command, class_sig): super().__init__() self.command_model = ui.SimpleStringModel(command.__name__) manager = omni.kit.app.get_app().get_extension_manager() ext_id = manager.get_extension_id_by_module(command.__module__) ext_name = omni.ext.get_extension_name(ext_id) if ext_id else "Unknown" self.extension_model = ui.SimpleStringModel(ext_name) self.undo_model = ui.SimpleBoolModel(hasattr(command, "undo") and inspect.isfunction(command.undo)) self.doc = command.__doc__ or (command.__init__ is not None and command.__init__.__doc__) self.class_sig = class_sig self.children = [] # uncomment these lines if child items are needed later on # if doc is not None: # self.children.append(CommandChildItem(doc)) class CommandChildItem(CommandItem): def __init__(self, arg): super().__init__(str(arg)) self.children = [] class Columns: """ Store UI info about the columns in one place so it's easier to keep in """ class ColumnData: def __init__(self, label, column, width, attrib_name): self.label = label self.column = column self.width = width self.attrib_name = attrib_name Command = ColumnData("Command", 0, ui.Fraction(1), "command_model") Extension = ColumnData("Extension", 1, ui.Pixel(200), "extension_model") CanUndo = ColumnData("Can Undo", 2, ui.Pixel(80), "undo_model") ORDER = [Command, Extension, CanUndo] @classmethod def get_count(cls): return len(cls.ORDER) @classmethod def get_label(cls, index): return cls.ORDER[index].label @classmethod def get_model(cls, entry: CommandItem, index): return getattr(entry, cls.ORDER[index].attrib_name)
4,521
Python
33.519084
119
0.610263
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/extension.py
import carb.settings import omni.ext import omni.kit.ui from .main import Window EXTENSION_NAME = "Commands" class Extension(omni.ext.IExt): def on_startup(self): self._menu_path = f"Window/{EXTENSION_NAME}" self._window = None open_by_default = carb.settings.get_settings().get("exts/omni.kit.window.commands/windowOpenByDefault") self._menu = omni.kit.ui.get_editor_menu().add_item( self._menu_path, self._on_menu_click, True, value=open_by_default ) if open_by_default: self._on_menu_click(None, True) def on_shutdown(self): if self._window is not None: self._window.on_shutdown() self._menu = None self._window = None def _on_menu_click(self, menu, toggled): if toggled: if self._window is None: self._window = Window(EXTENSION_NAME, self._menu_path) else: self._window.show() else: if self._window is not None: self._window.hide()
1,062
Python
28.527777
111
0.582863
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/history.py
from pathlib import Path import carb.settings from omni import ui import omni.kit.undo class HistoryData: def __init__(self): self._data = omni.kit.undo.get_history() if len(self._data): self._curr = next(iter(self._data)) self._last = next(reversed(self._data)) else: self._curr = 0 self._last = -1 def is_not_empty(self): return self._curr <= self._last def get_next(self): self._curr += 1 return self._data[self._curr - 1] def is_next_lower(self, level): return self._data[self._curr].level > level class HistoryModel(ui.AbstractItemModel): def __init__(self): super().__init__() self._root = MainItem(None, HistoryData()) def _commands_changed(self): self._root = MainItem(None, HistoryData()) self._item_changed(None) def get_item_children(self, item): if item is None: return self._root.children return item.children def get_item_value_model_count(self, item): return 1 def get_item_value_model(self, item, column_id): if column_id == 0: return item.name_model class HistoryDelegate(ui.AbstractItemDelegate): def __init__(self): super().__init__() self._icon_path = Path(__file__).parent.parent.parent.parent.parent.joinpath("icons") self._style = carb.settings.get_settings().get_as_string("/persistent/app/window/uiStyle") or "NvidiaDark" # Read all the svg files in the directory self._icons = {icon.stem: icon for icon in self._icon_path.joinpath(self._style).glob("*.svg")} def build_widget(self, model, item, column_id, level, expanded): """Create a widget per column per item""" value_model = model.get_item_value_model(item, column_id) # call out commands that had errors text = value_model.as_string name = "" if hasattr(item, "_data") and hasattr(item._data, "error") and item._data.error: text = "[ERROR] " + text name = "error" ui.Label(text, name=name, style_type_name_override="TreeView.Item") def build_branch(self, model, item, column_id, level, expanded): """Create a branch widget that opens or closes subtree""" if column_id == 0: with ui.HStack(width=16 * (level + 2), height=0): ui.Spacer() if model.can_item_have_children(item): # Draw the +/- icon image_name = "Minus" if expanded else "Plus" ui.Image( str(self._icons.get(image_name)), width=10, height=10, style_type_name_override="TreeView.Item" ) ui.Spacer(width=4) def build_header(self, column_id): pass class MainItem(ui.AbstractItem): def __init__(self, command_data, history): super().__init__() self._data = command_data if command_data is None: self._create_root(history) else: self._create_node(history) def _create_root(self, history): self.children = [] while history.is_not_empty(): self.children.append(MainItem(history.get_next(), history)) def _create_node(self, history): self.name_model = ui.SimpleStringModel(self._data.name) self.children = [ParamItem(arg, val) for arg, val in self._data.kwargs.items()] while history.is_not_empty() and history.is_next_lower(self._data.level): next_command = history.get_next() self.children.append(MainItem(next_command, history)) class ParamItem(ui.AbstractItem): def __init__(self, arg, val): super().__init__() self.name_model = ui.SimpleStringModel(str(arg) + "=" + str(val)) self.children = []
3,889
Python
32.534482
119
0.580869
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/tests/__init__.py
from .test_extension import *
30
Python
14.499993
29
0.766667
omniverse-code/kit/exts/omni.kit.window.commands/omni/kit/window/commands/tests/test_extension.py
## Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. ## ## NVIDIA CORPORATION and its licensors retain all intellectual property ## and proprietary rights in and to this software, related documentation ## and any modifications thereto. Any use, reproduction, disclosure or ## distribution of this software and related documentation without an express ## license agreement from NVIDIA CORPORATION is strictly prohibited. ## import omni.kit.test import re from pathlib import Path import omni.kit.app import omni.kit.commands import omni.kit.undo from omni.kit.window.commands import Window from omni.ui.tests.test_base import OmniUiTest _result = [] class TestAppendCommand(omni.kit.commands.Command): def __init__(self, x, y): self._x = x self._y = y def do(self): global _result _result.append(self._x) _result.append(self._y) def undo(self): global _result del _result[-1] del _result[-1] class TestCommandsWindow(OmniUiTest): # Before running each test async def setUp(self): await super().setUp() extension_path = omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__) self._golden_img_dir = Path(extension_path).joinpath("data").joinpath("tests").absolute() # make sure we are starting from a clean state omni.kit.undo.clear_stack() # Register all commands omni.kit.commands.register(TestAppendCommand) # After running each test async def tearDown(self): # Unregister all commands omni.kit.commands.unregister(TestAppendCommand) await super().tearDown() async def test_simple_command(self): window = await self.create_test_window(1000, 600) with window.frame: win = Window("Commands", "Commands") win.show() global _result # Execute and undo _result = [] omni.kit.commands.execute("TestAppend", x=1, y=2) self.assertListEqual(_result, [1, 2]) omni.kit.undo.undo() self.assertListEqual(_result, []) script = """import omni.kit.commands omni.kit.commands.execute('TestAppend', x=1, y=2) omni.kit.commands.execute('Undo')""" result = win._generate_command_script(False) # strip all whitespaces to ease our comparison s = re.sub("[\s+]", "", script) r = re.sub("[\s+]", "", result) # test script self.assertEqual(s, r) for i in range(50): await omni.kit.app.get_app().next_update_async() # test image await self.finalize_test( golden_img_dir=self._golden_img_dir, golden_img_name="test_simple_command.png", use_log=False )
2,862
Python
28.822916
110
0.620196
omniverse-code/kit/exts/omni.kit.window.commands/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.2.4] - 2022-11-17 ### Changes - Switched out pyperclip for linux-friendly copy & paste ## [0.2.3] - 2022-09-22 ### Fixes - Make test pass again by allowing more time for SVG load. ## [0.2.2] - 2022-06-07 ### Fixes - Get extension name from the extension manager. ## [0.2.1] - 2022-05-09 ### Changes - Added tests ## [0.2.0] - 2021-12-16 ### Changes - New TreeView for the search window that provide more details ## [0.1.1] - 2021-02-10 ### Changes - Updated StyleUI handling ## [0.1.0] - 2020-07-30 ### Added - initial implementation
641
Markdown
19.062499
80
0.656786
omniverse-code/kit/exts/omni.kit.window.commands/docs/index.rst
omni.kit.window.commands ########################### * Commands history view. * Script generator for the execution of top-level or selected commands. * Full-text search in names of all currently registered commands. .. toctree:: :maxdepth: 1 CHANGELOG
272
reStructuredText
23.81818
75
0.647059
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/renderer_capture/__init__.py
from omni.kit.renderer_capture import *
40
Python
19.49999
39
0.8
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/__init__.py
from .scripts.extension import *
33
Python
15.999992
32
0.787879
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/scripts/extension.py
import carb.settings import omni.ext import omni.kit.renderer_capture class Extension(omni.ext.IExt): def __init__(self): omni.ext.IExt.__init__(self) pass def on_startup(self): self._settings = carb.settings.get_settings() self._settings.set_default_bool("/exts/omni.kit.renderer.capture/autostartCapture", True) self._autostart = self._settings.get("/exts/omni.kit.renderer.capture/autostartCapture") if self._autostart: self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface() self._renderer_capture.startup() def on_shutdown(self): if self._autostart: self._renderer_capture.shutdown() self._renderer_capture = None
772
Python
31.208332
99
0.65544
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/__init__.py
from .test_renderer_capture import *
37
Python
17.999991
36
0.783784
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer/capture/tests/test_renderer_capture.py
import os import sys import inspect import pathlib import importlib import carb import carb.dictionary import carb.settings import carb.tokens import omni.appwindow import omni.kit.app import omni.kit.test import omni.kit.renderer.bind import omni.kit.renderer_capture import omni.kit.renderer_capture_test OUTPUTS_DIR = omni.kit.test.get_test_output_path() USE_TUPLES = True # Ancient hack coming from dark times SET_ALPHA_TO_1_SETTING_PATH = "/app/captureFrame/setAlphaTo1" class RendererCaptureTest(omni.kit.test.AsyncTestCase): async def setUp(self): self._settings = carb.settings.get_settings() self._dict = carb.dictionary.acquire_dictionary_interface() self._app_window_factory = omni.appwindow.acquire_app_window_factory_interface() self._renderer = omni.kit.renderer.bind.acquire_renderer_interface() self._renderer_capture = omni.kit.renderer_capture.acquire_renderer_capture_interface() self._renderer_capture_test = omni.kit.renderer_capture_test.acquire_renderer_capture_test_interface() self._renderer.startup() self._renderer_capture.startup() self._renderer_capture_test.startup() def __test_name(self) -> str: return f"{self.__class__.__name__}.{inspect.stack()[1][3]}" async def tearDown(self): self._renderer_capture_test.shutdown() self._renderer_capture.shutdown() self._renderer.shutdown() self._renderer_capture_test = None self._renderer_capture = None self._renderer = None self._app_window_factory = None self._settings = None def _create_and_attach_window(self, w, h, window_type): app_window = self._app_window_factory.create_window_by_type(window_type) app_window.startup_with_desc( title="Renderer capture test OS window", width=w, height=h, x=omni.appwindow.POSITION_CENTERED, y=omni.appwindow.POSITION_CENTERED, decorations=True, resize=True, always_on_top=False, scale_to_monitor=False, dpi_scale_override=1.0 ) self._app_window_factory.set_default_window(app_window) self._renderer.attach_app_window(app_window) return app_window def _detach_and_destroy_window(self, app_window): self._app_window_factory.set_default_window(None) self._renderer.detach_app_window(app_window) app_window.shutdown() def _capture_callback(self, buf, buf_size, w, h, fmt): if USE_TUPLES: self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_rgba_tuples(buf, buf_size, w, h, fmt) else: self._captured_buffer = omni.kit.renderer_capture.convert_raw_bytes_to_list(buf, buf_size, w, h, fmt) self._captured_buffer_w = w self._captured_buffer_h = h self._captured_buffer_fmt = fmt def _get_pil_image_from_captured_data(self): from PIL import Image image = Image.new('RGBA', [self._captured_buffer_w, self._captured_buffer_h]) if USE_TUPLES: image.putdata(self._captured_buffer) else: buf_channel_it = iter(self._captured_buffer) captured_buffer_tuples = list(zip(buf_channel_it, buf_channel_it, buf_channel_it, buf_channel_it)) image.putdata(captured_buffer_tuples) return image def _get_pil_image_size_data(self, path): from PIL import Image image = Image.open(path) image_data = list(image.getdata()) image_w, image_h = image.size image.close() return image_w, image_h, image_data def _disable_alpha_to_1(self): self._settings.set_default(SET_ALPHA_TO_1_SETTING_PATH, False) self._setAlphaTo1 = self._settings.get(SET_ALPHA_TO_1_SETTING_PATH) self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, False) def _restore_alpha_to_1(self): self._settings.set(SET_ALPHA_TO_1_SETTING_PATH, self._setAlphaTo1) async def test_0001_capture_swapchain_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 8 TEST_IMG_H = 8 TEST_COLOR = (255, 0, 0, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None async def test_0002_capture_swapchain_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 16 TEST_IMG_H = 16 TEST_COLOR = (0, 255, 255, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._detach_and_destroy_window(app_window) app_window = None async def test_0003_capture_texture_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 4 TEST_IMG_H = 4 TEST_COLOR = (255, 255, 0, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_texture(TEST_IMG_PATH, texture) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0004_capture_texture_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 6 TEST_IMG_H = 6 TEST_COLOR = (255, 0, 255, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) texture = self._renderer_capture_test.create_solid_color_texture(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_texture_callback(self._capture_callback, texture) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0005_capture_rp_resource_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 5 TEST_IMG_H = 5 TEST_COLOR = (0, 255, 0, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_rp_resource(TEST_IMG_PATH, rp_resource) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0006_capture_rp_resource_callback(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 6 TEST_IMG_H = 6 TEST_COLOR = (0, 0, 255, 255) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) rp_resource = self._renderer_capture_test.create_solid_color_rp_resource(test_color_unit, TEST_IMG_W, TEST_IMG_H) self._renderer_capture.capture_next_frame_rp_resource_callback(self._capture_callback, rp_resource) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0007_capture_os_swapchain_to_file(self): test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 256 TEST_IMG_H = 32 TEST_COLOR = (255, 128, 0, 255) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.OS) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None async def test_0008_capture_transparent_swapchain_to_file(self): self._disable_alpha_to_1() test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 8 TEST_IMG_H = 8 TEST_COLOR = (255, 0, 0, 0) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain(TEST_IMG_PATH, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image_size_data = self._get_pil_image_size_data(TEST_IMG_PATH) self.assertEqual(len(image_size_data), 3) self.assertEqual(image_size_data[0], TEST_IMG_W) self.assertEqual(image_size_data[1], TEST_IMG_H) self.assertEqual(image_size_data[2][0], TEST_COLOR) self._detach_and_destroy_window(app_window) app_window = None self._restore_alpha_to_1() async def test_0009_capture_transparent_swapchain_callback(self): self._disable_alpha_to_1() test_name = self.__test_name() TEST_IMG_PATH = os.path.join(OUTPUTS_DIR, test_name + ".png") TEST_IMG_W = 16 TEST_IMG_H = 16 TEST_COLOR = (0, 255, 255, 0) app_window = self._create_and_attach_window(TEST_IMG_W, TEST_IMG_H, omni.appwindow.WindowType.VIRTUAL) test_color_unit = tuple(c / 255.0 for c in TEST_COLOR) self._renderer.set_clear_color(app_window, test_color_unit) self._renderer_capture.capture_next_frame_swapchain_callback(self._capture_callback, app_window) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) image = self._get_pil_image_from_captured_data() image.save(TEST_IMG_PATH) self.assertEqual(self._captured_buffer_w, TEST_IMG_W) self.assertEqual(self._captured_buffer_h, TEST_IMG_H) if USE_TUPLES: self.assertEqual(self._captured_buffer[0], TEST_COLOR) else: self.assertEqual(self._captured_buffer[0], TEST_COLOR[0]) self.assertEqual(self._captured_buffer[1], TEST_COLOR[1]) self.assertEqual(self._captured_buffer[2], TEST_COLOR[2]) self.assertEqual(self._captured_buffer[3], TEST_COLOR[3]) self._detach_and_destroy_window(app_window) app_window = None self._restore_alpha_to_1() async def __test_capture_rp_resource_with_format(self, format_desc_item): test_name = self.__test_name() TEST_IMG_PATH_NOEXT = os.path.join(OUTPUTS_DIR, test_name) TEST_IMG_W = 15 TEST_IMG_H = 15 TEST_COLOR = (12.34, 34.56, 67.89, 128.0) app_window = self._create_and_attach_window(12, 12, omni.appwindow.WindowType.VIRTUAL) files = {} format_desc_item["format"] = "exr" rp_resource = self._renderer_capture_test.create_solid_color_rp_resource_hdr(TEST_COLOR, TEST_IMG_W, TEST_IMG_H) async def capture(): filename = TEST_IMG_PATH_NOEXT + "_" + format_desc_item["compression"] + ".exr" files[format_desc_item["compression"]] = filename self._renderer_capture.capture_next_frame_rp_resource_to_file(filename, rp_resource, None, format_desc_item) await omni.kit.app.get_app().next_update_async() self._renderer_capture.wait_async_capture(app_window) format_desc_item["compression"] = "none" await capture() format_desc_item["compression"] = "rle" await capture() format_desc_item["compression"] = "b44" await capture() file_sizes = {} for file_key, file_path in files.items(): file_sizes[file_key] = os.path.getsize(file_path) self.assertNotEqual(file_sizes["none"], file_sizes["rle"]) self.assertNotEqual(file_sizes["none"], file_sizes["b44"]) self.assertNotEqual(file_sizes["rle"], file_sizes["b44"]) self._renderer_capture_test.cleanup_gpu_resources() self._detach_and_destroy_window(app_window) app_window = None async def test_0010_capture_rp_resource_hdr_to_file_carb_dict(self): format_desc_item = self._dict.create_item(None, "", carb.dictionary.ItemType.DICTIONARY) await self.__test_capture_rp_resource_with_format(format_desc_item) async def test_0010_capture_rp_resource_hdr_to_file_py_dict(self): format_desc_item = {} await self.__test_capture_rp_resource_with_format(format_desc_item)
17,721
Python
39.277273
121
0.639806
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture_test/__init__.py
import functools from ._renderer_capture_test import * # Cached interface instance pointer @functools.lru_cache() def get_renderer_capture_test_interface() -> IRendererCaptureTest: if not hasattr(get_renderer_capture_test_interface, "renderer_capture_test"): get_renderer_capture_test_interface.renderer_capture_test = acquire_renderer_capture_test_interface() return get_renderer_capture_test_interface.renderer_capture_test
444
Python
39.454542
109
0.783784
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/_renderer_capture.pyi
from __future__ import annotations import omni.kit.renderer_capture._renderer_capture import typing import omni.appwindow._appwindow import omni.gpu_foundation_factory._gpu_foundation_factory __all__ = [ "IRendererCapture", "Metadata", "acquire_renderer_capture_interface", "convert_raw_bytes_to_list", "convert_raw_bytes_to_rgba_tuples" ] class IRendererCapture(): def capture_next_frame_rp_resource(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture RTX resource manager RpResource and save to a file. """ def capture_next_frame_rp_resource_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available. """ def capture_next_frame_rp_resource_list_callback(self, callback: typing.Callable[[typing.List[int], int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture RTX resource manager RpResource and trigger a callback when capture buffer is available. """ def capture_next_frame_rp_resource_to_file(self, filepath: str, resource: omni.gpu_foundation_factory._gpu_foundation_factory.RpResource, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None: """ Request capture RTX resource manager RpResource and save to a file. """ def capture_next_frame_swapchain(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture swapchain and save to a file. """ def capture_next_frame_swapchain_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture swapchain and trigger a callback when capture buffer is available. """ def capture_next_frame_swapchain_to_file(self, filepath: str, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None: """ Request capture swapchain and save to a file. """ def capture_next_frame_texture(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture texture and save to a file. """ def capture_next_frame_texture_callback(self, callback: typing.Callable[[capsule, int, int, int, omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat], None], texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, metadata: Metadata = None) -> None: """ Request capture texture and trigger a callback when capture buffer is available. """ def capture_next_frame_texture_to_file(self, filepath: str, texture: omni.gpu_foundation_factory._gpu_foundation_factory.Texture = None, app_window: omni.appwindow._appwindow.IAppWindow = None, format_desc: object = None, metadata: Metadata = None) -> None: """ Request capture texture and save to a file. """ def capture_next_frame_using_render_product(self, viewport_handle: int, filepath: str, render_product: str) -> None: """ Request capture of all resources in render product """ def request_callback_memory_ownership(self) -> bool: """ Request memory ownership of a buffer passed into callback. Should be called from within a callback. """ def set_capture_sync(self, sync: bool, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool: """ Set synchronous capture mode. """ def shutdown(self) -> bool: """ Internal function. Shuts down capture interface. """ def start_frame_updates(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> bool: """ Starts per frame updates to collect capturing related data during each frame, such as FPS. """ def startup(self) -> bool: """ Internal function. Starts up capture interface. """ def wait_async_capture(self, app_window: omni.appwindow._appwindow.IAppWindow = None) -> None: """ Wait for asynchronous capture to complete. """ pass class Metadata(): pass def acquire_renderer_capture_interface(*args, **kwargs) -> typing.Any: pass def convert_raw_bytes_to_list(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[int]: pass def convert_raw_bytes_to_rgba_tuples(arg0: capsule, arg1: int, arg2: int, arg3: int, arg4: omni.gpu_foundation_factory._gpu_foundation_factory.TextureFormat) -> typing.List[tuple]: pass
5,729
unknown
59.957446
361
0.692617
omniverse-code/kit/exts/omni.kit.renderer.capture/omni/kit/renderer_capture/__init__.py
from ._renderer_capture import *
33
Python
15.999992
32
0.757576
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTextureToLinearArray.rst
.. _omni_syntheticdata_SdTextureToLinearArray_1: .. _omni_syntheticdata_SdTextureToLinearArray: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Texture To Linear Array :keywords: lang-en omnigraph node internal syntheticdata sd-texture-to-linear-array Sd Texture To Linear Array ========================== .. <description> SyntheticData node to copy the input texture into a linear array buffer .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cudaMipmappedArray", "``uint64``", "Pointer to the CUDA Mipmapped Array", "0" "inputs:format", "``uint64``", "Format", "0" "inputs:height", "``uint``", "Height", "0" "inputs:hydraTime", "``double``", "Hydra time in stage", "0.0" "inputs:mipCount", "``uint``", "Mip Count", "0" "inputs:outputHeight", "``uint``", "Requested output height", "0" "inputs:outputWidth", "``uint``", "Requested output width", "0" "inputs:simTime", "``double``", "Simulation time", "0.0" "inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0" "inputs:width", "``uint``", "Width", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:data", "``float[4][]``", "Buffer array data", "[]" "outputs:height", "``uint``", "Buffer array height", "None" "outputs:hydraTime", "``double``", "Hydra time in stage", "None" "outputs:simTime", "``double``", "Simulation time", "None" "outputs:stream", "``uint64``", "Pointer to the CUDA Stream", "None" "outputs:width", "``uint``", "Buffer array width", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTextureToLinearArray" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "internal" "Generated Class Name", "OgnSdTextureToLinearArrayDatabase" "Python Module", "omni.syntheticdata"
2,479
reStructuredText
29.617284
99
0.578459
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdLinearArrayToTexture.rst
.. _omni_syntheticdata_SdLinearArrayToTexture_1: .. _omni_syntheticdata_SdLinearArrayToTexture: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Linear Array To Texture :keywords: lang-en omnigraph node graph:action syntheticdata sd-linear-array-to-texture Sd Linear Array To Texture ========================== .. <description> Synthetic Data node to copy the input buffer array into a texture for visualization .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:data", "``float[4][]``", "Buffer array data", "[]" "inputs:exec", "``execution``", "Trigger", "None" "inputs:height", "``uint``", "Buffer array height", "0" "inputs:sdDisplayCudaMipmappedArray", "``uint64``", "Visualization texture CUDA mipmapped array pointer", "0" "inputs:sdDisplayFormat", "``uint64``", "Visualization texture format", "0" "inputs:sdDisplayHeight", "``uint``", "Visualization texture Height", "0" "inputs:sdDisplayStream", "``uint64``", "Visualization texture CUDA stream pointer", "0" "inputs:sdDisplayWidth", "``uint``", "Visualization texture width", "0" "inputs:stream", "``uint64``", "Pointer to the CUDA Stream", "0" "inputs:width", "``uint``", "Buffer array width", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cudaPtr", "``uint64``", "Display texture CUDA pointer", "None" "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:format", "``uint64``", "Display texture format", "None" "outputs:handlePtr", "``uint64``", "Display texture handle reference", "None" "outputs:height", "``uint``", "Display texture height", "None" "outputs:stream", "``uint64``", "Output texture CUDA stream pointer", "None" "outputs:width", "``uint``", "Display texture width", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdLinearArrayToTexture" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "graph:action" "Generated Class Name", "OgnSdLinearArrayToTextureDatabase" "Python Module", "omni.syntheticdata"
2,767
reStructuredText
32.756097
113
0.606072
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSemanticFilter.rst
.. _omni_syntheticdata_SdSemanticFilter_1: .. _omni_syntheticdata_SdSemanticFilter: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Semantic Filter :keywords: lang-en omnigraph node graph:simulation syntheticdata sd-semantic-filter Sd Semantic Filter ================== .. <description> Synthetic Data node to declare a semantic filter. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Dependency", "None" "inputs:hierarchicalLabels", "``bool``", "If true the filter consider all labels in the semantic hierarchy above the prims", "False" "inputs:matchingLabels", "``bool``", "If true output only the labels matching the filter (if false keep all labels of the matching prims)", "True" "inputs:name", "``token``", "Filter unique identifier [if empty, use the normalized predicate as an identifier]", "" "inputs:predicate", "``token``", "The semantic filter specification : a disjunctive normal form of semantic type and label", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:name", "``token``", "The semantic filter name identifier", "" "outputs:predicate", "``token``", "The semantic filter predicate in normalized form", "" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdSemanticFilter" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:simulation" "Generated Class Name", "OgnSdSemanticFilterDatabase" "Python Module", "omni.syntheticdata"
2,224
reStructuredText
29.479452
150
0.609712
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestStageSynchronization.rst
.. _omni_syntheticdata_SdTestStageSynchronization_1: .. _omni_syntheticdata_SdTestStageSynchronization: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Stage Synchronization :keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-stage-synchronization Sd Test Stage Synchronization ============================= .. <description> Synthetic Data node to test the pipeline stage synchronization .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "OnDemand connection : trigger", "None" "gpuFoundations (*inputs:gpu*)", "``uint64``", "PostRender connection : pointer to shared context containing gpu foundations", "0" "inputs:randomMaxProcessingTimeUs", "``uint``", "Maximum number of micro-seconds to randomly (uniformely) wait for in order to simulate varying workload", "0" "inputs:randomSeed", "``uint``", "Random seed for the randomization", "0" "inputs:renderResults", "``uint64``", "OnDemand connection : pointer to render product results", "0" "renderProduct (*inputs:rp*)", "``uint64``", "PostRender connection : pointer to render product for this view", "0" "inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0" "inputs:tag", "``token``", "A tag to identify the node", "" "inputs:traceError", "``bool``", "If true print an error message when the frame numbers are out-of-sync", "False" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "OnDemand connection : trigger", "None" "outputs:fabricSWHFrameNumber", "``uint64``", "Fabric frame number from the fabric", "None" "outputs:swhFrameNumber", "``uint64``", "Fabric frame number", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestStageSynchronization" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "graph:simulation,graph:postRender,graph:action,internal:test" "Generated Class Name", "OgnSdTestStageSynchronizationDatabase" "Python Module", "omni.syntheticdata"
2,765
reStructuredText
34.922077
162
0.633273
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestInstanceMapping.rst
.. _omni_syntheticdata_SdTestInstanceMapping_1: .. _omni_syntheticdata_SdTestInstanceMapping: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Instance Mapping :keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-instance-mapping Sd Test Instance Mapping ======================== .. <description> Synthetic Data node to test the instance mapping pipeline .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:instanceMapPtr", "``uint64``", "Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent", "0" "inputs:instancePrimPathPtr", "``uint64``", "Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims", "0" "inputs:minInstanceIndex", "``uint``", "Instance index of the first instance prim in the instance arrays", "0" "inputs:minSemanticIndex", "``uint``", "Semantic index of the first semantic prim in the semantic arrays", "0" "inputs:numInstances", "``uint``", "Number of instances prim in the instance arrays", "0" "inputs:numSemantics", "``uint``", "Number of semantic prim in the semantic arrays", "0" "inputs:semanticLabelTokenPtrs", "``uint64[]``", "Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim", "[]" "inputs:semanticLocalTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims", "0" "inputs:semanticMapPtr", "``uint64``", "Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent", "0" "inputs:semanticPrimPathPtr", "``uint64``", "Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims", "0" "inputs:semanticWorldTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity", "0" "inputs:stage", "``token``", "Stage in {simulation, postrender, ondemand}", "" "inputs:swhFrameNumber", "``uint64``", "Fabric frame number", "0" "inputs:testCaseIndex", "``int``", "Test case index", "-1" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:semanticFilterPredicate", "``token``", "The semantic filter predicate : a disjunctive normal form of semantic type and label", "None" "outputs:success", "``bool``", "Test value : false if failed", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestInstanceMapping" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""simulation"", ""postRender"", ""onDemand""]" "Categories", "graph:simulation,graph:postRender,graph:action,internal:test" "Generated Class Name", "OgnSdTestInstanceMappingDatabase" "Python Module", "omni.syntheticdata"
3,860
reStructuredText
44.964285
220
0.664508
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemanticBoundingBox.rst
.. _omni_syntheticdata_SdPostSemanticBoundingBox_1: .. _omni_syntheticdata_SdPostSemanticBoundingBox: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Semantic Bounding Box :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic-bounding-box Sd Post Semantic Bounding Box ============================= .. <description> Synthetic Data node to compute the bounding boxes of the scene semantic entities. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:instanceMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index", "0" "inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0" "inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[0, 0]" "inputs:renderVar", "``token``", "Name of the BoundingBox RenderVar to process", "" "renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0" "inputs:semanticLocalTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the local semantic transform", "0" "inputs:semanticMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:sdSemBBoxExtentCudaPtr", "``uint64``", "Cuda buffer containing the extent of the bounding boxes as a float4=(u_min,v_min,u_max,v_max) for 2D or a float6=(xmin,ymin,zmin,xmax,ymax,zmax) in object space for 3D", "None" "outputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostSemanticBoundingBox" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""BoundingBox2DLooseSD"", ""BoundingBox2DTightSD"", ""SemanticBoundingBox2DExtentLooseSD"", ""SemanticBoundingBox2DInfosLooseSD"", ""SemanticBoundingBox2DExtentTightSD"", ""SemanticBoundingBox2DInfosTightSD"", ""BoundingBox3DSD"", ""SemanticBoundingBox3DExtentSD"", ""SemanticBoundingBox3DInfosSD""]" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostSemanticBoundingBoxDatabase" "Python Module", "omni.syntheticdata"
3,344
reStructuredText
41.884615
318
0.664773
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderVarPtr.rst
.. _omni_syntheticdata_SdRenderVarPtr_2: .. _omni_syntheticdata_SdRenderVarPtr: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Render Var Ptr :keywords: lang-en omnigraph node graph:action syntheticdata sd-render-var-ptr Sd Render Var Ptr ================= .. <description> Synthetic Data node exposing the raw pointer data of a rendervar. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:renderResults", "``uint64``", "Render results pointer", "0" "inputs:renderVar", "``token``", "Name of the renderVar", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:bufferSize", "``uint64``", "Size (in bytes) of the buffer (0 if the input is a texture)", "None" "outputs:cudaDeviceIndex", "``int``", "Index of the device where the data lives (-1 for host data)", "-1" "outputs:dataPtr", "``uint64``", "Pointer to the raw data (cuda device pointer or host pointer)", "0" "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:format", "``uint64``", "Format", "None" "outputs:height", "``uint``", "Height (0 if the input is a buffer)", "None" "outputs:strides", "``int[2]``", "Strides (in bytes) ([0,0] if the input is a buffer)", "None" "outputs:width", "``uint``", "Width (0 if the input is a buffer)", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdRenderVarPtr" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "graph:action" "Generated Class Name", "OgnSdRenderVarPtrDatabase" "Python Module", "omni.syntheticdata"
2,325
reStructuredText
29.605263
109
0.582366
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestRenderProductCamera.rst
.. _omni_syntheticdata_SdTestRenderProductCamera_1: .. _omni_syntheticdata_SdTestRenderProductCamera: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Render Product Camera :keywords: lang-en omnigraph node graph:simulation,graph:postRender,graph:action,internal:test syntheticdata sd-test-render-product-camera Sd Test Render Product Camera ============================= .. <description> Synthetic Data node to test the renderProduct camera pipeline .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cameraApertureOffset", "``float[2]``", "Camera horizontal and vertical aperture offset", "[0.0, 0.0]" "inputs:cameraApertureSize", "``float[2]``", "Camera horizontal and vertical aperture", "[0.0, 0.0]" "inputs:cameraFStop", "``float``", "Camera fStop", "0.0" "inputs:cameraFisheyeParams", "``float[]``", "Camera fisheye projection parameters", "[]" "inputs:cameraFocalLength", "``float``", "Camera focal length", "0.0" "inputs:cameraFocusDistance", "``float``", "Camera focus distance", "0.0" "inputs:cameraModel", "``int``", "Camera model (pinhole or fisheye models)", "0" "inputs:cameraNearFar", "``float[2]``", "Camera near/far clipping range", "[0.0, 0.0]" "inputs:cameraProjection", "``matrixd[4]``", "Camera projection matrix", "[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]" "inputs:cameraViewTransform", "``matrixd[4]``", "Camera view matrix", "[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]" "inputs:exec", "``execution``", "Trigger", "None" "inputs:height", "``uint``", "Height of the frame", "0" "inputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "0.0" "inputs:renderProductCameraPath", "``token``", "RenderProduct camera prim path", "" "inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[0, 0]" "inputs:renderResults", "``uint64``", "OnDemand connection : pointer to render product results", "0" "renderProduct (*inputs:rp*)", "``uint64``", "PostRender connection : pointer to render product for this view", "0" "inputs:stage", "``token``", "Stage in {simulation, postrender, ondemand}", "" "inputs:traceError", "``bool``", "If true print an error message when the frame numbers are out-of-sync", "False" "inputs:width", "``uint``", "Width of the frame", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:test", "``bool``", "Test value : false if failed", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestRenderProductCamera" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "__tokens", "[""simulation"", ""postRender"", ""onDemand""]" "Categories", "graph:simulation,graph:postRender,graph:action,internal:test" "Generated Class Name", "OgnSdTestRenderProductCameraDatabase" "Python Module", "omni.syntheticdata"
3,613
reStructuredText
40.540229
167
0.606975
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdOnNewRenderProductFrame.rst
.. _omni_syntheticdata_SdOnNewRenderProductFrame_1: .. _omni_syntheticdata_SdOnNewRenderProductFrame: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd On New Render Product Frame :keywords: lang-en omnigraph node graph:action,flowControl syntheticdata sd-on-new-render-product-frame Sd On New Render Product Frame ============================== .. <description> Synthetic Data postprocess node to execute pipeline after the NewFrame event has been received on the given renderProduct .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*inputs:exec*)", "``execution``", "Executes for each newFrame event received", "None" "inputs:renderProductDataPtrs", "``uint64[]``", "HydraRenderProduct data pointers.", "[]" "inputs:renderProductPath", "``token``", "Path of the renderProduct to wait for being rendered", "" "inputs:renderProductPaths", "``token[]``", "Render product path tokens.", "[]" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cudaStream", "``uint64``", "Cuda stream", "None" "Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None" "outputs:renderProductPath", "``token``", "Path of the renderProduct to wait for being rendered", "None" "outputs:renderResults", "``uint64``", "Render results", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdOnNewRenderProductFrame" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnSdOnNewRenderProductFrameDatabase" "Python Module", "omni.syntheticdata"
2,299
reStructuredText
30.506849
121
0.61592
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdFabricTimeRangeExecution.rst
.. _omni_syntheticdata_SdFabricTimeRangeExecution_1: .. _omni_syntheticdata_SdFabricTimeRangeExecution: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Fabric Time Range Execution :keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-fabric-time-range-execution Sd Fabric Time Range Execution ============================== .. <description> Read a rational time range from Fabric or RenderVars and signal its execution if the current time fall within this range. The range is [begin,end[, that is the end time does not belong to the range. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations.", "0" "inputs:renderResults", "``uint64``", "Render results", "0" "inputs:timeRangeBeginDenominatorToken", "``token``", "Attribute name of the range begin time denominator", "timeRangeStartDenominator" "inputs:timeRangeBeginNumeratorToken", "``token``", "Attribute name of the range begin time numerator", "timeRangeStartNumerator" "inputs:timeRangeEndDenominatorToken", "``token``", "Attribute name of the range end time denominator", "timeRangeEndDenominator" "inputs:timeRangeEndNumeratorToken", "``token``", "Attribute name of the range end time numerator", "timeRangeEndNumerator" "inputs:timeRangeName", "``token``", "Time range name used to read from the Fabric or RenderVars.", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:timeRangeBeginDenominator", "``uint64``", "Time denominator of the last time range change (begin)", "None" "outputs:timeRangeBeginNumerator", "``int64``", "Time numerator of the last time range change (begin)", "None" "outputs:timeRangeEndDenominator", "``uint64``", "Time denominator of the last time range change (end)", "None" "outputs:timeRangeEndNumerator", "``int64``", "Time numerator of the last time range change (end)", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdFabricTimeRangeExecution" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:postRender,graph:action" "Generated Class Name", "OgnSdFabricTimeRangeExecutionDatabase" "Python Module", "omni.syntheticdata"
3,037
reStructuredText
37.948717
198
0.650971
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderVarDisplayTexture.rst
.. _omni_syntheticdata_SdRenderVarDisplayTexture_2: .. _omni_syntheticdata_SdRenderVarDisplayTexture: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Render Var Display Texture :keywords: lang-en omnigraph node graph:action,rendering,internal syntheticdata sd-render-var-display-texture Sd Render Var Display Texture ============================= .. <description> Synthetic Data node to expose texture resource of a visualization render variable .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:renderResults", "``uint64``", "Render results pointer", "0" "inputs:renderVarDisplay", "``token``", "Name of the renderVar", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cudaPtr", "``uint64``", "Display texture CUDA pointer", "None" "outputs:exec", "``execution``", "Trigger", "None" "outputs:format", "``uint64``", "Display texture format", "None" "outputs:height", "``uint``", "Display texture height", "None" "outputs:referenceTimeDenominator", "``uint64``", "Reference time represented as a rational number : denominator", "None" "outputs:referenceTimeNumerator", "``int64``", "Reference time represented as a rational number : numerator", "None" "outputs:rpResourcePtr", "``uint64``", "Display texture RpResource pointer", "None" "outputs:width", "``uint``", "Display texture width", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdRenderVarDisplayTexture" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:action,rendering,internal" "Generated Class Name", "OgnSdRenderVarDisplayTextureDatabase" "Python Module", "omni.syntheticdata"
2,410
reStructuredText
30.723684
125
0.614523
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostRenderVarTextureToBuffer.rst
.. _omni_syntheticdata_SdPostRenderVarTextureToBuffer_1: .. _omni_syntheticdata_SdPostRenderVarTextureToBuffer: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Render Var Texture To Buffer :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-render-var-texture-to-buffer Sd Post Render Var Texture To Buffer ==================================== .. <description> Expose a device renderVar buffer a texture one. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:renderVar", "``token``", "Name of the device renderVar to expose on the host", "" "inputs:renderVarBufferSuffix", "``string``", "Suffix appended to the renderVar name", "buffer" "inputs:rp", "``uint64``", "Pointer to render product for this view", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:renderVar", "``token``", "Name of the resulting renderVar on the host", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostRenderVarTextureToBuffer" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostRenderVarTextureToBufferDatabase" "Python Module", "omni.syntheticdata"
2,114
reStructuredText
28.375
115
0.603122
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostInstanceMapping.rst
.. _omni_syntheticdata_SdPostInstanceMapping_2: .. _omni_syntheticdata_SdPostInstanceMapping: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Instance Mapping :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-instance-mapping Sd Post Instance Mapping ======================== .. <description> Synthetic Data node to compute and store scene instances semantic hierarchy information .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0" "inputs:semanticFilterName", "``token``", "Name of the semantic filter to apply to the semanticLabelToken", "default" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:instanceMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numInstances containing the instance parent semantic index", "None" "outputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [ numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic, lastUpdateTimeNumeratorHigh, lastUpdateTimeNumeratorLow, , lastUpdateTimeDenominatorHigh, lastUpdateTimeDenominatorLow ]", "None" "outputs:instancePrimTokenSDCudaPtr", "``uint64``", "cuda uint64_t buffer pointer of size numInstances containing the instance path token", "None" "outputs:lastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None" "outputs:lastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None" "outputs:semanticLabelTokenSDCudaPtr", "``uint64``", "cuda uint64_t buffer pointer of size numSemantics containing the semantic label token", "None" "outputs:semanticLocalTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the local semantic transform", "None" "outputs:semanticMapSDCudaPtr", "``uint64``", "cuda uint16_t buffer pointer of size numSemantics containing the semantic parent semantic index", "None" "outputs:semanticPrimTokenSDCudaPtr", "``uint64``", "cuda uint32_t buffer pointer of size numSemantics containing the prim part of the semantic path token", "None" "outputs:semanticWorldTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the world semantic transform", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostInstanceMapping" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""InstanceMappingInfoSDhost"", ""SemanticMapSD"", ""SemanticMapSDhost"", ""SemanticPrimTokenSD"", ""SemanticPrimTokenSDhost"", ""InstanceMapSD"", ""InstanceMapSDhost"", ""InstancePrimTokenSD"", ""InstancePrimTokenSDhost"", ""SemanticLabelTokenSD"", ""SemanticLabelTokenSDhost"", ""SemanticLocalTransformSD"", ""SemanticLocalTransformSDhost"", ""SemanticWorldTransformSD"", ""SemanticWorldTransformSDhost""]" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostInstanceMappingDatabase" "Python Module", "omni.syntheticdata"
4,032
reStructuredText
48.790123
425
0.689236
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdInstanceMapping.rst
.. _omni_syntheticdata_SdInstanceMapping_2: .. _omni_syntheticdata_SdInstanceMapping: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Instance Mapping :keywords: lang-en omnigraph node graph:action syntheticdata sd-instance-mapping Sd Instance Mapping =================== .. <description> Synthetic Data node to expose the scene instances semantic hierarchy information .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:lazy", "``bool``", "Compute outputs only when connected to a downstream node", "True" "inputs:renderResults", "``uint64``", "Render results pointer", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:sdIMInstanceSemanticMap", "``uchar[]``", "Raw array of uint16_t of size sdIMNumInstances*sdIMMaxSemanticHierarchyDepth containing the mapping from the instances index to their inherited semantic entities", "None" "outputs:sdIMInstanceTokens", "``token[]``", "Instance array containing the token for every instances", "None" "outputs:sdIMLastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None" "outputs:sdIMLastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None" "outputs:sdIMMaxSemanticHierarchyDepth", "``uint``", "Maximal number of semantic entities inherited by an instance", "None" "outputs:sdIMMinInstanceIndex", "``uint``", "Instance id of the first instance in the instance arrays", "None" "outputs:sdIMMinSemanticIndex", "``uint``", "Semantic id of the first semantic entity in the semantic arrays", "None" "outputs:sdIMNumInstances", "``uint``", "Number of instances in the instance arrays", "None" "outputs:sdIMNumSemanticTokens", "``uint``", "Number of semantics token including the semantic entity path, the semantic entity types and if the number of semantic types is greater than one a ", "None" "outputs:sdIMNumSemantics", "``uint``", "Number of semantic entities in the semantic arrays", "None" "outputs:sdIMSemanticLocalTransform", "``float[]``", "Semantic array of 4x4 float matrices containing the transform from world to local space for every semantic entity", "None" "outputs:sdIMSemanticTokenMap", "``token[]``", "Semantic array of token of size numSemantics * numSemanticTypes containing the mapping from the semantic entities to the semantic entity path and semantic types", "None" "outputs:sdIMSemanticWorldTransform", "``float[]``", "Semantic array of 4x4 float matrices containing the transform from local to world space for every semantic entity", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdInstanceMapping" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""InstanceMappingInfoSDhost"", ""InstanceMapSDhost"", ""SemanticLabelTokenSDhost"", ""InstancePrimTokenSDhost"", ""SemanticLocalTransformSDhost"", ""SemanticWorldTransformSDhost""]" "Categories", "graph:action" "Generated Class Name", "OgnSdInstanceMappingDatabase" "Python Module", "omni.syntheticdata"
3,895
reStructuredText
45.939758
225
0.675225
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdInstanceMappingPtr.rst
.. _omni_syntheticdata_SdInstanceMappingPtr_2: .. _omni_syntheticdata_SdInstanceMappingPtr: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Instance Mapping Ptr :keywords: lang-en omnigraph node graph:action syntheticdata sd-instance-mapping-ptr Sd Instance Mapping Ptr ======================= .. <description> Synthetic Data node to expose the scene instances semantic hierarchy information .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cudaPtr", "``bool``", "If true, return cuda device pointer instead of host pointer", "False" "inputs:exec", "``execution``", "Trigger", "None" "inputs:renderResults", "``uint64``", "Render results pointer", "0" "inputs:semanticFilerTokens", "``token[]``", "Tokens identifying the semantic filters applied to the output semantic labels. Each token should correspond to an activated SdSemanticFilter node", "[]" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cudaDeviceIndex", "``int``", "If the data is on the device it is the cuda index of this device otherwise it is set to -1", "-1" "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:instanceMapPtr", "``uint64``", "Array pointer of numInstances uint16_t containing the semantic index of the instance prim first semantic prim parent", "None" "outputs:instancePrimPathPtr", "``uint64``", "Array pointer of numInstances uint64_t containing the prim path tokens for every instance prims", "None" "outputs:lastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time the data has changed", "None" "outputs:lastUpdateTimeNumerator", "``int64``", "Time numerator of the last time the data has changed", "None" "outputs:minInstanceIndex", "``uint``", "Instance index of the first instance prim in the instance arrays", "None" "outputs:minSemanticIndex", "``uint``", "Semantic index of the first semantic prim in the semantic arrays", "None" "outputs:numInstances", "``uint``", "Number of instances prim in the instance arrays", "None" "outputs:numSemantics", "``uint``", "Number of semantic prim in the semantic arrays", "None" "outputs:semanticLabelTokenPtrs", "``uint64[]``", "Array containing for every input semantic filters the corresponding array pointer of numSemantics uint64_t representing the semantic label of the semantic prim", "None" "outputs:semanticLocalTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from world to object space for every semantic prims", "None" "outputs:semanticMapPtr", "``uint64``", "Array pointer of numSemantics uint16_t containing the semantic index of the semantic prim first semantic prim parent", "None" "outputs:semanticPrimPathPtr", "``uint64``", "Array pointer of numSemantics uint32_t containing the prim part of the prim path tokens for every semantic prims", "None" "outputs:semanticWorldTransformPtr", "``uint64``", "Array pointer of numSemantics 4x4 float matrices containing the transform from local to world space for every semantic entity", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdInstanceMappingPtr" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""InstanceMappingInfoSDhost"", ""InstancePrimTokenSDhost"", ""InstancePrimTokenSD"", ""SemanticPrimTokenSDhost"", ""SemanticPrimTokenSD"", ""InstanceMapSDhost"", ""InstanceMapSD"", ""SemanticMapSDhost"", ""SemanticMapSD"", ""SemanticWorldTransformSDhost"", ""SemanticWorldTransformSD"", ""SemanticLocalTransformSDhost"", ""SemanticLocalTransformSD"", ""SemanticLabelTokenSDhost"", ""SemanticLabelTokenSD""]" "Categories", "graph:action" "Generated Class Name", "OgnSdInstanceMappingPtrDatabase" "Python Module", "omni.syntheticdata"
4,502
reStructuredText
51.97647
425
0.684363
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestSimFabricTimeRange.rst
.. _omni_syntheticdata_SdTestSimFabricTimeRange_1: .. _omni_syntheticdata_SdTestSimFabricTimeRange: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Sim Fabric Time Range :keywords: lang-en omnigraph node graph:simulation,internal,event compute-on-request syntheticdata sd-test-sim-fabric-time-range Sd Test Sim Fabric Time Range ============================= .. <description> Testing node : on request write/update a Fabric time range of a given number of frames starting at the current simulation time. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:numberOfFrames", "``uint64``", "Number of frames to writes.", "0" "inputs:timeRangeBeginDenominatorToken", "``token``", "Attribute name of the range begin time denominator", "timeRangeStartDenominator" "inputs:timeRangeBeginNumeratorToken", "``token``", "Attribute name of the range begin time numerator", "timeRangeStartNumerator" "inputs:timeRangeEndDenominatorToken", "``token``", "Attribute name of the range end time denominator", "timeRangeEndDenominator" "inputs:timeRangeEndNumeratorToken", "``token``", "Attribute name of the range end time numerator", "timeRangeEndNumerator" "inputs:timeRangeName", "``token``", "Time range name used to write to the Fabric.", "TestSimFabricTimeRangeSD" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestSimFabricTimeRange" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""fc_exportToRingbuffer""]" "Categories", "graph:simulation,internal,event" "Generated Class Name", "OgnSdTestSimFabricTimeRangeDatabase" "Python Module", "omni.syntheticdata"
2,437
reStructuredText
32.39726
139
0.639311
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostCompRenderVarTextures.rst
.. _omni_syntheticdata_SdPostCompRenderVarTextures_1: .. _omni_syntheticdata_SdPostCompRenderVarTextures: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Comp Render Var Textures :keywords: lang-en omnigraph node graph:postRender,rendering,internal syntheticdata sd-post-comp-render-var-textures Sd Post Comp Render Var Textures ================================ .. <description> Synthetic Data node to compose a front renderVar texture into a back renderVar texture .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cudaPtr", "``uint64``", "Front texture CUDA pointer", "0" "inputs:format", "``uint64``", "Front texture format", "0" "gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:height", "``uint``", "Front texture height", "0" "inputs:mode", "``token``", "Mode : grid, line", "line" "inputs:parameters", "``float[3]``", "Parameters", "[0, 0, 0]" "inputs:renderVar", "``token``", "Name of the back RenderVar", "LdrColor" "renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0" "inputs:width", "``uint``", "Front texture width", "0" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostCompRenderVarTextures" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""line"", ""grid""]" "Categories", "graph:postRender,rendering,internal" "Generated Class Name", "OgnSdPostCompRenderVarTexturesDatabase" "Python Module", "omni.syntheticdata"
2,167
reStructuredText
31.358208
120
0.5976
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdUpdateSwhFrameNumber.rst
.. _omni_syntheticdata_SdUpdateSwFrameNumber_1: .. _omni_syntheticdata_SdUpdateSwFrameNumber: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Update Sw Frame Number :keywords: lang-en omnigraph node graph:simulation syntheticdata sd-update-sw-frame-number Sd Update Sw Frame Number ========================= .. <description> Synthetic Data node to return the current update swhFrameNumber .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:swhFrameNumber", "``uint64``", "Fabric frame number", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdUpdateSwFrameNumber" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:simulation" "Generated Class Name", "OgnSdUpdateSwhFrameNumberDatabase" "Python Module", "omni.syntheticdata"
1,523
reStructuredText
24.830508
99
0.589626
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemantic3dBoundingBoxFilter.rst
.. _omni_syntheticdata_SdPostSemantic3dBoundingBoxFilter_1: .. _omni_syntheticdata_SdPostSemantic3dBoundingBoxFilter: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Semantic3D Bounding Box Filter :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic3d-bounding-box-filter Sd Post Semantic3D Bounding Box Filter ====================================== .. <description> Synthetic Data node to cull the semantic 3d bounding boxes. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0" "inputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "0.01" "renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0" "inputs:sdSemBBox3dCamCornersCudaPtr", "``uint64``", "Cuda buffer containing the projection of the 3d bounding boxes on the camera plane represented as a float3=(u,v,z,a) for each bounding box corners", "0" "inputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "0" "inputs:viewportNearFar", "``float[2]``", "near and far plane (in scene units) used to clip the 3d bounding boxes.", "[0.0, -1.0]" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostSemantic3dBoundingBoxFilter" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""SemanticBoundingBox3DInfosSD"", ""SemanticBoundingBox3DFilterInfosSD""]" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostSemantic3dBoundingBoxFilterDatabase" "Python Module", "omni.syntheticdata"
2,834
reStructuredText
36.302631
210
0.641849
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSimInstanceMapping.rst
.. _omni_syntheticdata_SdSimInstanceMapping_1: .. _omni_syntheticdata_SdSimInstanceMapping: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Sim Instance Mapping :keywords: lang-en omnigraph node graph:simulation,internal syntheticdata sd-sim-instance-mapping Sd Sim Instance Mapping ======================= .. <description> Synthetic Data node to update and cache the instance mapping data .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:needTransform", "``bool``", "If true compute the semantic entities world and object transforms", "True" "inputs:semanticFilterPredicate", "``token``", "The semantic filter predicate : a disjunctive normal form of semantic type and label", "*:*" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:semanticFilterPredicate", "``token``", "The semantic filter predicate in normalized form", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdSimInstanceMapping" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:simulation,internal" "Generated Class Name", "OgnSdSimInstanceMappingDatabase" "Python Module", "omni.syntheticdata"
1,900
reStructuredText
26.550724
144
0.607368
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostRenderVarToHost.rst
.. _omni_syntheticdata_SdPostRenderVarToHost_1: .. _omni_syntheticdata_SdPostRenderVarToHost: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Render Var To Host :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-render-var-to-host Sd Post Render Var To Host ========================== .. <description> Expose a host renderVar from the input device renderVar. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:renderVar", "``token``", "Name of the device renderVar to expose on the host", "" "inputs:renderVarHostSuffix", "``string``", "Suffix appended to the renderVar name", "host" "inputs:rp", "``uint64``", "Pointer to render product for this view", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:renderVar", "``token``", "Name of the resulting renderVar on the host", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostRenderVarToHost" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostRenderVarToHostDatabase" "Python Module", "omni.syntheticdata"
2,043
reStructuredText
27.388889
105
0.595203
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdSimRenderProductCamera.rst
.. _omni_syntheticdata_SdSimRenderProductCamera_1: .. _omni_syntheticdata_SdSimRenderProductCamera: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Sim Render Product Camera :keywords: lang-en omnigraph node graph:simulation,internal syntheticdata sd-sim-render-product-camera Sd Sim Render Product Camera ============================ .. <description> Synthetic Data node to expose the renderProduct camera in the fabric .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:renderProductPath", "``token``", "renderProduct prim path", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdSimRenderProductCamera" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:simulation,internal" "Generated Class Name", "OgnSdSimRenderProductCameraDatabase" "Python Module", "omni.syntheticdata"
1,642
reStructuredText
23.522388
106
0.588307
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdFrameIdentifier.rst
.. _omni_syntheticdata_SdFrameIdentifier_1: .. _omni_syntheticdata_SdFrameIdentifier: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Frame Identifier :keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-frame-identifier Sd Frame Identifier =================== .. <description> Synthetic Data node to expose pipeline frame identifier. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:renderResults", "``uint64``", "Render results", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:durationDenominator", "``uint64``", "Duration denominator. Only valid if eConstantFramerateFrameNumber", "0" "outputs:durationNumerator", "``int64``", "Duration numerator. Only valid if eConstantFramerateFrameNumber.", "0" "Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None" "outputs:externalTimeOfSimNs", "``int64``", "External time in Ns. Only valid if eConstantFramerateFrameNumber.", "-1" "outputs:frameNumber", "``int64``", "Frame number. Valid if eFrameNumber or eConstantFramerateFrameNumber.", "-1" "outputs:rationalTimeOfSimDenominator", "``uint64``", "rational time of simulation denominator.", "0" "outputs:rationalTimeOfSimNumerator", "``int64``", "rational time of simulation numerator.", "0" "outputs:sampleTimeOffsetInSimFrames", "``uint64``", "Sample time offset. Only valid if eConstantFramerateFrameNumber.", "0" "outputs:type", "``token``", "Type of the frame identifier.", "NoFrameNumber" "", "*allowedTokens*", "NoFrameNumber,FrameNumber,ConstantFramerateFrameNumber", "" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdFrameIdentifier" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:postRender,graph:action" "Generated Class Name", "OgnSdFrameIdentifierDatabase" "Python Module", "omni.syntheticdata"
2,650
reStructuredText
33.428571
128
0.636226
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestPrintRawArray.rst
.. _omni_syntheticdata_SdTestPrintRawArray_1: .. _omni_syntheticdata_SdTestPrintRawArray: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Print Raw Array :keywords: lang-en omnigraph node graph:action,internal:test syntheticdata sd-test-print-raw-array Sd Test Print Raw Array ======================= .. <description> Synthetic Data test node printing the input linear array .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:bufferSize", "``uint``", "Size (in bytes) of the buffer (0 if the input is a texture)", "0" "inputs:data", "``uchar[]``", "Buffer array data", "[]" "inputs:dataFileBaseName", "``token``", "Basename of the output npy file", "/tmp/sdTestRawArray" "inputs:elementCount", "``int``", "Number of array element", "1" "inputs:elementType", "``token``", "Type of the array element", "uint8" "inputs:exec", "``execution``", "Trigger", "None" "inputs:height", "``uint``", "Height (0 if the input is a buffer)", "0" "inputs:mode", "``token``", "Mode in [printFormatted, printReferences, testReferences]", "printFormatted" "inputs:randomSeed", "``int``", "Random seed", "0" "inputs:referenceNumUniqueRandomValues", "``int``", "Number of reference unique random values to compare", "7" "inputs:referenceSWHFrameNumbers", "``uint[]``", "Reference swhFrameNumbers relative to the first one", "[11, 17, 29]" "inputs:referenceTolerance", "``float``", "Reference tolerance", "0.1" "inputs:referenceValues", "``float[]``", "Reference data point values", "[]" "inputs:swhFrameNumber", "``uint64``", "Frame number", "0" "inputs:width", "``uint``", "Width (0 if the input is a buffer)", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:swhFrameNumber", "``uint64``", "FrameNumber just rendered", "None" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:initialSWHFrameNumber", "``int64``", "Initial swhFrameNumber", "-1" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestPrintRawArray" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "__tokens", "[""uint16"", ""int16"", ""uint32"", ""int32"", ""float32"", ""token"", ""printFormatted"", ""printReferences"", ""writeToDisk""]" "Categories", "graph:action,internal:test" "Generated Class Name", "OgnSdTestPrintRawArrayDatabase" "Python Module", "omni.syntheticdata"
3,216
reStructuredText
33.967391
146
0.601679
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdOnNewFrame.rst
.. _omni_syntheticdata_SdOnNewFrame_1: .. _omni_syntheticdata_SdOnNewFrame: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd On New Frame :keywords: lang-en omnigraph node graph:action,flowControl syntheticdata sd-on-new-frame Sd On New Frame =============== .. <description> Synthetic Data postprocess node to execute pipeline after the NewFrame event has been received .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cudaStream", "``uint64``", "Cuda stream", "None" "outputs:exec", "``execution``", "Executes for each newFrame event received", "None" "outputs:referenceTimeDenominator", "``uint64``", "Reference time represented as a rational number : denominator", "None" "outputs:referenceTimeNumerator", "``int64``", "Reference time represented as a rational number : numerator", "None" "outputs:renderProductDataPtrs", "``uint64[]``", "HydraRenderProduct data pointer.", "None" "outputs:renderProductPaths", "``token[]``", "Render product path tokens.", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdOnNewFrame" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:action,flowControl" "Generated Class Name", "OgnSdOnNewFrameDatabase" "Python Module", "omni.syntheticdata"
1,904
reStructuredText
29.238095
125
0.612395
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdNoOp.rst
.. _omni_syntheticdata_SdNoOp_1: .. _omni_syntheticdata_SdNoOp: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd No Op :keywords: lang-en omnigraph node internal syntheticdata sd-no-op Sd No Op ======== .. <description> Synthetic Data pass through node .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdNoOp" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "internal" "Generated Class Name", "OgnSdNoOpDatabase" "Python Module", "omni.syntheticdata"
1,399
reStructuredText
19.895522
99
0.54396
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTimeChangeExecution.rst
.. _omni_syntheticdata_SdTimeChangeExecution_1: .. _omni_syntheticdata_SdTimeChangeExecution: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Time Change Execution :keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-time-change-execution Sd Time Change Execution ======================== .. <description> Set its execution output if the input rational time is more recent that the last registered time. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:errorOnFutureChange", "``bool``", "Print error if the last update is in the future.", "False" "inputs:exec", "``execution``", "Trigger", "None" "inputs:lastUpdateTimeDenominator", "``uint64``", "Time denominator of the last time change", "0" "inputs:lastUpdateTimeNumerator", "``int64``", "Time numerator of the last time change", "0" "inputs:renderResults", "``uint64``", "Render results", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTimeChangeExecution" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "Categories", "graph:postRender,graph:action" "Generated Class Name", "OgnSdTimeChangeExecutionDatabase" "Python Module", "omni.syntheticdata"
1,999
reStructuredText
27.169014
106
0.602301
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdTestStageManipulationScenarii.rst
.. _omni_syntheticdata_SdTestStageManipulationScenarii_1: .. _omni_syntheticdata_SdTestStageManipulationScenarii: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Test Stage Manipulation Scenarii :keywords: lang-en omnigraph node graph:simulation,internal:test syntheticdata sd-test-stage-manipulation-scenarii Sd Test Stage Manipulation Scenarii =================================== .. <description> Synthetic Data test node applying randomly some predefined stage manipulation scenarii .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:randomSeed", "``int``", "Random seed", "0" "inputs:worldPrimPath", "``token``", "Path of the world prim : contains every modifiable prim, cannot be modified", "" State ----- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "state:frameNumber", "``uint64``", "Current frameNumber (number of invocations)", "0" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdTestStageManipulationScenarii" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "True" "Implementation Language", "Python" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "graph:simulation,internal:test" "Generated Class Name", "OgnSdTestStageManipulationScenariiDatabase" "Python Module", "omni.syntheticdata"
1,863
reStructuredText
26.411764
122
0.611379
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderProductCamera.rst
.. _omni_syntheticdata_SdRenderProductCamera_2: .. _omni_syntheticdata_SdRenderProductCamera: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Render Product Camera :keywords: lang-en omnigraph node graph:postRender,graph:action syntheticdata sd-render-product-camera Sd Render Product Camera ======================== .. <description> Synthetic Data node to expose the camera data .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:exec", "``execution``", "Trigger", "None" "inputs:gpu", "``uint64``", "Pointer to shared context containing gpu foundations.", "0" "inputs:renderProductPath", "``token``", "RenderProduct prim path", "" "inputs:renderResults", "``uint64``", "Render results", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:cameraApertureOffset", "``float[2]``", "Camera horizontal and vertical aperture offset", "None" "outputs:cameraApertureSize", "``float[2]``", "Camera horizontal and vertical aperture", "None" "outputs:cameraFStop", "``float``", "Camera fStop", "None" "outputs:cameraFisheyeParams", "``float[]``", "Camera fisheye projection parameters", "None" "outputs:cameraFocalLength", "``float``", "Camera focal length", "None" "outputs:cameraFocusDistance", "``float``", "Camera focus distance", "None" "outputs:cameraModel", "``int``", "Camera model (pinhole or fisheye models)", "None" "outputs:cameraNearFar", "``float[2]``", "Camera near/far clipping range", "None" "outputs:cameraProjection", "``matrixd[4]``", "Camera projection matrix", "None" "outputs:cameraViewTransform", "``matrixd[4]``", "Camera view matrix", "None" "Received (*outputs:exec*)", "``execution``", "Executes for each newFrame event received", "None" "outputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "None" "outputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdRenderProductCamera" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""RenderProductCameraSD""]" "Categories", "graph:postRender,graph:action" "Generated Class Name", "OgnSdRenderProductCameraDatabase" "Python Module", "omni.syntheticdata"
2,943
reStructuredText
34.469879
108
0.620795
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdPostSemantic3dBoundingBoxCameraProjection.rst
.. _omni_syntheticdata_SdPostSemantic3dBoundingBoxCameraProjection_1: .. _omni_syntheticdata_SdPostSemantic3dBoundingBoxCameraProjection: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Post Semantic3D Bounding Box Camera Projection :keywords: lang-en omnigraph node graph:postRender,rendering syntheticdata sd-post-semantic3d-bounding-box-camera-projection Sd Post Semantic3D Bounding Box Camera Projection ================================================= .. <description> Synthetic Data node to project 3d bounding boxes data in camera space. .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cameraFisheyeParams", "``float[]``", "Camera fisheye projection parameters", "[]" "inputs:cameraModel", "``int``", "Camera model (pinhole or fisheye models)", "0" "inputs:cameraNearFar", "``float[2]``", "Camera near/far clipping range", "[1.0, 10000000.0]" "inputs:exec", "``execution``", "Trigger", "None" "gpuFoundations (*inputs:gpu*)", "``uint64``", "Pointer to shared context containing gpu foundations", "0" "inputs:instanceMappingInfoSDPtr", "``uint64``", "uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]", "0" "inputs:metersPerSceneUnit", "``float``", "Scene units to meters scale", "0.01" "inputs:renderProductResolution", "``int[2]``", "RenderProduct resolution", "[65536, 65536]" "renderProduct (*inputs:rp*)", "``uint64``", "Pointer to render product for this view", "0" "inputs:sdSemBBoxExtentCudaPtr", "``uint64``", "Cuda buffer containing the extent of the bounding boxes as a float4=(u_min,v_min,u_max,v_max) for 2D or a float6=(xmin,ymin,zmin,xmax,ymax,zmax) in object space for 3D", "0" "inputs:sdSemBBoxInfosCudaPtr", "``uint64``", "Cuda buffer containing valid bounding boxes infos", "0" "inputs:semanticWorldTransformSDCudaPtr", "``uint64``", "cuda float44 buffer pointer of size numSemantics containing the world semantic transform", "0" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:exec", "``execution``", "Trigger", "None" "outputs:sdSemBBox3dCamCornersCudaPtr", "``uint64``", "Cuda buffer containing the projection of the 3d bounding boxes on the camera plane represented as a float4=(u,v,z,a) for each bounding box corners", "None" "outputs:sdSemBBox3dCamExtentCudaPtr", "``uint64``", "Cuda buffer containing the 2d extent of the 3d bounding boxes on the camera plane represented as a float6=(u_min,u_max,v_min,v_max,z_min,z_max)", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdPostSemantic3dBoundingBoxCameraProjection" "Version", "1" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "None" "__tokens", "[""SemanticBoundingBox3DInfosSD"", ""SemanticBoundingBox3DCamCornersSD"", ""SemanticBoundingBox3DCamExtentSD""]" "Categories", "graph:postRender,rendering" "Generated Class Name", "OgnSdPostSemantic3dBoundingBoxCameraProjectionDatabase" "Python Module", "omni.syntheticdata"
3,691
reStructuredText
44.580246
225
0.663777
omniverse-code/kit/exts/omni.syntheticdata/ogn/docs/OgnSdRenderVarToRawArray.rst
.. _omni_syntheticdata_SdRenderVarToRawArray_2: .. _omni_syntheticdata_SdRenderVarToRawArray: .. ================================================================================ .. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT. .. ================================================================================ :orphan: .. meta:: :title: Sd Render Var To Raw Array :keywords: lang-en omnigraph node graph:action syntheticdata sd-render-var-to-raw-array Sd Render Var To Raw Array ========================== .. <description> Synthetic Data action node to copy the input rendervar into an output raw array .. </description> Installation ------------ To use this node enable :ref:`omni.syntheticdata<ext_omni_syntheticdata>` in the Extension Manager. Inputs ------ .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "inputs:cudaStream", "``uint64``", "Pointer to the CUDA stream", "0" "inputs:exec", "``execution``", "Trigger", "None" "inputs:renderResults", "``uint64``", "Render results pointer", "0" "inputs:renderVar", "``token``", "Name of the renderVar", "" Outputs ------- .. csv-table:: :header: "Name", "Type", "Descripton", "Default" :widths: 20, 20, 50, 10 "outputs:bufferSize", "``uint64``", "Size (in bytes) of the buffer (0 if the input is a texture)", "None" "outputs:cudaStream", "``uint64``", "Pointer to the CUDA stream", "None" "outputs:data", "``uchar[]``", "Buffer array data", "[]" "Received (*outputs:exec*)", "``execution``", "Executes when the event is received", "None" "outputs:format", "``uint64``", "Format", "None" "outputs:height", "``uint``", "Height (0 if the input is a buffer)", "None" "outputs:strides", "``int[2]``", "Strides (in bytes) ([0,0] if the input is a buffer)", "None" "outputs:width", "``uint``", "Width (0 if the input is a buffer)", "None" Metadata -------- .. csv-table:: :header: "Name", "Value" :widths: 30,70 "Unique ID", "omni.syntheticdata.SdRenderVarToRawArray" "Version", "2" "Extension", "omni.syntheticdata" "Has State?", "False" "Implementation Language", "C++" "Default Memory Type", "cpu" "Generated Code Exclusions", "tests" "Categories", "graph:action" "Generated Class Name", "OgnSdRenderVarToRawArrayDatabase" "Python Module", "omni.syntheticdata"
2,398
reStructuredText
30.155844
109
0.583403
omniverse-code/kit/exts/omni.syntheticdata/include/omni/kit/syntheticdata/SyntheticData.h
// Copyright (c) 2020-2021, NVIDIA CORPORATION. All rights reserved. // // NVIDIA CORPORATION and its licensors retain all intellectual property // and proprietary rights in and to this software, related documentation // and any modifications thereto. Any use, reproduction, disclosure or // distribution of this software and related documentation without an express // license agreement from NVIDIA CORPORATION is strictly prohibited. // #pragma once #include <carb/Interface.h> #include <carb/sensors/SensorTypes.h> #include <string> namespace omni { // Forward declare deprecated viewport interface namespace kit { class IViewportWindow; }; namespace syntheticdata { /** * Return code for functions that need to return information about a failure. */ enum class SyntheticDataResult : int32_t { eSuccess = 0, ///< Successful completion. eFailure, ///< A general failure or error. }; /** * Structure which contains a list mapping instance Ids to prims with semantic labels that * can be used to build bounding boxes for meshes with a common semantic class */ struct InstanceMapping { uint32_t uniqueId; ///< a unique ID for this instance mapping entry std::string primPath; ///< the prim path for this instance mapping uint16_t semanticId; ///< the semantic ID for this instance mapping std::string semanticLabel; ///< the semantic class label for this mapping std::vector<uint32_t> instanceIds; ///< a list of instance Ids that inherit this semantic label void* metaData; ///< reserved for future use }; struct BoundingBox2DExtent { int32_t x_min; ///< left extent int32_t y_min; ///< top extent int32_t x_max; ///< right extent int32_t y_max; ///< bottom extent }; struct BoundingBox3DExtent { float x_min; ///< left extent (local coords) float y_min; ///< top extent (local coords) float z_min; ///< front extent (local coords) float x_max; ///< right extent (local coords) float y_max; ///< bottom extent (local coords) float z_max; ///< back extent (local coords) }; struct SyntheticData { CARB_PLUGIN_INTERFACE("omni::syntheticdata::SyntheticData", 0, 9) /** * Enable a specific sensor type on a viewport. * * @param type the type of sensor to enable * * @param viewportWindow the viewport to enable the sensor on * * @return false * * @deprecated removed since version 0.8 */ bool(CARB_ABI* createSensor)(carb::sensors::SensorType type, omni::kit::IViewportWindow* viewportWindow); /** * Disable a sensor on a viewport. * * @param type the type of sensor to disable * * @param viewportWindow the viewport to disable the sensor on * * @return false * * @deprecated removed since version 0.8 */ bool(CARB_ABI* destroySensor)(carb::sensors::SensorType type, omni::kit::IViewportWindow* viewportWindow); /** * Retrieve resource information on the sensor type of a specific viewport * * @param type the type of sensor to retrieve information from * * @param viewportWindow the viewport to retrieve information from * * @return dummy sensorInfo. * * @deprecated removed since version 0.8 */ const carb::sensors::SensorInfo(CARB_ABI* getSensorInfo)(carb::sensors::SensorType type, omni::kit::IViewportWindow* viewportWindow); /** * Get pointer the sensor data on the device * * @param type the type of sensor to retrieve data from * * @param viewportWindow the viewport you are retrieving data from * * @return nullptr * * @deprecated removed since version 0.8 */ void*(CARB_ABI* getSensorDeviceData)(carb::sensors::SensorType type, omni::kit::IViewportWindow* viewportWindow); /** * Get pointer the sensor data on the host * * @param type the type of sensor to retrieve data from * * @param viewportWindow the viewport you are retrieving data from * * @return nullptr * * @deprecated removed since version 0.8 */ void*(CARB_ABI* getSensorHostData)(carb::sensors::SensorType type, omni::kit::IViewportWindow* viewportWindow); /** * Get the number of sensors that are currently enabled on a viewport * * @param viewportWindow the viewport to return the count for * * @return 0 * * @deprecated removed since version 0.8 */ uint32_t(CARB_ABI* getSensorsCount)(omni::kit::IViewportWindow* viewportWindow); /** * Get a list of sensors bound to the viewport * * @param viewportWindow the viewport to retrieve sensors for * * @param sensorList an array of sensors in the viewport * * @param count number of sensors to retrieve for the given viewport * * @remarks It is up to the caller to allocate memory for the sensor * list, using getSensorCount() to determind the list size. * The call will fail if count is larger than the number of * instance IDs at uri, or if instanceList is NULL. * * @return eFailure * * @deprecated removed since version 0.8 */ SyntheticDataResult(CARB_ABI* getSensors)(omni::kit::IViewportWindow* viewportWindow, carb::sensors::SensorType* sensorList, uint32_t count); /** * Get instance ID count for an asset * * @param uri the object to retrieve the instance ID count for * * @return number of instance IDs listed at the uri * * @deprecated to be removed, replaced by InstanceMapping AOVs */ size_t(CARB_ABI* getInstanceIdsCount)(const char* uri); /** * Get instance IDs for an asset * * @param uri the object to retrieve the instance ID list for * * @param instanceList An array of instance IDs for the given uri * * @param count number of instance IDs to retrieve at the uri * * @remarks It is up to the caller to allocate memory for the instance * list, using getInstanceIdsCount() to determind the list size. * The call will fail if count is larger than the number of * instance IDs at uri, or if instanceList is NULL. * * @return eSuccess if successful, eFailure otherwise * * @deprecated to be removed, replaced by InstanceMapping AOVs */ SyntheticDataResult(CARB_ABI* getInstanceIds)(const char* uri, uint32_t* instanceList, size_t count); /** * Get uri from an instance ID * * @param instanceId Instance ID to retrieve a uri for * * @return uri for the mesh specified by instanceId * * @deprecated to be removed, replaced by InstanceMapping AOVs */ const char*(CARB_ABI* getUriFromInstanceId)(uint32_t instanceId); /** * Get semantic ID for an asset * * @param type the semantic type to retrieve the semantic ID for * @param data the semantic data to retrieve the semantic ID for * * @return semantic ID retrieved by the segmentation sensor * * @deprecated to be removed, replaced by InstanceMapping AOVs */ uint16_t(CARB_ABI* getSemanticIdFromData)(const char* type, const char* data); /** * Get semantic type for an asset * * @param semanticId the Id to retrieve the semantic type for * * @return semantic type retrieved by the segmentation sensor * * @deprecated to be removed, replaced by InstanceMapping AOVs */ const char*(CARB_ABI* getSemanticTypeFromId)(uint16_t semanticId); /** * Get semantic data for an asset * * @param semanticId the Id to retrieve the semantic class fors * * @return semantic data retrieved by the segmentation sensor * * @deprecated to be removed, replaced by InstanceMapping AOVs */ const char*(CARB_ABI* getSemanticDataFromId)(uint16_t semanticId); /** * Specify the semantic ID of bounding boxes to return * * @param semanticId only retreive bounding boxes with this id * * @remarks 0 is the default value and retrieves all bounding boxes * * @deprecated to be removed, will be replaced by OmniGraph node */ void(CARB_ABI* setBoundingBoxSemanticId)(uint16_t semanticId); /** * Specify the semantic type and data of bounding boxes to return * * @param type only retrieve bounding boxes with this semantic type * @param data only retreive bounding boxes with this semantic data * * @remarks null string is the default value and retrieves all bounding boxes * * @deprecated to be removed, will be replaced by OmniGraph node */ void(CARB_ABI* setBoundingBoxSemantics)(const char* type, const char* data); /** * Build out a list that will containing mappings of instances and semantics * to prims * * @param uri the root prim to derive instance mappings from * * @param instanceMappings a list to output instance mappings to * * @remarks It is expected that you will pass in an empty vector to be filled * in with instance mappings. It is the caller's responsibility to make * sure the vector is freed when it is no longer needed * * @deprecated to be removed, replaced by InstanceMapping AOVs */ size_t(CARB_ABI* getInstanceMappings)(const char* uri, std::vector<InstanceMapping>& instanceMappings); /** * Callback to update the pipeline internal data just before flushing the fabric * * @param stausdStageId id of the current USD stage for which the data has to be updated */ void(CARB_ABI* updatePipelineBeforeFabricFlush)(uint64_t usdStageId); /** * Fetch the offseted current simulation time (Fabric reference time) * * @param usdStageId id of the current USD stage for which the data has to be updated * @param numSimulationFramesOffset number of simulation frames to offset the current simulation time (0 to get the current simulation time) * @param rationalTimeOfSimNumerator output numerator part of the current simulation time * @param rationalTimeOfSimDenominator output denominator part of the current simulation time */ void(CARB_ABI* getRationalTimeOfSimulation)(uint64_t usdStageId, int32_t numSimulationFramesOffset, int64_t& rationalTimeOfSimNumerator, uint64_t& rationalTimeOfSimDenominator); /** * Parse rendered frame event * * @param renderProductPathHandle handle of the render product path * @param renderProductPtr pointer on the render product data * @param renderProductPathStr output render product path * @param rationalTimeOfSimNumerator output numerator part of the current simulation time * @param rationalTimeOfSimDenominator output denominator part of the current simulation time */ void(CARB_ABI* parseRenderedFrameEventPayload)(int64_t renderProductPathHandle, int64_t renderProductPtr, std::string& renderProductPathStr, int64_t& rationalTimeOfSimNumerator, uint64_t& rationalTimeOfSimDenominator); }; } }
11,820
C
34.821212
144
0.641709
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/__init__.py
from . import _syntheticdata from .scripts.extension import * from .ogn import *
81
Python
19.499995
32
0.765432
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestRenderProductCameraDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdTestRenderProductCamera Synthetic Data node to test the renderProduct camera pipeline """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdTestRenderProductCameraDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestRenderProductCamera Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.cameraApertureOffset inputs.cameraApertureSize inputs.cameraFStop inputs.cameraFisheyeParams inputs.cameraFocalLength inputs.cameraFocusDistance inputs.cameraModel inputs.cameraNearFar inputs.cameraProjection inputs.cameraViewTransform inputs.exec inputs.height inputs.metersPerSceneUnit inputs.renderProductCameraPath inputs.renderProductResolution inputs.renderResults inputs.rp inputs.stage inputs.traceError inputs.width Outputs: outputs.test Predefined Tokens: tokens.simulation tokens.postRender tokens.onDemand """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:cameraApertureOffset', 'float2', 0, None, 'Camera horizontal and vertical aperture offset', {}, True, [0.0, 0.0], False, ''), ('inputs:cameraApertureSize', 'float2', 0, None, 'Camera horizontal and vertical aperture', {}, True, [0.0, 0.0], False, ''), ('inputs:cameraFStop', 'float', 0, None, 'Camera fStop', {}, True, 0.0, False, ''), ('inputs:cameraFisheyeParams', 'float[]', 0, None, 'Camera fisheye projection parameters', {}, True, [], False, ''), ('inputs:cameraFocalLength', 'float', 0, None, 'Camera focal length', {}, True, 0.0, False, ''), ('inputs:cameraFocusDistance', 'float', 0, None, 'Camera focus distance', {}, True, 0.0, False, ''), ('inputs:cameraModel', 'int', 0, None, 'Camera model (pinhole or fisheye models)', {}, True, 0, False, ''), ('inputs:cameraNearFar', 'float2', 0, None, 'Camera near/far clipping range', {}, True, [0.0, 0.0], False, ''), ('inputs:cameraProjection', 'matrix4d', 0, None, 'Camera projection matrix', {}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''), ('inputs:cameraViewTransform', 'matrix4d', 0, None, 'Camera view matrix', {}, True, [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]], False, ''), ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:height', 'uint', 0, None, 'Height of the frame', {}, True, 0, False, ''), ('inputs:metersPerSceneUnit', 'float', 0, None, 'Scene units to meters scale', {}, True, 0.0, False, ''), ('inputs:renderProductCameraPath', 'token', 0, None, 'RenderProduct camera prim path', {}, True, "", False, ''), ('inputs:renderProductResolution', 'int2', 0, None, 'RenderProduct resolution', {}, True, [0, 0], False, ''), ('inputs:renderResults', 'uint64', 0, None, 'OnDemand connection : pointer to render product results', {}, True, 0, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'PostRender connection : pointer to render product for this view', {}, True, 0, False, ''), ('inputs:stage', 'token', 0, None, 'Stage in {simulation, postrender, ondemand}', {}, True, "", False, ''), ('inputs:traceError', 'bool', 0, None, 'If true print an error message when the frame numbers are out-of-sync', {ogn.MetadataKeys.DEFAULT: 'false'}, True, False, False, ''), ('inputs:width', 'uint', 0, None, 'Width of the frame', {}, True, 0, False, ''), ('outputs:test', 'bool', 0, None, 'Test value : false if failed', {}, True, None, False, ''), ]) class tokens: simulation = "simulation" postRender = "postRender" onDemand = "onDemand" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.cameraProjection = og.AttributeRole.MATRIX role_data.inputs.cameraViewTransform = og.AttributeRole.MATRIX role_data.inputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def cameraApertureOffset(self): data_view = og.AttributeValueHelper(self._attributes.cameraApertureOffset) return data_view.get() @cameraApertureOffset.setter def cameraApertureOffset(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraApertureOffset) data_view = og.AttributeValueHelper(self._attributes.cameraApertureOffset) data_view.set(value) @property def cameraApertureSize(self): data_view = og.AttributeValueHelper(self._attributes.cameraApertureSize) return data_view.get() @cameraApertureSize.setter def cameraApertureSize(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraApertureSize) data_view = og.AttributeValueHelper(self._attributes.cameraApertureSize) data_view.set(value) @property def cameraFStop(self): data_view = og.AttributeValueHelper(self._attributes.cameraFStop) return data_view.get() @cameraFStop.setter def cameraFStop(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraFStop) data_view = og.AttributeValueHelper(self._attributes.cameraFStop) data_view.set(value) @property def cameraFisheyeParams(self): data_view = og.AttributeValueHelper(self._attributes.cameraFisheyeParams) return data_view.get() @cameraFisheyeParams.setter def cameraFisheyeParams(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraFisheyeParams) data_view = og.AttributeValueHelper(self._attributes.cameraFisheyeParams) data_view.set(value) self.cameraFisheyeParams_size = data_view.get_array_size() @property def cameraFocalLength(self): data_view = og.AttributeValueHelper(self._attributes.cameraFocalLength) return data_view.get() @cameraFocalLength.setter def cameraFocalLength(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraFocalLength) data_view = og.AttributeValueHelper(self._attributes.cameraFocalLength) data_view.set(value) @property def cameraFocusDistance(self): data_view = og.AttributeValueHelper(self._attributes.cameraFocusDistance) return data_view.get() @cameraFocusDistance.setter def cameraFocusDistance(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraFocusDistance) data_view = og.AttributeValueHelper(self._attributes.cameraFocusDistance) data_view.set(value) @property def cameraModel(self): data_view = og.AttributeValueHelper(self._attributes.cameraModel) return data_view.get() @cameraModel.setter def cameraModel(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraModel) data_view = og.AttributeValueHelper(self._attributes.cameraModel) data_view.set(value) @property def cameraNearFar(self): data_view = og.AttributeValueHelper(self._attributes.cameraNearFar) return data_view.get() @cameraNearFar.setter def cameraNearFar(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraNearFar) data_view = og.AttributeValueHelper(self._attributes.cameraNearFar) data_view.set(value) @property def cameraProjection(self): data_view = og.AttributeValueHelper(self._attributes.cameraProjection) return data_view.get() @cameraProjection.setter def cameraProjection(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraProjection) data_view = og.AttributeValueHelper(self._attributes.cameraProjection) data_view.set(value) @property def cameraViewTransform(self): data_view = og.AttributeValueHelper(self._attributes.cameraViewTransform) return data_view.get() @cameraViewTransform.setter def cameraViewTransform(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.cameraViewTransform) data_view = og.AttributeValueHelper(self._attributes.cameraViewTransform) data_view.set(value) @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def height(self): data_view = og.AttributeValueHelper(self._attributes.height) return data_view.get() @height.setter def height(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.height) data_view = og.AttributeValueHelper(self._attributes.height) data_view.set(value) @property def metersPerSceneUnit(self): data_view = og.AttributeValueHelper(self._attributes.metersPerSceneUnit) return data_view.get() @metersPerSceneUnit.setter def metersPerSceneUnit(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.metersPerSceneUnit) data_view = og.AttributeValueHelper(self._attributes.metersPerSceneUnit) data_view.set(value) @property def renderProductCameraPath(self): data_view = og.AttributeValueHelper(self._attributes.renderProductCameraPath) return data_view.get() @renderProductCameraPath.setter def renderProductCameraPath(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderProductCameraPath) data_view = og.AttributeValueHelper(self._attributes.renderProductCameraPath) data_view.set(value) @property def renderProductResolution(self): data_view = og.AttributeValueHelper(self._attributes.renderProductResolution) return data_view.get() @renderProductResolution.setter def renderProductResolution(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderProductResolution) data_view = og.AttributeValueHelper(self._attributes.renderProductResolution) data_view.set(value) @property def renderResults(self): data_view = og.AttributeValueHelper(self._attributes.renderResults) return data_view.get() @renderResults.setter def renderResults(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.renderResults) data_view = og.AttributeValueHelper(self._attributes.renderResults) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def stage(self): data_view = og.AttributeValueHelper(self._attributes.stage) return data_view.get() @stage.setter def stage(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.stage) data_view = og.AttributeValueHelper(self._attributes.stage) data_view.set(value) @property def traceError(self): data_view = og.AttributeValueHelper(self._attributes.traceError) return data_view.get() @traceError.setter def traceError(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.traceError) data_view = og.AttributeValueHelper(self._attributes.traceError) data_view.set(value) @property def width(self): data_view = og.AttributeValueHelper(self._attributes.width) return data_view.get() @width.setter def width(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.width) data_view = og.AttributeValueHelper(self._attributes.width) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def test(self): data_view = og.AttributeValueHelper(self._attributes.test) return data_view.get() @test.setter def test(self, value): data_view = og.AttributeValueHelper(self._attributes.test) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdTestRenderProductCameraDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdTestRenderProductCameraDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdTestRenderProductCameraDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
17,689
Python
43.671717
196
0.633671
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdPostSemantic3dBoundingBoxFilterDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdPostSemantic3dBoundingBoxFilter Synthetic Data node to cull the semantic 3d bounding boxes. """ import numpy import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdPostSemantic3dBoundingBoxFilterDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdPostSemantic3dBoundingBoxFilter Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.exec inputs.gpu inputs.instanceMappingInfoSDPtr inputs.metersPerSceneUnit inputs.rp inputs.sdSemBBox3dCamCornersCudaPtr inputs.sdSemBBoxInfosCudaPtr inputs.viewportNearFar Outputs: outputs.exec outputs.sdSemBBoxInfosCudaPtr Predefined Tokens: tokens.SemanticBoundingBox3DInfosSD tokens.SemanticBoundingBox3DFilterInfosSD """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('inputs:gpu', 'uint64', 0, 'gpuFoundations', 'Pointer to shared context containing gpu foundations', {}, True, 0, False, ''), ('inputs:instanceMappingInfoSDPtr', 'uint64', 0, None, 'uint buffer pointer containing the following information : [numInstances, minInstanceId, numSemantics, minSemanticId, numProtoSemantic]', {}, True, 0, False, ''), ('inputs:metersPerSceneUnit', 'float', 0, None, 'Scene units to meters scale', {ogn.MetadataKeys.DEFAULT: '0.01'}, True, 0.01, False, ''), ('inputs:rp', 'uint64', 0, 'renderProduct', 'Pointer to render product for this view', {}, True, 0, False, ''), ('inputs:sdSemBBox3dCamCornersCudaPtr', 'uint64', 0, None, 'Cuda buffer containing the projection of the 3d bounding boxes on the camera plane represented as a float3=(u,v,z,a) for each bounding box corners', {}, True, 0, False, ''), ('inputs:sdSemBBoxInfosCudaPtr', 'uint64', 0, None, 'Cuda buffer containing valid bounding boxes infos', {}, True, 0, False, ''), ('inputs:viewportNearFar', 'float2', 0, None, 'near and far plane (in scene units) used to clip the 3d bounding boxes.', {ogn.MetadataKeys.DEFAULT: '[0.0, -1.0]'}, True, [0.0, -1.0], False, ''), ('outputs:exec', 'execution', 0, None, 'Trigger', {}, True, None, False, ''), ('outputs:sdSemBBoxInfosCudaPtr', 'uint64', 0, None, 'Cuda buffer containing valid bounding boxes infos', {}, True, None, False, ''), ]) class tokens: SemanticBoundingBox3DInfosSD = "SemanticBoundingBox3DInfosSD" SemanticBoundingBox3DFilterInfosSD = "SemanticBoundingBox3DFilterInfosSD" @classmethod def _populate_role_data(cls): """Populate a role structure with the non-default roles on this node type""" role_data = super()._populate_role_data() role_data.inputs.exec = og.AttributeRole.EXECUTION role_data.outputs.exec = og.AttributeRole.EXECUTION return role_data class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [] self._batchedReadValues = [] @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.exec) data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def gpu(self): data_view = og.AttributeValueHelper(self._attributes.gpu) return data_view.get() @gpu.setter def gpu(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.gpu) data_view = og.AttributeValueHelper(self._attributes.gpu) data_view.set(value) @property def instanceMappingInfoSDPtr(self): data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr) return data_view.get() @instanceMappingInfoSDPtr.setter def instanceMappingInfoSDPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.instanceMappingInfoSDPtr) data_view = og.AttributeValueHelper(self._attributes.instanceMappingInfoSDPtr) data_view.set(value) @property def metersPerSceneUnit(self): data_view = og.AttributeValueHelper(self._attributes.metersPerSceneUnit) return data_view.get() @metersPerSceneUnit.setter def metersPerSceneUnit(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.metersPerSceneUnit) data_view = og.AttributeValueHelper(self._attributes.metersPerSceneUnit) data_view.set(value) @property def rp(self): data_view = og.AttributeValueHelper(self._attributes.rp) return data_view.get() @rp.setter def rp(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.rp) data_view = og.AttributeValueHelper(self._attributes.rp) data_view.set(value) @property def sdSemBBox3dCamCornersCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.sdSemBBox3dCamCornersCudaPtr) return data_view.get() @sdSemBBox3dCamCornersCudaPtr.setter def sdSemBBox3dCamCornersCudaPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.sdSemBBox3dCamCornersCudaPtr) data_view = og.AttributeValueHelper(self._attributes.sdSemBBox3dCamCornersCudaPtr) data_view.set(value) @property def sdSemBBoxInfosCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.sdSemBBoxInfosCudaPtr) return data_view.get() @sdSemBBoxInfosCudaPtr.setter def sdSemBBoxInfosCudaPtr(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.sdSemBBoxInfosCudaPtr) data_view = og.AttributeValueHelper(self._attributes.sdSemBBoxInfosCudaPtr) data_view.set(value) @property def viewportNearFar(self): data_view = og.AttributeValueHelper(self._attributes.viewportNearFar) return data_view.get() @viewportNearFar.setter def viewportNearFar(self, value): if self._setting_locked: raise og.ReadOnlyError(self._attributes.viewportNearFar) data_view = og.AttributeValueHelper(self._attributes.viewportNearFar) data_view.set(value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } @property def exec(self): data_view = og.AttributeValueHelper(self._attributes.exec) return data_view.get() @exec.setter def exec(self, value): data_view = og.AttributeValueHelper(self._attributes.exec) data_view.set(value) @property def sdSemBBoxInfosCudaPtr(self): data_view = og.AttributeValueHelper(self._attributes.sdSemBBoxInfosCudaPtr) return data_view.get() @sdSemBBoxInfosCudaPtr.setter def sdSemBBoxInfosCudaPtr(self, value): data_view = og.AttributeValueHelper(self._attributes.sdSemBBoxInfosCudaPtr) data_view.set(value) def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdPostSemantic3dBoundingBoxFilterDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdPostSemantic3dBoundingBoxFilterDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdPostSemantic3dBoundingBoxFilterDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
11,071
Python
45.915254
241
0.662722
omniverse-code/kit/exts/omni.syntheticdata/omni/syntheticdata/ogn/OgnSdTestStageManipulationScenariiDatabase.py
"""Support for simplified access to data on nodes of type omni.syntheticdata.SdTestStageManipulationScenarii Synthetic Data test node applying randomly some predefined stage manipulation scenarii """ import sys import traceback import omni.graph.core as og import omni.graph.core._omni_graph_core as _og import omni.graph.tools.ogn as ogn class OgnSdTestStageManipulationScenariiDatabase(og.Database): """Helper class providing simplified access to data on nodes of type omni.syntheticdata.SdTestStageManipulationScenarii Class Members: node: Node being evaluated Attribute Value Properties: Inputs: inputs.randomSeed inputs.worldPrimPath State: state.frameNumber """ # Imprint the generator and target ABI versions in the file for JIT generation GENERATOR_VERSION = (1, 41, 3) TARGET_VERSION = (2, 139, 12) # This is an internal object that provides per-class storage of a per-node data dictionary PER_NODE_DATA = {} # This is an internal object that describes unchanging attributes in a generic way # The values in this list are in no particular order, as a per-attribute tuple # Name, Type, ExtendedTypeIndex, UiName, Description, Metadata, # Is_Required, DefaultValue, Is_Deprecated, DeprecationMsg # You should not need to access any of this data directly, use the defined database interfaces INTERFACE = og.Database._get_interface([ ('inputs:randomSeed', 'int', 0, None, 'Random seed', {}, True, 0, False, ''), ('inputs:worldPrimPath', 'token', 0, None, 'Path of the world prim : contains every modifiable prim, cannot be modified', {}, True, "", False, ''), ('state:frameNumber', 'uint64', 0, None, 'Current frameNumber (number of invocations)', {ogn.MetadataKeys.DEFAULT: '0'}, True, 0, False, ''), ]) class ValuesForInputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = {"randomSeed", "worldPrimPath", "_setting_locked", "_batchedReadAttributes", "_batchedReadValues"} """Helper class that creates natural hierarchical access to input attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedReadAttributes = [self._attributes.randomSeed, self._attributes.worldPrimPath] self._batchedReadValues = [0, ""] @property def randomSeed(self): return self._batchedReadValues[0] @randomSeed.setter def randomSeed(self, value): self._batchedReadValues[0] = value @property def worldPrimPath(self): return self._batchedReadValues[1] @worldPrimPath.setter def worldPrimPath(self, value): self._batchedReadValues[1] = value def __getattr__(self, item: str): if item in self.LOCAL_PROPERTY_NAMES: return object.__getattribute__(self, item) else: return super().__getattr__(item) def __setattr__(self, item: str, new_value): if item in self.LOCAL_PROPERTY_NAMES: object.__setattr__(self, item, new_value) else: super().__setattr__(item, new_value) def _prefetch(self): readAttributes = self._batchedReadAttributes newValues = _og._prefetch_input_attributes_data(readAttributes) if len(readAttributes) == len(newValues): self._batchedReadValues = newValues class ValuesForOutputs(og.DynamicAttributeAccess): LOCAL_PROPERTY_NAMES = { } """Helper class that creates natural hierarchical access to output attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) self._batchedWriteValues = { } def _commit(self): _og._commit_output_attributes_data(self._batchedWriteValues) self._batchedWriteValues = { } class ValuesForState(og.DynamicAttributeAccess): """Helper class that creates natural hierarchical access to state attributes""" def __init__(self, node: og.Node, attributes, dynamic_attributes: og.DynamicAttributeInterface): """Initialize simplified access for the attribute data""" context = node.get_graph().get_default_graph_context() super().__init__(context, node, attributes, dynamic_attributes) @property def frameNumber(self): data_view = og.AttributeValueHelper(self._attributes.frameNumber) return data_view.get() @frameNumber.setter def frameNumber(self, value): data_view = og.AttributeValueHelper(self._attributes.frameNumber) data_view.set(value) def __init__(self, node): super().__init__(node) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_INPUT) self.inputs = OgnSdTestStageManipulationScenariiDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT) self.outputs = OgnSdTestStageManipulationScenariiDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes) dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE) self.state = OgnSdTestStageManipulationScenariiDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes) class abi: """Class defining the ABI interface for the node type""" @staticmethod def get_node_type(): get_node_type_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'get_node_type', None) if callable(get_node_type_function): return get_node_type_function() return 'omni.syntheticdata.SdTestStageManipulationScenarii' @staticmethod def compute(context, node): def database_valid(): return True try: per_node_data = OgnSdTestStageManipulationScenariiDatabase.PER_NODE_DATA[node.node_id()] db = per_node_data.get('_db') if db is None: db = OgnSdTestStageManipulationScenariiDatabase(node) per_node_data['_db'] = db if not database_valid(): per_node_data['_db'] = None return False except: db = OgnSdTestStageManipulationScenariiDatabase(node) try: compute_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'compute', None) if callable(compute_function) and compute_function.__code__.co_argcount > 1: return compute_function(context, node) db.inputs._prefetch() db.inputs._setting_locked = True with og.in_compute(): return OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS.compute(db) except Exception as error: stack_trace = "".join(traceback.format_tb(sys.exc_info()[2].tb_next)) db.log_error(f'Assertion raised in compute - {error}\n{stack_trace}', add_context=False) finally: db.inputs._setting_locked = False db.outputs._commit() return False @staticmethod def initialize(context, node): OgnSdTestStageManipulationScenariiDatabase._initialize_per_node_data(node) initialize_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'initialize', None) if callable(initialize_function): initialize_function(context, node) per_node_data = OgnSdTestStageManipulationScenariiDatabase.PER_NODE_DATA[node.node_id()] def on_connection_or_disconnection(*args): per_node_data['_db'] = None node.register_on_connected_callback(on_connection_or_disconnection) node.register_on_disconnected_callback(on_connection_or_disconnection) @staticmethod def release(node): release_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'release', None) if callable(release_function): release_function(node) OgnSdTestStageManipulationScenariiDatabase._release_per_node_data(node) @staticmethod def release_instance(node, target): OgnSdTestStageManipulationScenariiDatabase._release_per_node_instance_data(node, target) @staticmethod def update_node_version(context, node, old_version, new_version): update_node_version_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'update_node_version', None) if callable(update_node_version_function): return update_node_version_function(context, node, old_version, new_version) return False @staticmethod def initialize_type(node_type): initialize_type_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'initialize_type', None) needs_initializing = True if callable(initialize_type_function): needs_initializing = initialize_type_function(node_type) if needs_initializing: node_type.set_metadata(ogn.MetadataKeys.EXTENSION, "omni.syntheticdata") node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:simulation,internal:test") node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Synthetic Data test node applying randomly some predefined stage manipulation scenarii") node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests") node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python") OgnSdTestStageManipulationScenariiDatabase.INTERFACE.add_to_node_type(node_type) node_type.set_has_state(True) @staticmethod def on_connection_type_resolve(node): on_connection_type_resolve_function = getattr(OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS, 'on_connection_type_resolve', None) if callable(on_connection_type_resolve_function): on_connection_type_resolve_function(node) NODE_TYPE_CLASS = None @staticmethod def register(node_type_class): OgnSdTestStageManipulationScenariiDatabase.NODE_TYPE_CLASS = node_type_class og.register_node_type(OgnSdTestStageManipulationScenariiDatabase.abi, 1) @staticmethod def deregister(): og.deregister_node_type("omni.syntheticdata.SdTestStageManipulationScenarii")
11,395
Python
47.288135
158
0.656955