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.collaboration.presence_layer/omni/kit/collaboration/presence_layer/__init__.py | # Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from .extension import *
from .event import *
from .constants import LAYER_SUBSCRIPTION_ORDER | 526 | Python | 46.909087 | 76 | 0.807985 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/utils.py | import carb
from .constants import *
from pxr import Sdf, Usd, UsdGeom
class CarbProfilerScope: # pragma: no cover
def __init__(self, id, name):
self._id = id
self._name = name
def __enter__(self):
carb.profiler.begin(self._id, self._name)
def __exit__(self, type, value, trace):
carb.profiler.end(self._id)
@carb.profiler.profile
def get_user_id_from_path(path: Sdf.Path):
prefixes = path.GetPrefixes()
if len(prefixes) < 2:
return None
# "/{SESSION_SHARED_LAYER_ROOT_NAME}/_{self.user_id}"
# Premove the prefix _ to get real user id.
user_id = prefixes[1].name[1:]
return user_id
def is_local_builtin_camera(path: Sdf.Path):
"""
Checkes if it's local builtin camera. If so, it will return the corresponding builtin camera
name for bound camera property.
"""
path = Sdf.Path(path)
return LOCAL_BUILT_IN_CAMERA_PATH_TO_SHARED_NAME.get(path, None)
def get_user_shared_root_path(user_id: str) -> Sdf.Path:
# The prefix "_" is used to make sure the id is valid for identifier
return SESSION_SHARED_LAYER_ROOT_PATH.AppendElementString(f"_{user_id}")
def get_bound_camera_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_BOUND_CAMERA_PROPERTY_NAME)
def get_selection_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_SELECTION_PROPERTY_NAME)
def get_following_user_property_path(user_id: str) -> Sdf.Path:
shared_root_path = get_user_shared_root_path(user_id)
return shared_root_path.AppendProperty(SESSION_SHARED_FOLLOWING_USER_PROPERTY_NAME)
def get_or_create_property_spec(layer, property_path, typename, is_custom=True):
property_spec = layer.GetAttributeAtPath(property_path)
if property_spec and property_spec.typeName != typename:
carb.log_verboase(f"Type of property {property_spec} does not match: {property_spec.typeName}, {typename}.")
prim_spec = layer.GetPrimAtPath(property_path.GetPrimPath())
if prim_spec:
prim_spec.RemoveProperty(property_spec)
property_spec = None
if not property_spec:
Sdf.JustCreatePrimAttributeInLayer(
layer, property_path, typename, isCustom=is_custom
)
property_spec = layer.GetAttributeAtPath(property_path)
return property_spec
| 2,521 | Python | 30.135802 | 116 | 0.686632 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/presence_layer_manager.py | import asyncio
import carb
import time
import omni.client
import omni.usd
import omni.kit.usd.layers as layers
import omni.kit.app
from omni.kit.async_engine import run_coroutine
from pxr import Sdf, Usd, UsdGeom, Tf, Trace, Gf
from typing import Dict, List, Union, Set
from .utils import (
get_user_id_from_path, get_bound_camera_property_path, get_following_user_property_path,
get_selection_property_path, get_user_shared_root_path, get_or_create_property_spec,
is_local_builtin_camera
)
from .event import PresenceLayerEventType, EVENT_PAYLOAD_KEY
from .constants import *
from .peer_user_shared_data import PeerUserSharedData
class PresenceLayerChanges:
def __init__(self) -> None:
self.clear()
def clear(self):
self.bound_camera_changed_ids = set()
self.selection_changed_ids = set()
self.following_user_changed_ids = set()
self.camera_info_changes = {}
self.resynced_camera_ids = set()
def is_empty(self):
return (
not self.bound_camera_changed_ids and
not self.selection_changed_ids and
not self.following_user_changed_ids and
not self.camera_info_changes and
not self.resynced_camera_ids
)
def add_camera_info_change(self, user_id, path):
changes = self.camera_info_changes.get(user_id, None)
if changes is None:
self.camera_info_changes[user_id] = set()
# Changed property name
self.camera_info_changes[user_id].add(path.name)
def __str__(self):
return (f"Bound Camera Changed: {self.bound_camera_changed_ids}, "
f"Seletion Changed: {self.selection_changed_ids}, "
f"Following User Changed: {self.following_user_changed_ids}, "
f"Camera Info Changed: {self.camera_info_changes}, "
f"Camera Resynced: {self.resynced_camera_ids}")
class PresenceLayerManager:
def __init__(self, usd_context):
self.__usd_context = usd_context
self.__live_syncing = layers.get_live_syncing(self.__usd_context)
self.__layers = layers.get_layers(self.__usd_context)
self.__shared_data_stage = None
self.__peer_users: Dict[str, PeerUserSharedData] = {}
# Fast access to query the follow relationship. Key is the
# user id that's followed, and values are the user ids that
# are currently following this user.
self.__user_following_map: Dict[str, Set[str]] = {}
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
self.__shared_stage_objects_changed = None
self.__delayed_changes_handle_task = None
self.__local_following_user_id = None
self.__pending_changed_paths = set()
def start(self):
for event in [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
layers.LayerEventType.LIVE_SESSION_MERGE_ENDED,
]:
layers_event_sub = self.__layers.get_event_stream().create_subscription_to_pop_by_type(
event, self.__on_layers_event, name=f"Layers event: omni.kit.collaboration.presence_layer {str(event)}",
order=LAYER_SUBSCRIPTION_ORDER
)
self.__layers_event_subscriptions.append(layers_event_sub)
self.__stage_event_subscription = self.__usd_context.get_stage_event_stream().create_subscription_to_pop(
self.__on_stage_event, name="Stage event: omni.kit.collaboration.presence_layer"
)
stage_url = self.__usd_context.get_stage_url()
if not stage_url.startswith("omniverse:"):
return
self.__on_session_state_changed()
def __on_stage_event(self, event):
if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED):
self.__on_selection_changed()
elif event.type == int(omni.usd.StageEventType.CLOSING):
self.__stop_subscription()
def __on_selection_changed(self):
if not self.__shared_data_stage:
return
selection = self.__usd_context.get_selection()
selected_prim_paths = selection.get_selected_prim_paths() or []
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
logged_user_id = current_session.logged_user_id
selection_property_path = get_selection_property_path(logged_user_id)
with Sdf.ChangeBlock():
property_spec = get_or_create_property_spec(
self.__shared_data_stage.GetRootLayer(), selection_property_path,
Sdf.ValueTypeNames.StringArray
)
property_spec.default = selected_prim_paths
def __start_subscription(self):
# Skip it if one of its sublayer is in live session already.
if self.__shared_data_stage:
return
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
self.__shared_data_stage = self.__create_or_open_shared_stage(current_session)
if not self.__shared_data_stage:
return
self.__shared_stage_objects_changed = Tf.Notice.Register(
Usd.Notice.ObjectsChanged, self.__on_shared_usd_changed, self.__shared_data_stage
)
stage = self.__usd_context.get_stage()
target_layer = stage.GetSessionLayer()
with Usd.EditContext(stage, target_layer):
prim = stage.DefinePrim(LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH, "Scope")
omni.usd.editor.set_hide_in_stage_window(prim, True)
omni.usd.editor.set_hide_in_ui(prim, True)
for peer_user in current_session.peer_users:
self.__track_new_user(peer_user.user_id)
def __stop_subscription(self):
for peer_user in self.__peer_users.values():
peer_user.destroy()
self.__peer_users.clear()
self.__pending_changed_paths.clear()
self.__shared_data_stage = None
if self.__shared_stage_objects_changed:
self.__shared_stage_objects_changed.Revoke()
self.__shared_stage_objects_changed = None
if self.__delayed_changes_handle_task:
self.__delayed_changes_handle_task.cancel()
self.__delayed_changes_handle_task = None
local_stage = self.__usd_context.get_stage()
if local_stage:
layers.LayerUtils.remove_prim_spec(
local_stage.GetSessionLayer(),
LOCAL_SESSION_LAYER_SHARED_DATA_ROOT_PATH
)
self.__user_following_map.clear()
def stop(self):
self.__stop_subscription()
self.__layers_event_subscriptions = []
self.__stage_event_subscription = None
@carb.profiler.profile
def __notify_changes(self, pending_changes):
if pending_changes.is_empty():
return
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if not event_stream:
return
def __check_and_send_events(event_type, changed_ids, lambda_filter):
valid_users = []
for user_id in changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not lambda_filter(peer_user):
continue
valid_users.append(user_id)
if valid_users:
event_stream.push(int(event_type), 0, {EVENT_PAYLOAD_KEY: valid_users})
return valid_users
all_bound_camera_changed_ids = set()
for user_id in pending_changes.following_user_changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not peer_user.update_following_user():
continue
old_following_user_id = peer_user.following_user_id
if old_following_user_id:
self.__remove_following_user(user_id, old_following_user_id)
new_following_user_id = peer_user.following_user_id
if new_following_user_id:
self.__track_following_user(user_id, new_following_user_id)
all_bound_camera_changed_ids.add(user_id)
for user_id in pending_changes.bound_camera_changed_ids:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user or not peer_user.update_bound_camera():
continue
all_bound_camera_changed_ids.add(user_id)
# Updates all users that are currently following this user also.
all_bound_camera_changed_ids.update(self.get_all_following_users(user_id))
if all_bound_camera_changed_ids:
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0,
{EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)}
)
__check_and_send_events(
PresenceLayerEventType.BOUND_CAMERA_RESYNCED,
pending_changes.resynced_camera_ids,
lambda user: True
)
__check_and_send_events(
PresenceLayerEventType.SELECTIONS_CHANGED,
pending_changes.selection_changed_ids,
lambda user: user.update_selections()
)
camera_info_changes = pending_changes.camera_info_changes
if camera_info_changes:
# FIXME: WA to make sure changes can be serialized to event stream.
camera_changes_payload = {}
with Sdf.ChangeBlock():
for user_id, property_names in camera_info_changes.items():
peer_user = self.__peer_users.get(user_id, None)
if property_names:
peer_user.replicate_bound_camera_to_local(property_names)
camera_changes_payload[user_id] = list(property_names)
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_PROPERTIES_CHANGED),
payload=camera_changes_payload
)
@carb.profiler.profile
async def __handling_pending_changes(self):
pending_changes = PresenceLayerChanges()
pending_changed_paths = self.__pending_changed_paths
self.__pending_changed_paths = set()
for path in pending_changed_paths:
if path == SESSION_SHARED_LAYER_ROOT_PATH or path == Sdf.Path.absoluteRootPath:
pending_changes.bound_camera_changed_ids.update(self.__peer_users.keys())
pending_changes.following_user_changed_ids.update(self.__peer_users.keys())
pending_changes.selection_changed_ids.update(self.__peer_users.keys())
pending_changes.resynced_camera_ids.update(self.__peer_users.keys())
break
user_id = get_user_id_from_path(path)
peer_user = self.__peer_users.get(user_id)
if not peer_user:
continue
if path == peer_user.shared_root_path:
pending_changes.bound_camera_changed_ids.add(user_id)
pending_changes.following_user_changed_ids.add(user_id)
pending_changes.selection_changed_ids.add(user_id)
pending_changes.resynced_camera_ids.add(user_id)
continue
# Checkes bound_camera property under user root
if peer_user.is_following_user_property_affected(path):
pending_changes.following_user_changed_ids.add(user_id)
elif peer_user.is_selection_property_affected(path):
pending_changes.selection_changed_ids.add(user_id)
elif peer_user.is_bound_camera_property_affected(path):
pending_changes.bound_camera_changed_ids.add(user_id)
elif peer_user.is_builtin_camera_affected(path):
# Only sync properties that are under camera prim.
if path.IsPropertyPath():
pending_changes.add_camera_info_change(user_id, path)
else:
pending_changes.resynced_camera_ids.add(user_id)
self.__notify_changes(pending_changes)
self.__delayed_changes_handle_task = None
@carb.profiler.profile
def __on_shared_usd_changed(self, notice, sender):
if not sender or sender != self.__shared_data_stage:
return
self.__pending_changed_paths.update(notice.GetResyncedPaths())
self.__pending_changed_paths.update(notice.GetChangedInfoOnlyPaths())
if not self.__pending_changed_paths:
return
if not self.__delayed_changes_handle_task or self.__delayed_changes_handle_task.done():
self.__delayed_changes_handle_task = run_coroutine(self.__handling_pending_changes())
def __create_or_open_shared_stage(self, session: layers.LiveSession):
session_url = session.url
if not session_url.endswith("/"):
session_url += "/"
shared_data_layer_path = omni.client.combine_urls(session_url, SESSION_SHARED_USER_LAYER)
layer = Sdf.Layer.FindOrOpen(shared_data_layer_path)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_layer_path)
if not layer:
carb.log_warn(f"Failed to open shared data layer {shared_data_layer_path}.")
return None
Sdf.CreatePrimInLayer(layer, SESSION_SHARED_LAYER_ROOT_PATH)
stage = Usd.Stage.Open(layer)
return stage
@property
def shared_data_stage(self) -> Usd.Stage:
return self.__shared_data_stage
def __on_session_state_changed(self):
if not self.__live_syncing.is_in_live_session():
self.__stop_subscription()
else:
self.__start_subscription()
def __track_new_user(self, user_id):
if user_id in self.__peer_users:
return
if not self.__shared_data_stage:
return
current_session = self.__live_syncing.get_current_live_session()
if not current_session:
return
user_info = current_session.get_peer_user_info(user_id)
if not user_info:
return
peer_user = PeerUserSharedData(self.__usd_context, self.__shared_data_stage, user_info)
self.__peer_users[user_id] = peer_user
following_user_id = peer_user.following_user_id
if following_user_id:
self.__track_following_user(user_id, following_user_id)
def __track_following_user(self, user_id, following_user_id):
user_ids = self.__user_following_map.get(following_user_id, None)
if not user_ids:
user_ids = set()
self.__user_following_map[following_user_id] = user_ids
user_ids.add(user_id)
def __untrack_followed_user(self, user_id):
for following_users in self.__user_following_map.values():
following_users.discard(user_id)
self.__user_following_map.pop(user_id, None)
def __remove_following_user(self, user_id, followed_user_id):
"""Removes user_id from list that are currently following followed_user_id."""
user_list = self.__user_following_map.get(followed_user_id, None)
if not user_list:
return False
if user_id in user_list:
user_list.discard(user_id)
return True
return False
def __untrack_user(self, user_id):
self.__untrack_followed_user(user_id)
peer_user = self.__peer_users.pop(user_id, None)
if peer_user:
peer_user.destroy()
def __on_layers_event(self, event):
payload = layers.get_layer_event_payload(event)
if not payload:
return
interested_events = [
layers.LayerEventType.LIVE_SESSION_STATE_CHANGED,
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
layers.LayerEventType.LIVE_SESSION_USER_LEFT,
layers.LayerEventType.LIVE_SESSION_MERGE_ENDED
]
if payload.event_type not in interested_events:
return
if not payload.is_layer_influenced(self.__usd_context.get_stage_url()):
return
if payload.event_type == layers.LayerEventType.LIVE_SESSION_STATE_CHANGED:
self.__on_session_state_changed()
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_JOINED:
# Creates user shared data
# Try to copy camera info and add widgets for the bound camera.
self.__track_new_user(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_USER_LEFT:
self.__untrack_user(payload.user_id)
elif payload.event_type == layers.LayerEventType.LIVE_SESSION_MERGE_ENDED:
if payload.success:
self.__shared_data_stage.GetRootLayer().Clear()
def get_all_following_users(self, followed_user_id):
"""Get all user ids that are currently following followed_user_id."""
return self.__user_following_map.get(followed_user_id, set())
def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]:
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
accessed_user_ids = set()
usd_prim = None
while True:
# To avoid A follows B and B follows A
if user_id in accessed_user_ids:
break
accessed_user_ids.add(user_id)
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
break
usd_prim = peer_user.get_bound_camera_prim()
if usd_prim:
break
# It's following other users.
user_id = self.get_following_user_id(user_id)
# If it's following me.
if user_id == current_session.logged_user_id:
accessed_user_ids.add(user_id)
shared_data_stage = self.__shared_data_stage
current_stage = self.__usd_context.get_stage()
my_bound_camera_property_path = get_bound_camera_property_path(user_id)
camera_path_property = shared_data_stage.GetRootLayer().GetAttributeAtPath(
my_bound_camera_property_path
)
if camera_path_property:
bound_camera_path = str(camera_path_property.default).strip()
# Maps builin camera binding to local path or keep it intact.
bound_camera_path = SHARED_NAME_TO_LOCAL_BUILT_IN_CAMERA_PATH.get(
bound_camera_path, bound_camera_path
)
if bound_camera_path:
usd_prim = current_stage.GetPrimAtPath(bound_camera_path)
break
# Otherwise, checking local Kit is following other user to pass the ball.
my_following_user_property_path = get_following_user_property_path(user_id)
following_user_property = shared_data_stage.GetRootLayer().GetAttributeAtPath(
my_following_user_property_path
)
if not following_user_property:
break
user_id = str(following_user_property.default).strip()
if not user_id or not current_session.get_peer_user_info(user_id):
break
return usd_prim
def is_bound_to_builtin_camera(self, user_id):
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return False
return peer_user.is_bound_to_builtin_camera()
def get_following_user_id(self, user_id: str = None) -> str:
"""Gets the user id that the specific user is currently following."""
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return None
if user_id is None:
user_id = current_session.logged_user_id
# Local user is handled differently as peer users.
if user_id == current_session.logged_user_id:
following_user_property_path = get_following_user_property_path(current_session.logged_user_id)
following_user_property = self.__shared_data_stage.GetRootLayer().GetAttributeAtPath(
following_user_property_path
)
if following_user_property:
following_user_id = str(following_user_property.default).strip()
if following_user_id and following_user_id in self.__peer_users:
return following_user_id
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return None
# Ensure the following user id is currently in the live session.
following_user = self.__peer_users.get(peer_user.following_user_id, None)
logged_user_id = current_session.logged_user_id
if following_user or peer_user.following_user_id == logged_user_id:
return peer_user.following_user_id
return None
def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str:
following_user_id = self.get_following_user_id(followed_by_user_id)
return following_user_id == user_id
def get_selections(self, user_id: str) -> List[Sdf.Path]:
peer_user = self.__peer_users.get(user_id, None)
if not peer_user:
return None
return peer_user.selections
def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path):
if not local_camera_path:
local_camera_path = Sdf.Path.emptyPath
else:
local_camera_path = Sdf.Path(local_camera_path)
shared_data_stage = self.__shared_data_stage
if not shared_data_stage:
return
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return
# If camera does not exist
if local_camera_path:
current_stage = self.__usd_context.get_stage()
camera_prim = current_stage.GetPrimAtPath(local_camera_path)
if not camera_prim or not UsdGeom.Camera(camera_prim):
carb.log_error(f"Cannot sync camera {local_camera_path} to presence layer as it does not exist.")
return
logged_user_id = current_session.logged_user_id
bound_camera_property_path = get_bound_camera_property_path(logged_user_id)
following_user_property_path = get_following_user_property_path(logged_user_id)
local_builtin_camera = is_local_builtin_camera(local_camera_path)
camera_path = local_builtin_camera or local_camera_path # It's local builtin camera path or stage camera.
camera_path = str(camera_path) if camera_path else ""
with Sdf.ChangeBlock():
# Only synchronizes builtin camera as non-builtin cameras are visible to all users already.
if local_builtin_camera:
user_shared_root = get_user_shared_root_path(logged_user_id)
shared_camera_prim_path = user_shared_root.AppendElementString(local_builtin_camera)
Sdf.CreatePrimInLayer(shared_data_stage.GetRootLayer(), shared_camera_prim_path)
Sdf.CopySpec(
current_stage.GetSessionLayer(), local_camera_path,
shared_data_stage.GetRootLayer(), shared_camera_prim_path
)
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = camera_path
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = ""
# Notify all users that are currently following the local user.
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
all_bound_camera_changed_ids = set()
all_bound_camera_changed_ids.update(self.get_all_following_users(logged_user_id))
if all_bound_camera_changed_ids:
event_stream.push(
int(PresenceLayerEventType.BOUND_CAMERA_CHANGED), 0,
{EVENT_PAYLOAD_KEY: list(all_bound_camera_changed_ids)}
)
def __set_following_user_id_property(self, following_user_id):
"""Broadcasts local user's following id."""
shared_data_stage = self.__shared_data_stage
if not shared_data_stage:
return False
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
logged_user_id = current_session.logged_user_id
following_user_property_path = get_following_user_property_path(logged_user_id)
bound_camera_property_path = get_bound_camera_property_path(logged_user_id)
with Sdf.ChangeBlock():
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
if following_user_id:
property_spec.default = ""
else:
# Quits to perspective camera by default.
property_spec.default = "/OmniverseKit_Persp"
property_spec = get_or_create_property_spec(
shared_data_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
if self.__local_following_user_id:
self.__remove_following_user(logged_user_id, self.__local_following_user_id)
self.__local_following_user_id = following_user_id
if following_user_id:
self.__track_following_user(logged_user_id, following_user_id)
return True
def enter_follow_mode(self, following_user_id: str):
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
carb.log_warn(f"Cannot follow user {following_user_id} as it's not in a live session.")
return False
if current_session.logged_user_id == following_user_id:
carb.log_warn("Cannot follow myself.")
return False
following_user = self.__peer_users.get(following_user_id, None)
if not following_user:
carb.log_warn(f"Cannot follow user {following_user_id} as the user does not exist in the session.")
return False
if not self.get_bound_camera_prim(following_user_id):
message = f"Cannot follow user {following_user.user_name} as the user does not share bound camera."
try:
import omni.kit.notification_manager as nm
nm.post_notification(message, status=nm.NotificationStatus.WARNING)
except ImportError:
pass
finally:
carb.log_warn(message)
return False
# If user is already following me or other users, reports errors.
if (
following_user.following_user_id and
(
following_user.following_user_id == current_session.logged_user_id or
following_user.following_user_id in self.__peer_users
)
):
carb.log_warn(f"Cannot follow user {following_user.user_name} as the user is in following mode.")
return False
if self.get_following_user_id() == following_user_id:
return True
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if self.__set_following_user_id_property(following_user_id):
event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
return True
return False
def quit_follow_mode(self):
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
if self.is_in_following_mode(current_session.logged_user_id):
event_stream = layers.get_layers(self.__usd_context).get_event_stream()
if self.__set_following_user_id_property(""):
event_stream.dispatch(PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
def can_follow(self, user_id):
following_user = self.__peer_users.get(user_id, None)
return not following_user or following_user.following_user_id
def is_in_following_mode(self, user_id: str = None) -> bool:
"""
Checkes if the user is following other user.
user_id (str): The user id to check. By default, it's None, which means to check if local user is in follow mode.
"""
live_syncing = self.__live_syncing
current_session = live_syncing.get_current_live_session()
if not current_session:
return False
if user_id is None:
user_id = current_session.logged_user_id
following_user_id = self.get_following_user_id(user_id)
if following_user_id:
return True
else:
return False
class PresenceLayerAPI:
"""
Presence layer is the transport layer that works for exchange persistent data for
all users in the same Live Session. PresenceLayerAPI provides the APIs that serve
for easy access to data of presence layer.
"""
def __init__(self, presence_layer_instance: PresenceLayerManager) -> None:
self.__presence_layer_instance = presence_layer_instance
def is_bound_to_builtin_camera(self, user_id):
"""
Checkes if peer user is bound to builtin camera. If peer user is following other user,
it will always return False.
"""
return self.__presence_layer_instance.is_bound_to_builtin_camera(user_id)
@carb.profiler.profile
def get_bound_camera_prim(self, user_id) -> Union[Usd.Prim, None]:
"""
Gets the bound camera of the peer user in the local stage. If peer user is following other user, it will
return the bound camera of the following user.
"""
return self.__presence_layer_instance.get_bound_camera_prim(user_id)
def get_following_user_id(self, user_id: str = None) -> str:
"""
Gets the user id that the specific user is currently following.
user_id (str): User id, includes both local and peer users. If it's None, it will return the user id that
local user is currently following.
"""
return self.__presence_layer_instance.get_following_user_id(user_id)
def is_user_followed_by(self, user_id: str, followed_by_user_id: str) -> str:
"""
Checkes if user is followed by other specific user.
Args:
user_id (str): The user id to query.
followed_by_user_id (str): The user that's following the one has user_id.
"""
return self.__presence_layer_instance.is_user_followed_by(user_id, followed_by_user_id)
def get_selections(self, user_id: str) -> List[Sdf.Path]:
"""Gets the prim paths that the user selects."""
return self.__presence_layer_instance.get_selections(user_id)
@carb.profiler.profile
def broadcast_local_bound_camera(self, local_camera_path: Sdf.Path):
"""
Broadcasts local bound camera to presence layer. Local application can be either in
bound camera mode or following user mode. Switching bound camera will quit
following user mode.
"""
return self.__presence_layer_instance.broadcast_local_bound_camera(local_camera_path)
@carb.profiler.profile
def enter_follow_mode(self, following_user_id: str):
"""
Try to follow user from local. Local application can be either in
bound camera mode or following user mode. Switching bound camera will quit
following user mode. If the user specified by following_user_id is in following
mode already, this function will return False.
Args:
following_user_id (str): The user id that local user is trying to follow.
"""
return self.__presence_layer_instance.enter_follow_mode(following_user_id)
def quit_follow_mode(self):
self.__presence_layer_instance.quit_follow_mode()
def can_follow(self, user_id):
"""If the specified peer user can be followed."""
return self.__presence_layer_instance.can_follow(user_id)
def is_in_following_mode(self, user_id: str = None):
"""
Checkes if the user is following other user.
user_id (str): User id, including both the local and peer users. By default, it's None, which means to
check if local user is in follow mode.
"""
return self.__presence_layer_instance.is_in_following_mode(user_id)
def get_shared_data_stage(self):
return self.__presence_layer_instance.shared_data_stage
| 33,571 | Python | 38.589623 | 121 | 0.613446 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/__init__.py | from .test_presence_layer import * | 34 | Python | 33.999966 | 34 | 0.794118 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/omni/kit/collaboration/presence_layer/tests/test_presence_layer.py | import carb
import omni.kit.test
import omni.usd
import omni.client
import unittest
import omni.kit.app
import carb.settings
import omni.kit.collaboration.presence_layer as pl
import omni.kit.collaboration.presence_layer.utils as pl_utils
import omni.kit.usd.layers as layers
from omni.kit.usd.layers.tests.mock_utils import MockLiveSyncingApi
from pxr import Usd, Sdf
from typing import List
class TestPresenceLayer(omni.kit.test.AsyncTestCase):
# Before running each test
async def setUp(self):
self.app = omni.kit.app.get_app()
self.usd_context = omni.usd.get_context()
self.layers = layers.get_layers(self.usd_context)
self.live_syncing = layers.get_live_syncing(self.usd_context)
self.local_builtin_cameras = [
"/OmniverseKit_Persp", "/OmniverseKit_Front", "/OmniverseKit_Top", "/OmniverseKit_Right"
]
await omni.usd.get_context().new_stage_async()
self.simulated_user_name = "test"
self.simulated_user_id = "abcde"
self.simulated_user_name2 = "test2"
self.simulated_user_id2 = "abcdef"
async def tearDown(self):
pass
async def wait(self, frames=10):
for i in range(frames):
await self.app.next_update_async()
async def __create_session_and_simulate_users(self):
session = self.live_syncing.find_live_session_by_name(self.stage_url, "test")
if not session:
session = self.live_syncing.create_live_session("test", self.stage_url)
self.assertTrue(session, "Failed to create live session.")
self.assertTrue(self.live_syncing.join_live_session(session))
await self.wait()
# Access private variable to simulate user login.
user = layers.LiveSessionUser(self.simulated_user_name, self.simulated_user_id, "Create")
user2 = layers.LiveSessionUser(self.simulated_user_name2, self.simulated_user_id2, "Create")
current_session = self.live_syncing.get_current_live_session()
session_channel = current_session._session_channel()
session_channel._peer_users[self.simulated_user_id] = user
session_channel._peer_users[self.simulated_user_id2] = user2
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
{"user_name": self.simulated_user_name, "user_id": self.simulated_user_id}
)
session_channel._send_layer_event(
layers.LayerEventType.LIVE_SESSION_USER_JOINED,
{"user_name": self.simulated_user_name2, "user_id": self.simulated_user_id2}
)
await self.wait()
def __get_shared_stage(self, current_session: layers.LiveSession):
shared_data_stage_url = current_session.url + "/shared_data/users.live"
layer = Sdf.Layer.FindOrOpen(shared_data_stage_url)
if not layer:
layer = Sdf.Layer.CreateNew(shared_data_stage_url)
return Usd.Stage.Open(layer)
async def __bound_camera(self, shared_stage: Usd.Stage, user_id: str, camera_path: Sdf.Path):
if not camera_path:
camera_path = Sdf.Path.emptyPath
camera_path = Sdf.Path(camera_path)
bound_camera_property_path = pl_utils.get_bound_camera_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), bound_camera_property_path,
Sdf.ValueTypeNames.String
)
builtin_camera_name = pl_utils.is_local_builtin_camera(camera_path)
if not builtin_camera_name:
property_spec.default = str(camera_path)
else:
property_spec.default = builtin_camera_name
if builtin_camera_name:
persp_camera = pl_utils.get_user_shared_root_path(user_id).AppendChild(builtin_camera_name)
camera_prim = shared_stage.DefinePrim(persp_camera, "Camera")
await self.wait()
async def __select_prims(self, shared_stage: Usd.Stage, user_id: str, selections: List[str]):
selection_property_path = pl_utils.get_selection_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), selection_property_path,
Sdf.ValueTypeNames.StringArray
)
property_spec.default = selections
await self.wait()
async def __follow_user(
self, shared_stage: Usd.Stage, user_id: str, following_user_id: str
):
following_user_property_path = pl_utils.get_following_user_property_path(user_id)
property_spec = pl_utils.get_or_create_property_spec(
shared_stage.GetRootLayer(), following_user_property_path,
Sdf.ValueTypeNames.String
)
property_spec.default = following_user_id
await self.wait()
@MockLiveSyncingApi
async def test_api(self):
self.stage_url = "omniverse://__faked_omniverse_server__/test/test.usd"
format = Sdf.FileFormat.FindByExtension(".usd")
layer = Sdf.Layer.New(format, self.stage_url)
stage = Usd.Stage.Open(layer)
await self.usd_context.attach_stage_async(stage)
self.all_camera_paths = []
for i in range(10):
camera_path = Sdf.Path(f"/Camera{i}")
stage.DefinePrim(camera_path, "Camera")
self.all_camera_paths.append(camera_path)
# Simulated builtin cameras
with Usd.EditContext(stage, stage.GetSessionLayer()):
for camera_path in self.local_builtin_cameras:
stage.DefinePrim(camera_path, "Camera")
self.all_camera_paths.append(camera_path)
def _on_layers_event(event):
nonlocal payload
p = pl.get_presence_layer_event_payload(event)
if p.event_type:
payload = p
subscription = self.layers.get_event_stream().create_subscription_to_pop(
_on_layers_event, name="omni.kit.collaboration.presence_layer.tests"
)
await self.__create_session_and_simulate_users()
current_live_session = self.live_syncing.get_current_live_session()
shared_stage = self.__get_shared_stage(current_live_session)
self.assertTrue(shared_stage)
presence_layer = pl.get_presence_layer_interface(self.usd_context)
# Simulated user has empty camera bound at start.
self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id))
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
self.assertFalse(presence_layer.get_following_user_id(self.simulated_user_id))
self.assertFalse(presence_layer.get_selections(self.simulated_user_id))
# Bound to invalid camera
for camera_path in ["/nonexisted", ""]:
await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertFalse(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id))
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
payload = None
# Bound to valid camera
for camera_path in self.all_camera_paths:
camera_path = Sdf.Path(camera_path)
is_builtin_camera = pl_utils.is_local_builtin_camera(camera_path) is not None
await self.__bound_camera(shared_stage, self.simulated_user_id, camera_path)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED, camera_path)
self.assertEqual(presence_layer.is_bound_to_builtin_camera(self.simulated_user_id), is_builtin_camera, camera_path)
self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id), camera_path)
# Selections
for selections in [["/test", "/test2"], [], ["/test", "/test2", "test3"]]:
payload = None
await self.__select_prims(shared_stage, self.simulated_user_id, selections)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.SELECTIONS_CHANGED)
self.assertEqual(presence_layer.get_selections(self.simulated_user_id), selections, selections)
# Following user
# Setups default camera
logged_user_id = current_live_session.logged_user_id
presence_layer.broadcast_local_bound_camera("/OmniverseKit_Persp")
await self.__bound_camera(shared_stage, self.simulated_user_id2, self.all_camera_paths[0])
for user_id in [logged_user_id, self.simulated_user_id2]:
payload = None
await self.__follow_user(shared_stage, self.simulated_user_id, user_id)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertEqual(presence_layer.get_following_user_id(self.simulated_user_id), user_id)
self.assertTrue(presence_layer.is_user_followed_by(user_id, self.simulated_user_id))
self.assertTrue(presence_layer.get_bound_camera_prim(self.simulated_user_id))
user_id = "invalid_user_id"
payload = None
await self.__follow_user(shared_stage, self.simulated_user_id, user_id)
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.BOUND_CAMERA_CHANGED)
self.assertFalse(presence_layer.get_bound_camera_prim(self.simulated_user_id))
self.assertFalse(presence_layer.is_in_following_mode(self.simulated_user_id), user_id)
self.assertFalse(presence_layer.is_user_followed_by(user_id, self.simulated_user_id))
await self.__follow_user(shared_stage, self.simulated_user_id, "")
payload = None
self.assertFalse(presence_layer.enter_follow_mode(logged_user_id))
self.assertTrue(presence_layer.enter_follow_mode(self.simulated_user_id))
await self.wait()
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
self.assertEqual(presence_layer.get_following_user_id(), self.simulated_user_id)
self.assertTrue(presence_layer.is_in_following_mode(logged_user_id))
self.assertTrue(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id))
payload = None
presence_layer.quit_follow_mode()
await self.wait()
self.assertTrue(payload)
self.assertEqual(payload.event_type, pl.PresenceLayerEventType.LOCAL_FOLLOW_MODE_CHANGED)
self.assertFalse(presence_layer.get_following_user_id())
self.assertFalse(presence_layer.is_in_following_mode(logged_user_id))
self.assertFalse(presence_layer.is_user_followed_by(self.simulated_user_id, logged_user_id))
| 10,977 | Python | 45.12605 | 127 | 0.667213 |
omniverse-code/kit/exts/omni.kit.collaboration.presence_layer/docs/index.rst | omni.kit.collaboration.presence_layer
######################################
Live Session: Presence Layer
Introduction
============
Presence Layer works for storage for exchanging persistent data for all users in the same Live Session. The theory
behind uses .live layer as transport layer, on top of which all user data are structured as USD prim. It provides
easy API to access the data without using raw USD API, and also event stream to subscribe the data changes. Currently,
it's used for spatial awareness, which includes the following applications:
* Bound Camera.
* Selections.
* User Following.
User can exchange and synchronize their local states of the above applications into the Presence Layer for other users
to be aware of.
Presence Layer is bound to UsdContext. For each context, it has an unique presence layer. | 833 | reStructuredText | 40.699998 | 118 | 0.755102 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/hotkeys.py | from typing import Optional
import carb
import omni.kit.app
from omni.kit.actions.core import get_action_registry
_HOTKEYS_EXT = "omni.kit.hotkeys.core"
_DEFAULT_HOTKEY_MAP = {
"perspective_camera": "ALT+P",
"top_camera": "ALT+T",
"front_camera": "ALT+F",
"right_camera": "ALT+R",
"toggle_grid_visibility": "G",
"toggle_camera_visibility": "SHIFT+C",
"toggle_light_visibility": "SHIFT+L",
"toggle_global_visibility": "SHIFT+H",
"toggle_wireframe": "SHIFT+W",
}
def register_hotkeys(extension_id: str, window_name: Optional[str] = None):
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
if not ext_manager.is_extension_enabled(_HOTKEYS_EXT):
carb.log_info(f"{_HOTKEYS_EXT} is not enabled. Cannot register hotkeys.")
return
import omni.kit.hotkeys.core as hotkeys
hotkey_registry = hotkeys.get_hotkey_registry()
action_registry = get_action_registry()
ext_actions = action_registry.get_all_actions_for_extension(extension_id)
hotkey_filter = hotkeys.HotkeyFilter(windows=[window_name]) if window_name else None
hotkey_map = _DEFAULT_HOTKEY_MAP.copy()
# add UI hotkeys
if carb.settings.get_settings().get("exts/omni.kit.viewport.actions/ui_hotkeys"):
hotkey_map["toggle_ui"] = "F7"
# check if IAppWindowImplOs has already registered F11
if not carb.settings.get_settings().get("/exts/omni.appwindow/listenF11"):
hotkey_map["toggle_fullscreen"] = "F11"
if carb.settings.get_settings().get_as_bool( "/app/window/showDpiScaleMenu"):
hotkey_map["dpi_scale_increase"] = "EQUAL"
hotkey_map["dpi_scale_decrease"] = "MINUS"
for action in ext_actions:
key = hotkey_map.get(action.id, None)
# Not all Actions will have default hotkeys
if not key:
continue
hotkey_registry.register_hotkey(
hotkey_ext_id=extension_id,
key=key,
action_ext_id=action.extension_id,
action_id=action.id,
filter=hotkey_filter,
)
def deregister_hotkeys(extension_id: str):
ext_manager = omni.kit.app.get_app_interface().get_extension_manager()
if not ext_manager.is_extension_enabled(_HOTKEYS_EXT):
carb.log_info(f"{_HOTKEYS_EXT} is not enabled. No hotkeys to deregister.")
return
import omni.kit.hotkeys.core as hotkeys
hotkey_registry = hotkeys.get_hotkey_registry()
hotkey_registry.deregister_all_hotkeys_for_extension(extension_id)
| 2,546 | Python | 35.385714 | 88 | 0.661037 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/extension.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["ViewportActionsExtension", "get_instance"]
from .actions import register_actions, deregister_actions
from .hotkeys import register_hotkeys, deregister_hotkeys
import omni.ext
import omni.kit.app
from typing import Callable
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
class ViewportActionsExtension(omni.ext.IExt):
"""Actions and Hotkeys related to the Viewport"""
def __init__(self):
super().__init__()
self._ext_name = None
self._hotkey_extension_enabled_hook = None
self._hotkey_extension_disabled_hook = None
def on_startup(self, ext_id):
global _extension_instance
_extension_instance = self
self._ext_name = omni.ext.get_extension_name(ext_id)
# Hooks to hotkey extension enable/disable
app = omni.kit.app.get_app_interface()
ext_manager = app.get_extension_manager()
hooks: omni.ext.IExtensionManagerHooks = ext_manager.get_hooks()
self._hotkey_extension_enabled_hook = hooks.create_extension_state_change_hook(
self._on_hotkey_ext_changed,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE,
ext_name="omni.kit.hotkeys.core",
)
self._hotkey_extension_disabled_hook = hooks.create_extension_state_change_hook(
self._on_hotkey_ext_changed,
omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE,
ext_name="omni.kit.hotkeys.core",
)
register_actions(self._ext_name)
register_hotkeys(self._ext_name)
def on_shutdown(self):
global _extension_instance
_extension_instance = None
self._hotkey_extension_enabled_hook = None
self._hotkey_extension_disabled_hook = None
deregister_hotkeys(self._ext_name)
deregister_actions(self._ext_name)
self._ext_name = None
del ViewportActionsExtension.__g_usd_context_streams
def _on_hotkey_ext_changed(self, ext_id: str, ext_change_type: omni.ext.ExtensionStateChangeType):
if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_ENABLE:
register_hotkeys(self._ext_name)
if ext_change_type == omni.ext.ExtensionStateChangeType.AFTER_EXTENSION_DISABLE:
deregister_hotkeys(self._ext_name)
__g_usd_context_streams = None
@staticmethod
def _watch_stage_open(usd_context_name: str, open_callback: Callable):
if ViewportActionsExtension.__g_usd_context_streams is None:
ViewportActionsExtension.__g_usd_context_streams = {}
sub_id = ViewportActionsExtension.__g_usd_context_streams.get(usd_context_name, None)
if sub_id is not None:
return
import omni.usd
def on_stage_event(event):
if event.type == int(omni.usd.StageEventType.OPENED):
stage = omni.usd.get_context(usd_context_name).get_stage()
if stage:
open_callback(usd_context_name, stage)
ViewportActionsExtension.__g_usd_context_streams[usd_context_name] = (
omni.usd.get_context(usd_context_name).get_stage_event_stream().create_subscription_to_pop(
on_stage_event, name="omni.kit.viewport.actions.sticky_visibility"
)
)
| 3,792 | Python | 35.825242 | 103 | 0.671677 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/actions.py |
__all__ = ["register_actions", "deregister_actions"]
import omni.kit.actions.core
import omni.kit.viewport.utility
import carb
import omni.ui as ui
from pxr import Sdf, UsdGeom
from functools import partial
from typing import List, Optional, Sequence, Tuple
PERSP_CAM = "perspective_camera"
TOP_CAM = "top_camera"
FRONT_CAM = "front_camera"
RIGHT_CAM = "right_camera"
SHOW_ALL_PURPOSE = "toggle_show_by_purpose_all"
SHOW_GUIDE = "toggle_show_by_purpose_guide"
SHOW_PROXY = "toggle_show_by_purpose_proxy"
SHOW_RENDER = "toggle_show_by_purpose_render"
INERTIA_TOGGLE = "toggle_camera_inertia_enabled"
FILL_VIEWPORT_TOGGLE = "toggle_fill_viewport"
RENDERER_RTX_REALTIME = "set_renderer_rtx_realtime"
RENDERER_RTX_PT = "set_renderer_rtx_pathtracing"
RENDERER_RTX_TOGGLE = "toggle_rtx_rendermode"
RENDERER_IRAY = "set_renderer_iray"
RENDERER_PXR_STORM = "set_renderer_pxr_storm"
RENDERER_WIREFRAME = "toggle_wireframe"
PERSISTENT_SETTINGS_PREFIX = "/persistent"
INERTIA_ENABLE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/camInertiaEnabled"
FILL_VIEWPORT_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/fillViewport"
DISPLAY_GUIDE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/guide"
DISPLAY_PROXY_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/proxy"
DISPLAY_RENDER_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/hydra/displayPurpose/render"
SECTION_VISIBILE_SETTING = PERSISTENT_SETTINGS_PREFIX + "/app/viewport/{viewport_api_id}/{section}/visible"
SHADING_MODE_SETTING = "/exts/omni.kit.viewport.menubar.render/shadingMode"
SHOW_DPI_SCALE_MENU_SETTING = "/app/window/showDpiScaleMenu"
DPI_SCALE_OVERRIDE_SETTING = "/app/window/dpiScaleOverride"
DPI_SCALE_OVERRIDE_DEFAULT = -1.0
DPI_SCALE_OVERRIDE_MIN = 0.5
DPI_SCALE_OVERRIDE_MAX = 5.0
DPI_SCALE_OVERRIDE_STEP = 0.5
workspace_data = []
def register_actions(extension_id: str):
action_registry = omni.kit.actions.core.get_action_registry()
actions_tag = "Viewport Camera Menu Actions"
action_registry.register_action(
extension_id,
PERSP_CAM,
partial(set_camera, "/OmniverseKit_Persp"),
display_name="Perspective Camera",
description="Switch to Perspective Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
TOP_CAM,
partial(set_camera, "/OmniverseKit_Top"),
display_name="Top Camera",
description="Switch to Top Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
FRONT_CAM,
partial(set_camera, "/OmniverseKit_Front"),
display_name="Front Camera",
description="Switch to Front Camera",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RIGHT_CAM,
partial(set_camera, "/OmniverseKit_Right"),
display_name="Right Camera",
description="Switch to Right Camera",
tag=actions_tag,
)
actions_tag = "Viewport Display Menu Actions"
action_registry.register_action(
extension_id,
SHOW_ALL_PURPOSE,
partial(
toggle_category_settings,
DISPLAY_GUIDE_SETTING,
DISPLAY_PROXY_SETTING,
DISPLAY_RENDER_SETTING,
),
display_name="Toggle Show All Purpose",
description="Toggle Show By Purpose - All",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_GUIDE,
partial(_toggle_setting, DISPLAY_GUIDE_SETTING),
display_name="Toggle Show Guide Purpose",
description="Toggle Show By Purpose - Guide",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_PROXY,
partial(_toggle_setting, DISPLAY_PROXY_SETTING),
display_name="Toggle Show Proxy Purpose",
description="Toggle Show By Purpose - Proxy",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
SHOW_RENDER,
partial(_toggle_setting, DISPLAY_RENDER_SETTING),
display_name="Toggle Show Render Purpose",
description="Toggle Show By Purpose - Render",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_camera_visibility",
toggle_camera_visibility,
display_name="Toggle Show Cameras",
description="Toggle Show By Type - Cameras",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_light_visibility",
toggle_light_visibility,
display_name="Toggle Show Lights",
description="Toggle Show By Type - Lights",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_skeleton_visibility",
toggle_skeleton_visibility,
display_name="Toggle Show Skeletons",
description="Toggle Show By Type - Skeletons",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_audio_visibility",
toggle_audio_visibility,
display_name="Toggle Show Audio",
description="Toggle Show By Type - Audio",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_mesh_visibility",
toggle_mesh_visibility,
display_name="Toggle Show Meshes",
description="Toggle Show By Type - Meshes",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_show_by_type_visibility",
toggle_show_by_type_visibility,
display_name="Toggle Show By Type",
description="Toggle Show By Type - All Type Toggle",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_grid_visibility",
toggle_grid_visibility,
display_name="Toggle Grid",
description="Toggle drawing of grid",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_axis_visibility",
toggle_axis_visibility,
display_name="Toggle Camera Axis",
description="Toggle drawing of camera axis",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_selection_hilight_visibility",
toggle_selection_hilight_visibility,
display_name="Toggle Selection Outline",
description="Toggle drawing of selection hilight",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_global_visibility",
toggle_global_visibility,
display_name="Toggle Global Visibility",
description="Toggle drawing of grid, HUD, audio, light, camera, and skeleton gizmos",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_viewport_visibility",
toggle_viewport_visibility,
display_name="Toggle Viewport item visibility",
description="Toggle drawing of Viewport items by key.",
tag=actions_tag,
)
actions_tag = "Viewport Settings Menu Actions"
action_registry.register_action(
extension_id,
INERTIA_TOGGLE,
partial(_toggle_setting, INERTIA_ENABLE_SETTING),
display_name="Toggle Camera Inertia Enabled",
description="Toggle Camera Inertia Mode Enabled",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
FILL_VIEWPORT_TOGGLE,
partial(_toggle_setting, FILL_VIEWPORT_SETTING),
display_name="Toggle Fill Viewport",
description="Toggle Fill Viewport Setting",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_lock_navigation_height",
partial(_toggle_setting, "/persistent/exts/omni.kit.manipulator.camera/flyViewLock"),
display_name="Toggle Lock Navigation Height",
description="Toggle whether fly-mode forward/backward and up/down uses ore ignores the camera orientation.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"set_viewport_resolution",
set_viewport_resolution,
display_name="Set Viewport Resolution",
description="Set a Viewport's resolution with a tuple or named constant.",
tag=actions_tag,
)
carb.settings.get_settings().set_default_bool(SHOW_DPI_SCALE_MENU_SETTING, False)
action_registry.register_action(
extension_id,
"toggle_ui",
on_toggle_ui,
display_name="Toggle Viewport UI Overlay",
description="Toggle Viewport UI Overlay",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_fullscreen",
on_fullscreen,
display_name="Toggle Viewport Fullscreen",
description="Toggle Viewport Fullscreen",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_increase",
on_dpi_scale_increase,
display_name="DPI Scale Increase",
description="DPI Scale Increase",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_decrease",
on_dpi_scale_decrease,
display_name="DPI Scale Decrease",
description="DPI Scale Decrease",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"dpi_scale_reset",
on_dpi_scale_reset,
display_name="DPI Scale Reset",
description="DPI scale reset to default",
tag=actions_tag,
)
actions_tag = "Viewport Render Menu Actions"
# TODO: these should maybe register dynamically as renderers are loaded/unloaded?
settings = carb.settings.get_settings()
available_engines = (settings.get('/renderer/enabled') or '').split(',')
ignore_loaded_engined = True
if ignore_loaded_engined or ('rtx' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_RTX_REALTIME,
partial(set_renderer, "rtx", "RaytracedLighting"),
display_name="Set Renderer to RTX Realtime",
description="Set Renderer Engine to RTX Realtime",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_RTX_PT,
partial(set_renderer, "rtx", "PathTracing"),
display_name="Set Renderer to RTX Pathtracing",
description="Set Renderer Engine to RTX Pathtracing",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_RTX_TOGGLE,
toggle_rtx_rendermode,
display_name="Toggle RTX render-mode",
description="Toggle RTX render-mode between Realtime and Pathtracing",
tag=actions_tag,
)
if ignore_loaded_engined or ('iray' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_IRAY,
partial(set_renderer, "iray", "iray"),
display_name="Set Renderer to RTX Accurate (Iray)",
description="Set Renderer Engine to RTX Accurate (Iray)",
tag=actions_tag,
)
if ignore_loaded_engined or ('pxr' in available_engines):
action_registry.register_action(
extension_id,
RENDERER_PXR_STORM,
partial(set_renderer, "pxr", "HdStormRendererPlugin"),
display_name="Set Renderer to Pixar Storm",
description="Set Renderer Engine to Pixar Storm",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
RENDERER_WIREFRAME,
toggle_wireframe,
display_name="Toggle wireframe",
description="Toggle wireframe",
tag=actions_tag,
)
# HUD visibility actions
actions_tag = "Viewport HUD Visibility Actions"
action_registry.register_action(
extension_id,
"toggle_hud_fps_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderFPS"], action="toggle_hud_fps_visibility"),
display_name="Toggle Render FPS HUD visibility",
description="Toggle whether render fps item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_resolution_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderResolution"], action="toggle_hud_resolution_visibility"),
display_name="Toggle Render Resolution HUD visibility",
description="Toggle whether render resolution item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_progress_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/renderProgress"], action="toggle_hud_progress_visibility"),
display_name="Toggle Render Progress HUD visibility",
description="Toggle whether render progress item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_camera_speed_visibility",
partial(_toggle_viewport_visibility, visible=None, setting_keys=["hud/cameraSpeed"], action="toggle_hud_camera_speed_visibility"),
display_name="Toggle Camera Speed HUD visibility",
description="Toggle whether camera speed HUD item is visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_memory_visibility",
toggle_hud_memory_visibility,
display_name="Toggle Memory Item HUD visibility",
description="Toggle whether HUD memory items HUD are visible in HUD or not.",
tag=actions_tag,
)
action_registry.register_action(
extension_id,
"toggle_hud_visibility",
toggle_hud_visibility,
display_name="Toggle Gloabl HUD visiblity",
description="Toggle whether any HUD items are visible or not.",
tag=actions_tag,
)
def deregister_actions(extension_id):
action_registry = omni.kit.actions.core.get_action_registry()
if action_registry:
action_registry.deregister_all_actions_for_extension(extension_id)
def _get_viewport_argument(viewport_api, action: str):
if not viewport_api:
viewport_api = omni.kit.viewport.utility.get_active_viewport()
if not viewport_api:
carb.log_warn(f"There was no provided or active Viewport - not able to run viewport-specific action: {action}.")
return None
return viewport_api
def set_camera(camera_str: str, viewport_api=None) -> bool:
"""Switch the camera in the active viewport based on the camera path.
Args:
camera_str (str): Camera Path in string form. ie "/OmniverseKit_Persp"
viewport_api (viewport): Optional viewport in order to set the camera
in a specific viewport.
Returns:
bool: True if successful, False if not.
"""
viewport = _get_viewport_argument(viewport_api, "set_camera")
if not viewport:
return False
stage = viewport.stage
if not stage:
carb.log_warn("Viewport Stage does not exist, to switch cameras.")
return False
camera_path = Sdf.Path(camera_str)
prim = stage.GetPrimAtPath(camera_path)
if not prim:
carb.log_warn(f"Prim for camera path: {camera_path} does not exist in the stage.")
return False
if not UsdGeom.Camera(prim):
carb.log_warn(f"Camera: {camera_path} does not exist in the stage.")
return False
viewport.camera_path = camera_path
return True
def set_renderer(engine_name, render_mode, viewport_api=None) -> bool:
viewport = _get_viewport_argument(viewport_api, "set_renderer")
if not viewport:
return False
viewport.set_hd_engine(engine_name, render_mode)
return True
def toggle_rtx_rendermode(viewport_api=None) -> bool:
viewport = _get_viewport_argument(viewport_api, "toggle_rtx_rendermode")
if not viewport:
return False
# Toggle to PathTracing when already on RTX and using RaytracedLighting
if viewport.hydra_engine == "rtx" and viewport.render_mode == "RaytracedLighting":
render_mode = "PathTracing"
else:
render_mode = "RaytracedLighting"
viewport.set_hd_engine("rtx", render_mode)
return True
def toggle_wireframe() -> str:
settings = carb.settings.get_settings()
mode = settings.get(SHADING_MODE_SETTING)
if mode == "wireframe":
# Set to default
settings.set(SHADING_MODE_SETTING, "default")
settings.set("/rtx/wireframe/mode", 0)
return "default"
else:
# Set to wireframe
settings.set(SHADING_MODE_SETTING, "wireframe")
settings.set("/rtx/debugView/target", "")
flat_shade = settings.get("/rtx/debugMaterialType") == 0
wire_mode = 2 if flat_shade else 1
settings.set("/rtx/wireframe/mode", wire_mode)
return "wireframe"
def toggle_category_settings(*setting_names):
settings = carb.settings.get_settings()
vals = [settings.get(setting_name) for setting_name in setting_names]
value_for_all = False if all(vals) else True
for setting_name in setting_names:
settings.set(setting_name, value_for_all)
def _toggle_setting(setting_name: str, viewport_api: Optional["ViewportAPI"] = None, visible: bool | None = None):
viewport_api = _get_viewport_argument(viewport_api, "_toggle_setting")
if not viewport_api:
return
setting_path = setting_name.format(viewport_api_id=viewport_api.id)
settings = carb.settings.get_settings()
if visible is None:
visible = not bool(settings.get(setting_path))
settings.set(setting_path, visible)
return visible
_k_setting_to_prim_type = {
"scene/cameras": {"Camera"},
"scene/skeletons": {"Skeleton"},
"scene/audio": {"Sound", "Listener"},
"scene/meshes": {"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"},
# "scene/lights"
}
def _stage_opened(usd_context_name: str, stage):
if not stage:
return
settings = carb.settings.get_settings()
reset_on_open = settings.get("/exts/omni.kit.viewport.actions/resetVisibilityOnOpen")
def get_display_option_and_off(setting_key: str):
vis_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible"
return (vis_key, not bool(settings.get(vis_key)))
def is_display_option_off(setting_key: str):
return get_display_option_and_off(setting_key)[1]
types_to_hide = set()
for setting_key, prim_types in _k_setting_to_prim_type.items():
vis_key, is_off = get_display_option_and_off(setting_key)
if reset_on_open and setting_key in reset_on_open:
if is_off:
settings.set(vis_key, True)
elif is_off:
types_to_hide.update(prim_types)
if not types_to_hide:
return
from omni.kit.viewport.actions.visibility import VisibilityEdit
VisibilityEdit(stage, types_to_show=None, types_to_hide=types_to_hide).run()
def _get_visible(visible: bool | Sequence[bool], index: int):
"""Utility function to get visibilty as a bool or from a bool or a list with index"""
getitem = getattr(visible, "__getitem__", None)
if getitem:
return bool(getitem(index))
return bool(visible)
def _toggle_legacy_display_visibility(viewport_api,
visible: bool | Sequence[bool],
setting_keys: Sequence[str],
reduce_sequence: bool) -> List[str]:
persitent_to_legacy_map = {
"hud/renderFPS": (1 << 0, None),
"guide/axis": (1 << 1, None),
"hud/renderResolution": (1 << 3, None),
"scene/cameras": (1 << 5, "/app/viewport/show/camera"),
"guide/grid": (1 << 6, "/app/viewport/grid/enabled"),
"guide/selection": (1 << 7, "/app/viewport/outline/enabled"),
"scene/lights": (1 << 8, "/app/viewport/show/lights"),
"scene/skeletons": (1 << 9, None),
"scene/meshes": (1 << 10, None),
"hud/renderProgress": (1 << 11, None),
"scene/audio": (1 << 12, "/app/viewport/show/audio"),
"hud/deviceMemory": (1 << 13, None),
"hud/hostMemory": (1 << 14, None),
}
settings = carb.settings.get_settings()
display_options = settings.get("/persistent/app/viewport/displayOptions") or 0
empty_tuple = (None, None)
result = []
for i in range(len(setting_keys)):
section, new_visible = setting_keys[i], _get_visible(visible, i)
section_mask, section_key = persitent_to_legacy_map.get(section, empty_tuple)
if section_mask is None:
continue
was_visible = bool(display_options & section_mask)
if new_visible is None:
display_options ^= section_mask
# Make new_visible != was_visible comparison below correct for state transition
new_visible = bool(display_options & section_mask)
elif new_visible != was_visible:
if new_visible:
display_options |= section_mask
else:
display_options &= ~section_mask
if new_visible != was_visible:
result.append(section)
if section_key:
settings.set(section_key, new_visible)
settings.set("/persistent/app/viewport/displayOptions", display_options)
# Reduce the case of a single item sequence to the item or None if requested
if reduce_sequence:
result = result[0] if result else None
return result
def _toggle_viewport_visibility(viewport_api,
visible: bool | Sequence[bool] | None,
setting_keys: Sequence[str],
action: str,
reduce_sequence: bool = True) -> List[str] | str | None:
viewport_api = _get_viewport_argument(viewport_api, action)
if not viewport_api:
return []
if hasattr(viewport_api, 'legacy_window'):
return _toggle_legacy_display_visibility(viewport_api, visible, setting_keys, reduce_sequence)
settings = carb.settings.get_settings()
usd_context_name = viewport_api.usd_context_name
def get_visibility(setting_key: str) -> Tuple[bool, str]:
# Currently settings in "scene" correspond to a state change in the Usd stage
if setting_key.startswith("scene"):
setting_key = f"/app/viewport/usdcontext-{usd_context_name}/{setting_key}/visible"
else:
setting_key = f"/persistent/app/viewport/{viewport_api.id}/{setting_key}/visible"
return bool(settings.get(setting_key)), setting_key
if visible is None:
# No explicit visiblity given, figure out what things to flip
all_visible, any_visible = True, False
for setting_key in setting_keys:
# Get the current visibility
cur_visibility, _ = get_visibility(setting_key)
# If this any item is not visible, then the toggle is a transition to all items visible; early exit
if not cur_visibility:
all_visible = False
else:
any_visible = True
# Transition to hidden if all were visible, otherwise transition to visible
# All were visible => Nothing visible
# Nothing was visible => All visible
# Anything was visible => All visible
if any_visible and not all_visible:
visible = True
else:
visible = not all_visible
stage = viewport_api.stage
types_to_show, types_to_hide = set(), set()
# Apply any visibility UsdAttribute changes to the types requested
setting_to_prim_types = _k_setting_to_prim_type if stage else {}
result = []
# Find all the objects that need to be toggled
for i in range(len(setting_keys)):
setting_key, new_visible = setting_keys[i], _get_visible(visible, i)
cur_visibility, pref_key = get_visibility(setting_key)
cur_visibility = bool(cur_visibility)
if cur_visibility != new_visible:
settings.set(pref_key, new_visible)
prim_types = setting_to_prim_types.get(setting_key)
if prim_types:
if new_visible:
types_to_show.update(prim_types)
else:
types_to_hide.update(prim_types)
elif setting_key == "guide/selection":
# Still need to special case this to forward correctly (its global)
settings.set("/app/viewport/outline/enabled", new_visible)
# If visibility was toggled, add to the key to the return value
if new_visible != cur_visibility:
result.append(setting_key)
# Apply any visibility UsdAttribute changes to the types requested
if types_to_show or types_to_hide:
from .visibility import VisibilityEdit
VisibilityEdit(stage, types_to_show=types_to_show, types_to_hide=types_to_hide).run()
# The action is a toggle of state that is sticky across new stage's, so need to apply state to any new stage
from omni.kit.viewport.actions.extension import get_instance
get_instance()._watch_stage_open(usd_context_name, _stage_opened)
# Reduce the case of a single item sequence to the item or None if requested
if reduce_sequence:
result = result[0] if result else None
return result
def toggle_grid_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/grid"], "toggle_grid_visibility")
def toggle_axis_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/axis"], "toggle_axis_visibility")
def toggle_selection_hilight_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["guide/selection"], "toggle_selection_hilight_visibility")
def toggle_camera_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/cameras"], "toggle_camera_visibility")
def toggle_light_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/lights"], "toggle_light_visibility")
def toggle_skeleton_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/skeletons"], "toggle_skeleton_visibility")
def toggle_audio_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/audio"], "toggle_audio_visibility")
def toggle_mesh_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> str | None:
return _toggle_viewport_visibility(viewport_api, visible, ["scene/meshes"], "toggle_mesh_visibility")
def toggle_show_by_type_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
return _toggle_viewport_visibility(viewport_api, visible,
["scene/cameras", "scene/lights", "scene/skeletons", "scene/audio"],
"toggle_show_by_type_visibility", False)
def _get_toggle_types(settings, setting_path: str) -> List[str]:
toggle_types = settings.get(setting_path)
if toggle_types is None:
return []
if isinstance(toggle_types, str):
return toggle_types.split(",")
return toggle_types
def toggle_global_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
viewport_api = _get_viewport_argument(viewport_api, "toggle_global_visibility")
if viewport_api and hasattr(viewport_api, "legacy_window"):
viewport_api.legacy_window.toggle_global_visibility_settings()
return []
# Get the list of what to hide (defaulting to what legacy Viewport and toggle_global_visibility_settings did)
settings = carb.settings.get_settings()
toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/globalTypes")
toggle_types += _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes")
return _toggle_viewport_visibility(viewport_api, visible, toggle_types, "toggle_global_visibility", False)
def toggle_viewport_visibility(keys: Sequence[str], viewport_api=None, visible: bool | Sequence[bool] | None = None) -> List[str]:
return _toggle_viewport_visibility(viewport_api, visible, keys, "toggle_viewport_visibility", False)
def toggle_hud_memory_visibility(viewport_api=None, visible: bool | Sequence[bool] | None = None, host: bool = True, device: bool = True) -> str | None:
items = []
if host:
items.append("hud/hostMemory")
if device:
items.append("hud/deviceMemory")
if items:
return _toggle_viewport_visibility(viewport_api, visible, items, "toggle_hud_memory_visibility")
return []
def toggle_hud_visibility(viewport_api=None, visible: bool | None = None, use_setting: bool = False):
viewport = _get_viewport_argument(viewport_api, "toggle_hud_visibility")
if not viewport:
return
# as_menu works around a defect in Viewport-menu modeling of settings, where top-level item will enable
# or disable all child items only in the first grouping, but toggle_hud_visibility action should really mean
# all HUD items, (the ui-layer that contains any "hud/children" items).
if use_setting:
settings = carb.settings.get_settings()
toggle_types = _get_toggle_types(settings, "/exts/omni.kit.viewport.actions/visibilityToggle/hudTypes")
toggled = _toggle_viewport_visibility(viewport, visible, toggle_types, "toggle_hud_visibility", reduce_sequence=False)
any_vis = bool(visible)
if not any_vis:
for key in toggle_types:
any_vis = settings.get(f"/persistent/app/viewport/{viewport.id}/{key}/visible")
if any_vis:
break
# If any of the children are now visible, make sure the top-level parent is also visible
if any_vis:
_toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport, visible=True)
return toggled
return _toggle_setting("/persistent/app/viewport/{viewport_api_id}/hud/visible", viewport)
def set_viewport_resolution(resolution, viewport_api=None):
viewport_api = _get_viewport_argument(viewport_api, "set_viewport_resolution")
if not viewport_api:
return
# Accept resolution as a named constant (str) as well as a tuple
if isinstance(resolution, str):
resolution_tuple = NAME_RESOLUTIONS = {
"Icon": (512, 512),
"Square": (1024, 1024),
"SD": (1280, 960),
"HD720P": (1280, 720),
"HD1080P": (1920, 1080),
"2K": (2048, 1080),
"1440P": (2560, 1440),
"UHD": (3840, 2160),
"Ultra Wide": (3440, 1440),
"Super Ultra Wide": (3840, 1440),
"5K Wide": (5120, 2880),
}.get(resolution)
if resolution_tuple is None:
carb.log_error("Resolution named {resolution} is not known.")
return
resolution = resolution_tuple
viewport_api.resolution = resolution
def set_ui_hidden(hide):
global workspace_data
if hide:
# hide context_menu
try:
omni.kit.context_menu.close_menu()
except:
pass
# windows are going to be hidden. Save workspace 1st
workspace_data = ui.Workspace.dump_workspace()
carb.settings.get_settings().set("/app/window/hideUi", hide)
else:
carb.settings.get_settings().set("/app/window/hideUi", hide)
# windows are going to be restored from hidden. Re-load workspace
# ui.Workspace.restore_workspace is async so it don't need to
# wait for initial unhide of the window here
ui.Workspace.restore_workspace(workspace_data, False)
workspace_data = []
def is_ui_hidden():
return carb.settings.get_settings().get("/app/window/hideUi")
def on_toggle_ui():
set_ui_hidden(not is_ui_hidden())
def on_fullscreen():
display_mode_lock = carb.settings.get_settings().get(f"/app/window/displayModeLock")
if display_mode_lock:
# Always stay in fullscreen_mode, only hide or show UI.
set_ui_hidden(not is_ui_hidden())
else:
# Only toggle fullscreen on/off when not display_mode_lock
was_fullscreen = omni.appwindow.get_default_app_window().is_fullscreen()
omni.appwindow.get_default_app_window().set_fullscreen(not was_fullscreen)
# Always hide UI in fullscreen
set_ui_hidden(not was_fullscreen)
def step_and_clamp_dpi_scale_override(increase):
import omni.ui as ui
# Get the current value.
dpi_scale = carb.settings.get_settings().get_as_float(DPI_SCALE_OVERRIDE_SETTING)
if dpi_scale == DPI_SCALE_OVERRIDE_DEFAULT:
dpi_scale = ui.Workspace.get_dpi_scale()
# Increase or decrease the current value by the setp value.
if increase:
dpi_scale += DPI_SCALE_OVERRIDE_STEP
else:
dpi_scale -= DPI_SCALE_OVERRIDE_STEP
# Clamp the new value between the min/max values.
dpi_scale = max(min(dpi_scale, DPI_SCALE_OVERRIDE_MAX), DPI_SCALE_OVERRIDE_MIN)
# Set the new value.
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, dpi_scale)
def on_dpi_scale_increase():
step_and_clamp_dpi_scale_override(True)
def on_dpi_scale_decrease():
step_and_clamp_dpi_scale_override(False)
def on_dpi_scale_reset():
carb.settings.get_settings().set(DPI_SCALE_OVERRIDE_SETTING, DPI_SCALE_OVERRIDE_DEFAULT)
| 34,697 | Python | 35.71746 | 152 | 0.64484 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/visibility.py | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
__all__ = ["VisibilityEdit"]
import carb
import omni.usd
from pxr import Usd, UsdGeom, Sdf
from typing import Callable, Optional, Sequence
def _get_usd_rt_stage(stage: Usd.Stage):
try:
from pxr import UsdUtils
from usdrt import Usd as UsdRtUsd
stage_id = UsdUtils.StageCache.Get().GetId(stage).ToLongInt()
fabric_active_for_stage = UsdRtUsd.Stage.StageWithHistoryExists(stage_id)
if fabric_active_for_stage:
return UsdRtUsd.Stage.Attach(stage_id)
except (ImportError, ModuleNotFoundError):
pass
return None
class VisibilityEdit:
def __init__(self, stage, types_to_show: Optional[Sequence[str]] = None, types_to_hide: Optional[Sequence[str]] = None):
# Sdf.Path.FindLongestPrefix require Sdf.PathVector (i.e. list) so we cannot use a dict
self.__path_to_change = {}
self.__stage = stage
self.__types_to_show = types_to_show
self.__types_to_hide = types_to_hide
self.__ignore_hidden_in_stage = carb.settings.get_settings().get("/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden")
def run(self):
if self.__gather_prims():
self.__hide_prims()
@carb.profiler.profile
def __get_prim_iterator(self, predicate):
# Early exit for request to do nothing
if not bool(self.__types_to_show) and not bool(self.__types_to_hide):
return
# Local function to filter Usd.Prim, returns None to ignore it or the Usd.Prim otherwise
def filter_prim(prim: Usd.Prim):
if self.__ignore_hidden_in_stage and omni.usd.editor.is_hide_in_stage_window(prim):
return None
return prim
# If UsdRt is available, use it to pre-prune the traversal to only given types
rt_stage = _get_usd_rt_stage(self.__stage)
if rt_stage:
# Merge all the prim-types of interest into one set for querying
if self.__types_to_show:
prim_types = set(self.__types_to_show)
if self.__types_to_hide:
prim_types = prim_types.union(set(self.__types_to_hide))
else:
prim_types = set(self.__types_to_hide)
for prim_type in prim_types:
for prim_path in rt_stage.GetPrimsWithTypeName(prim_type):
prim = filter_prim(self.__stage.GetPrimAtPath(prim_path.GetString()))
if prim:
yield prim
return
iterator = iter(self.__stage.Traverse(predicate))
for prim in iterator:
# Prune anything that is hide_in_stage_window
# Not sure why, but this matches legacy behavior
if filter_prim(prim) is None:
iterator.PruneChildren()
continue
yield prim
@property
def predicate(self):
return Usd.TraverseInstanceProxies(Usd.PrimDefaultPredicate)
def __get_visibility(self, prim: Usd.Prim, prim_path: Sdf.Path):
type_name = prim.GetTypeName()
make_visible = type_name in self.__types_to_show if self.__types_to_show else False
make_invisible = type_name in self.__types_to_hide if self.__types_to_hide else False
return (make_visible, make_invisible)
@carb.profiler.profile
def __gather_prims(self):
path_to_change = {}
# Traverse the satge, gathering the prims that have requested a visibility change
# This is a two-phase process to allow hiding leaves of instances by hiding the
# top-most un-instanced parent whose leaves are all of a hideable type
for prim in self.__get_prim_iterator(self.predicate):
prim_path = prim.GetPath()
make_visible, make_invisible = self.__get_visibility(prim, prim_path)
# If not making this type visible or invisible, then nothing to do
if (make_visible is False) and (make_invisible is False):
continue
if prim.IsInstanceProxy():
is_child = False
for path in path_to_change.keys():
if path.GetCommonPrefix(prim_path) == path:
is_child = True
break
if is_child:
continue
parent = prim.GetParent()
while parent and not parent.IsInstance():
parent = parent.GetParent()
# Insert the parent now and validate all children in the second phase
if parent:
path_to_change[parent.GetPath()] = True
else:
path_to_change[prim_path] = False
self.__path_to_change = path_to_change
return len(self.__path_to_change) != 0
@carb.profiler.profile
def __hide_prims(self):
# Traverse the instanced prims, making sure that all children are of the proper type
# or an allowed 'intermediate' type of Xform or Scope.
# If all children pass that test, then the instance can safely be hidden, otherwise
# it contains children that are not being requested as hidden, so the instance is left alone.
predicate = self.predicate
# UsdGeom.Imageabales that are acceptable intermediate children
allowed_imageables = set(("Xform", "Scope"))
# Setup the edit-context once, and batch all changes
session_layer = self.__stage.GetSessionLayer()
with Usd.EditContext(self.__stage, session_layer):
with Sdf.ChangeBlock():
for prim_path, is_instance in self.__path_to_change.items():
prim = self.__stage.GetPrimAtPath(prim_path)
if not prim:
continue
if prim.IsInstanceProxy():
carb.log_error(f"Unexpected instance in list of prims to toggle visibility: {prim.GetPath()}")
continue
# Assume success
toggle_error = None
visible = None
# If its an instance, traverse all children and make sure that
# they are of the right type, not a UsdImageable, or an allowed intermediate.
if is_instance:
for child_prim in prim.GetFilteredChildren(predicate):
child_type = child_prim.GetTypeName()
child_show, child_hide = self.__get_visibility(child_prim, child_prim.GetPath())
if (not child_show) and (not child_hide):
# If child is in neither list, than it must be an allowed intermediate type (or not an Imagaeable)
if (not UsdGeom.Imageable(child_prim)) or (child_type in allowed_imageables):
continue
toggle_error = "it contains at least one child with a type not being requested to hide."
break
# First loop iteration, set visible to proper state
if visible is None:
visible = child_show
if child_show != visible:
toggle_error = "its hiearchy is too heterogeneous for this action."
break
else:
visible = prim.GetTypeName() in self.__types_to_show if self.__types_to_show else False
if toggle_error:
visible_verb = 'show' if visible else 'hide'
carb.log_warn(f"Will not {visible_verb} '{prim_path}', {toggle_error}")
continue
if visible:
# as the session layer overrides all other layers, remove the primSpec
prim_spec = session_layer.GetPrimAtPath(prim_path)
property = session_layer.GetPropertyAtPath(prim_path.AppendProperty(UsdGeom.Tokens.visibility)) if prim_spec else None
if property:
prim_spec.RemoveProperty(property)
else:
imageable = UsdGeom.Imageable(prim)
if imageable:
imageable.GetVisibilityAttr().Set(UsdGeom.Tokens.invisible)
| 8,950 | Python | 45.139175 | 148 | 0.574078 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_actions.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestActionsAndHotkeys']
import omni.kit.actions.core
from omni.kit.test import AsyncTestCase
from ..actions import is_ui_hidden, set_camera
class TestActionsAndHotkeys(AsyncTestCase):
async def setUp(self):
self.extension_id = "omni.kit.viewport.actions"
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
async def test_find_registered_action(self):
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action(self.extension_id, "perspective_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "top_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "front_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "right_camera")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_rtx_rendermode")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "set_viewport_resolution")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_camera_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_light_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_grid_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_axis_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_selection_hilight_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_global_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_fps_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_resolution_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_progress_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_camera_speed_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_memory_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_hud_visibility")
self.assertIsNotNone(action)
action = action_registry.get_action(self.extension_id, "toggle_wireframe")
self.assertIsNotNone(action)
async def test_action_return_values(self):
"""Test the return valus for actions match expected cases."""
await omni.usd.get_context().new_stage_async()
action_registry = omni.kit.actions.core.get_action_registry()
test_keys = ["scene/lights", "guide/grid", "guide/axis"]
try:
action = action_registry.get_action(self.extension_id, "toggle_camera_visibility")
self.assertIsNotNone(action)
# First toggle, should return key as camera's are visible by default
result = action.execute()
self.assertEqual(result, "scene/cameras")
# Re-run making invisible again, should do nothing as nothing was toggled
result = action.execute(visible=False)
self.assertEqual(result, None)
# Re-run making visible again, should return the type that was toggled
result = action.execute(visible=True)
self.assertEqual(result, "scene/cameras")
action = action_registry.get_action(self.extension_id, "toggle_viewport_visibility")
self.assertIsNotNone(action)
result = action.execute(keys=test_keys)
self.assertEqual(result, test_keys)
# Re-run making invisible again, should do nothing as nothing was toggled
result = action.execute(keys=test_keys, visible=False)
self.assertEqual(result, [])
# Re-run making visible again, should return the type that was toggled
sub_keys = [test_keys[0], test_keys[2]]
result = action.execute(keys=sub_keys, visible=True)
self.assertEqual(result, sub_keys)
# Test API to pass sequence of visibility bools (should return nothing as [0] and [2] are vis, and [1] is invis)
result = action.execute(keys=test_keys, visible=[True, False, True])
self.assertEqual(result, [])
# Test API to pass sequence of visibility bools (should return type of [1] as it is toggling to visible
result = action.execute(keys=test_keys, visible=[True, True, True])
self.assertEqual(result, [test_keys[1]])
action = action_registry.get_action(self.extension_id, "toggle_wireframe")
self.assertIsNotNone(action)
# First toggle, should change from "default" to "wireframe"
result = action.execute()
self.assertEqual(result, "wireframe")
# Re-run, should change fron "wireframe" to "default"
result = action.execute()
self.assertEqual(result, "default")
action = action_registry.get_action(self.extension_id, "top_camera")
self.assertIsNotNone(action)
result = action.execute()
self.assertTrue(result)
action = action_registry.get_action(self.extension_id, "front_camera")
self.assertIsNotNone(action)
result = action.execute()
self.assertTrue(result)
result = set_camera("/randomCamera") # Test for a camera that doesn't exist
self.assertFalse(result)
finally:
# Return everything to known startup state
action_registry.get_action(self.extension_id, "toggle_camera_visibility").execute(visible=True)
action_registry.get_action(self.extension_id, "toggle_viewport_visibility").execute(keys=test_keys, visible=True)
action_registry.get_action(self.extension_id, "perspective_camera").execute()
async def test_hud_action_overrides_parent_visibility(self):
"""Test that toggling any HUD item to visible will force the parent to visible"""
from omni.kit.viewport.utility import get_active_viewport_window
import carb.settings
try:
vp_window = get_active_viewport_window()
self.assertIsNotNone(vp_window)
self.assertIsNotNone(vp_window.viewport_api)
settings = carb.settings.get_settings()
hud_vis_path = f"/persistent/app/viewport/{vp_window.viewport_api.id}/hud/visible"
settings.set(hud_vis_path, False)
await self.wait_n_updates()
self.assertFalse(settings.get(hud_vis_path))
action_registry = omni.kit.actions.core.get_action_registry()
action = action_registry.get_action(self.extension_id, "toggle_hud_visibility")
self.assertIsNotNone(action)
action.execute(visible=True, use_setting=True)
# Should have forced the parent item back to True
await self.wait_n_updates()
self.assertTrue(settings.get(hud_vis_path))
finally:
pass
async def test_ui_toggling(self):
"""Test that ui toggles visibility and fullscreen correctly"""
await omni.usd.get_context().new_stage_async()
action_registry = omni.kit.actions.core.get_action_registry()
# Make sure it's not hidden to start with
self.assertFalse(is_ui_hidden())
action = action_registry.get_action(self.extension_id, "toggle_ui")
self.assertIsNotNone(action)
result = action.execute()
# Make sure it was hidden when toggled
self.assertTrue(is_ui_hidden())
result = action.execute()
# Make sure it is unhidden again after toggling again
self.assertFalse(is_ui_hidden())
action = action_registry.get_action(self.extension_id, "toggle_fullscreen")
self.assertIsNotNone(action)
await self.wait_n_updates(10)
# Make sure we're not fullscreen already
self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen())
result = action.execute()
await self.wait_n_updates(10)
# Make sure we are in fullscreen now
self.assertTrue(omni.appwindow.get_default_app_window().is_fullscreen())
result = action.execute()
await self.wait_n_updates(10)
# Make sure we are back out of fullscreen
self.assertFalse(omni.appwindow.get_default_app_window().is_fullscreen())
| 9,685 | Python | 41.858407 | 125 | 0.661951 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/__init__.py | from .test_actions import *
from .test_visibility import *
from .test_extension import *
| 89 | Python | 21.499995 | 30 | 0.764045 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_extension.py | ## Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
__all__ = ['TestExtension']
import omni.kit.actions.core
from omni.kit.test import AsyncTestCase
class TestExtension(AsyncTestCase):
async def setUp(self):
self.extension_id = "omni.kit.viewport.actions"
async def wait_n_updates(self, n_frames: int = 3):
app = omni.kit.app.get_app()
for _ in range(n_frames):
await app.next_update_async()
async def test_extension_start_stop(self):
manager = omni.kit.app.get_app().get_extension_manager()
ext_id = self.extension_id
self.assertTrue(ext_id)
self.assertTrue(manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, False)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(not manager.is_extension_enabled(ext_id))
manager.set_extension_enabled(ext_id, True)
for _ in range(10):
await omni.kit.app.get_app().next_update_async()
self.assertTrue(manager.is_extension_enabled(ext_id))
| 1,480 | Python | 36.024999 | 77 | 0.686486 |
omniverse-code/kit/exts/omni.kit.viewport.actions/omni/kit/viewport/actions/tests/test_visibility.py | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this software and related documentation without an express
# license agreement from NVIDIA CORPORATION is strictly prohibited.
#
from omni.kit.viewport.actions.visibility import VisibilityEdit
import carb
import omni.kit.app
import omni.kit.test
import omni.timeline
from pxr import Sdf, Usd, UsdGeom
from functools import partial
from pathlib import Path
TEST_DATA_PATH = Path(
omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__)
).resolve().absolute().joinpath("data", "tests")
USD_TEST_DATA_PATH = TEST_DATA_PATH.joinpath("usd")
class TestVisibilitySetting(omni.kit.test.AsyncTestCase):
async def setUp(self):
super().setUp()
self.usd_context = omni.usd.get_context()
await self.usd_context.new_stage_async()
# After running each test
async def tearDown(self):
super().tearDown()
@staticmethod
def __is_in_set(prim_set: set, prim: Usd.Prim, prim_path: Sdf.Path) -> bool: # pragma: no cover
return prim.GetTypeName() in prim_set
@staticmethod
def __make_callback(prim_set: set):
return prim_set
async def test_hide_show_skeletons(self):
usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_skel_test = self.__make_callback({"SkelRoot"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_skel_test)
vis_edit.run()
# Skeleton should still be set to invisible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
# Everything else should be have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
vis_edit = VisibilityEdit(stage, types_to_show=is_skel_test, types_to_hide=None)
vis_edit.run()
# Skeleton should still be restored to inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
async def test_hide_show_meshes(self):
usd_path = USD_TEST_DATA_PATH.joinpath("visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh)
vis_edit.run()
# Skeleton should still be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Points should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should be off or inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "invisible")
vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None)
vis_edit.run()
# Skeleton should still be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/SkelRoot")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Points should have kept inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Points")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
# Everything else should be restored to inherited
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Mesh")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cone")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Cylinder")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Sphere")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Capsule")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_03/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshInstances_04/Cube")).ComputeVisibility()
self.assertEqual(str(visibility), "inherited")
async def test_hide_show_meshes_instanceable_references(self):
usd_path = USD_TEST_DATA_PATH.joinpath("referenced", "scene.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
is_in_mesh = self.__make_callback({"Mesh", "Cone", "Cube", "Cylinder", "Sphere", "Capsule"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_in_mesh)
vis_edit.run()
visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
self.assertEqual(str(visibility_a), 'invisible')
self.assertEqual(str(visibility_b), 'invisible')
vis_edit = VisibilityEdit(stage, types_to_show=is_in_mesh, types_to_hide=None)
vis_edit.run()
visibility_a = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_0/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
visibility_b = UsdGeom.Imageable(stage.GetPrimAtPath("/World/envs/env_1/bolt0/M20_Bolt_Tight_Visual")).ComputeVisibility()
self.assertEqual(str(visibility_a), 'inherited')
self.assertEqual(str(visibility_b), 'inherited')
async def __test_hide_show_hide_camera_at_time(self):
usd_path = USD_TEST_DATA_PATH.joinpath("cam_visibility.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
# Default should be visible
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
# Hide cameras
is_camera = self.__make_callback({"Camera"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=is_camera)
vis_edit.run()
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'invisible')
# Show cameras
vis_edit = VisibilityEdit(stage, types_to_show=is_camera, types_to_hide=None)
vis_edit.run()
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Frontal_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Focal_Headlight_50mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera_Establishing_28mm")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/Camera")).ComputeVisibility()
self.assertEqual(str(visibility), 'inherited')
async def test_hide_show_hide_camera(self):
'''Test show and hide of camera works at default time'''
await self.__test_hide_show_hide_camera_at_time()
async def test_hide_show_hide_camera_at_time(self):
'''Test show and hide of camera works at user time'''
try:
omni.timeline.get_timeline_interface().set_current_time(100)
await self.__test_hide_show_hide_camera_at_time()
finally:
omni.timeline.get_timeline_interface().set_current_time(0)
@omni.kit.test.omni_test_registry(guid="1e1fa926-ddf8-11ed-995d-ac91a108fede")
async def test_camera_visibility_stage_window_hidden(self):
'''Test show and hide of prims that accounts for objects hidden in stage window'''
usd_path = USD_TEST_DATA_PATH.joinpath("stage_window_hidden.usda")
success, error = await self.usd_context.open_stage_async(str(usd_path))
self.assertTrue(success, error)
stage = self.usd_context.get_stage()
# Default should be visible
def test_visibility(expected):
if isinstance(expected, str):
expected = [expected] * 4
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraA")).ComputeVisibility()
self.assertEqual(str(visibility), expected[0])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/CameraB")).ComputeVisibility()
self.assertEqual(str(visibility), expected[1])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshA")).ComputeVisibility()
self.assertEqual(str(visibility), expected[2])
visibility = UsdGeom.Imageable(stage.GetPrimAtPath("/World/MeshB")).ComputeVisibility()
self.assertEqual(str(visibility), expected[3])
test_visibility('inherited')
# Hide all camera and mesh
prim_test = self.__make_callback({"Camera", "Mesh"})
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test)
vis_edit.run()
test_visibility('invisible')
# Revert back and re-test
vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None)
vis_edit.run()
test_visibility('inherited')
settings = carb.settings.get_settings()
igswh = settings.get('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden')
try:
settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', True)
vis_edit = VisibilityEdit(stage, types_to_show=None, types_to_hide=prim_test)
vis_edit.run()
test_visibility(['invisible', 'inherited', 'invisible', 'inherited'])
# Revert back and re-test
vis_edit = VisibilityEdit(stage, types_to_show=prim_test, types_to_hide=None)
vis_edit.run()
test_visibility('inherited')
finally:
settings.set('/exts/omni.kit.viewport.actions/visibilityToggle/ignoreStageWindowHidden', igswh)
| 17,167 | Python | 46.821727 | 130 | 0.694472 |
omniverse-code/kit/exts/omni.kit.viewport.actions/docs/index.rst | omni.kit.viewport.actions
#################################
Viewport Actions and Hotkeys
.. toctree::
:maxdepth: 1
CHANGELOG
.. automodule:: omni.kit.viewport.actions
:platform: Windows-x86_64, Linux-x86_64
:members:
:undoc-members:
:show-inheritance:
:imported-members:
| 303 | reStructuredText | 14.999999 | 43 | 0.60396 |
omniverse-code/kit/exts/omni.assets/omni/assets/yeller.py | import carb
import omni.ext
class AssetsYellerExtension(omni.ext.IExt):
def on_startup(self, ext_id):
carb.log_warn('omni.assets extension is deprecated! Please replace your dependency omni.assets -> omni.assets.plugins in extension.toml!')
def on_shutdown(self):
pass
| 296 | Python | 25.999998 | 146 | 0.719595 |
omniverse-code/kit/exts/omni.kit.window.material_swap/PACKAGE-LICENSES/omni.kit.window.material_swap-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.material_swap/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.3"
category = "Internal"
# 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 = "Material Swap"
description="Replaces bound materials"
# URL of the extension source repository.
repository = ""
# Keywords for the extension
keywords = ["kit", "usd", "material"]
# Location of change log file in target (final) folder of extension, relative to the root.
# More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog = "docs/CHANGELOG.md"
[dependencies]
"omni.usd" = {}
"omni.ui" = {}
"omni.kit.window.filepicker" = {}
[[python.module]]
name = "omni.kit.window.material_swap"
| 815 | TOML | 25.32258 | 90 | 0.72638 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/__init__.py | from .scripts import *
| 23 | Python | 10.999995 | 22 | 0.73913 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/__init__.py | from .material_swap import *
| 29 | Python | 13.999993 | 28 | 0.758621 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/scripts/material_swap.py | import os
import carb
import weakref
import omni.ext
import omni.kit.ui
import omni.usd
from typing import Callable
from pathlib import Path
from pxr import Usd, UsdGeom, Sdf, UsdShade
from omni.kit.window.filepicker import FilePickerDialog
from omni.kit.widget.filebrowser import FileBrowserItem
TEST_DATA_PATH = ""
_extension_instance = None
class MaterialSwapExtension(omni.ext.IExt):
def on_startup(self, ext_id):
self._usd_context = omni.usd.get_context()
self._selection = self._usd_context.get_selection()
self._build_ui()
manager = omni.kit.app.get_app().get_extension_manager()
extension_path = manager.get_extension_path(ext_id)
global TEST_DATA_PATH
TEST_DATA_PATH = Path(extension_path).joinpath("data").joinpath("tests")
global _extension_instance
_extension_instance = self
def _build_ui(self):
self._window = omni.kit.ui.Window("Material Swap", 300, 200, menu_path="Window/Material Swap")
mat_settings = omni.kit.ui.CollapsingFrame("Material Swap Parameters", True)
field_width = 120
self._default_material_name = "None Selected"
self._old_mat = omni.kit.ui.TextBox(self._default_material_name)
self._old_mat_label = omni.kit.ui.Label("Material to Replace")
self._old_mat_selected = omni.kit.ui.Button("Use Selected")
self._old_mat_selected.set_clicked_fn(self._get_selectedold_fn)
self._old_mat.width = field_width * 3
self._old_mat_label.width = field_width
self._old_mat_selected.width = field_width
old_row = omni.kit.ui.RowLayout()
old_row.add_child(self._old_mat_label)
old_row.add_child(self._old_mat)
old_row.add_child(self._old_mat_selected)
self._new_mat = omni.kit.ui.TextBox(self._default_material_name)
self._new_mat_label = omni.kit.ui.Label("Material to Use")
self._new_mat_browse = omni.kit.ui.Button("Browse")
self._new_mat_browse.set_clicked_fn(self._on_browse_fn)
self._new_mat_selected = omni.kit.ui.Button("Use Selected")
self._new_mat_selected.set_clicked_fn(self._get_selectednew_fn)
def on_filter_item(dialog: FilePickerDialog, item: FileBrowserItem) -> bool:
if item and not item.is_folder and dialog.current_filter_option == 0:
_, ext = os.path.splitext(item.path)
return ext in [".mdl"]
return True
# create filepicker
dialog = FilePickerDialog(
"Open File",
apply_button_label="Open",
click_apply_handler=lambda filename, dirname, o=weakref.ref(self): MaterialSwapExtension._on_file_open(o, dialog, filename, dirname),
item_filter_options=["MDL Files (*.mdl)", "All Files (*)"],
item_filter_fn=lambda item: on_filter_item(dialog, item),
)
dialog.hide()
self._new_mat_fp = dialog
self._new_mat.width = field_width * 3
self._new_mat_label.width = field_width
self._new_mat_browse.width = field_width
self._new_mat_selected.width = field_width
new_row = omni.kit.ui.RowLayout()
new_row.add_child(self._new_mat_label)
new_row.add_child(self._new_mat)
new_row.add_child(self._new_mat_selected)
new_row.add_child(self._new_mat_browse)
mat_settings.add_child(old_row)
mat_settings.add_child(new_row)
# buttons
actions = omni.kit.ui.CollapsingFrame("Actions", True)
self._ui_swap_button = omni.kit.ui.Button("Swap")
self._ui_swap_button.set_clicked_fn(self._on_swap_fn)
self._ui_swap_button.width = omni.kit.ui.Percent(30)
actions.add_child(self._ui_swap_button)
self._window.layout.add_child(mat_settings)
self._window.layout.add_child(actions)
def _on_swap_fn(self, widget):
if self._old_mat.value == self._default_material_name:
carb.log_error('"Material To Replace" not set')
return
if self._new_mat.value == self._default_material_name:
carb.log_error('"Material to Use" not set')
return
stage = self._usd_context.get_stage()
for prim in stage.Traverse():
if not prim.GetMetadata("hide_in_stage_window") and omni.usd.is_prim_material_supported(prim):
mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
mat_path = mat.GetPath()
if mat_path == self._old_mat.value:
path = prim.GetPath()
omni.kit.commands.execute(
"BindMaterial",
prim_path=path,
material_path=self._new_mat.value,
strength=UsdShade.Tokens.weakerThanDescendants,
)
def _on_browse_fn(self, widget):
self._new_mat_fp.show()
@staticmethod
def _on_file_open(owner_weak, dialog: FilePickerDialog, filename: str, dirname: str):
owner = owner_weak()
if not owner:
return
file_path = ""
if dirname:
file_path = f"{dirname}/{filename}"
elif filename:
file_path = filename
dialog.hide()
if not "omniverse:" in file_path:
carb.log_warn("No local file support, please select an Omniverse asset")
owner._new_mat.value = "No local file support, please select an Omniverse asset"
else:
owner._import_file_path = file_path
base_name = os.path.basename(owner._import_file_path)
file_name, _ = os.path.splitext(os.path.basename(base_name))
file_name = owner._make_valid_identifier(file_name)
owner._add_material(file_path, file_name)
def _add_material(self, mat_path, mat_name):
stage = self._usd_context.get_stage()
d_xform = stage.GetDefaultPrim()
d_xname = str(d_xform.GetPath())
mat_prim = stage.DefinePrim("{}/Looks/{}".format(d_xname, mat_name), "Material")
mat = UsdShade.Material.Get(stage, mat_prim.GetPath())
if mat:
shader_prim = stage.DefinePrim("{}/Looks/{}/Shader".format(d_xname, mat_name), "Shader")
shader = UsdShade.Shader.Get(stage, shader_prim.GetPath())
if shader:
mdl_token = "mdl"
shader_out = shader.CreateOutput("out", Sdf.ValueTypeNames.Token)
mat.CreateSurfaceOutput(mdl_token).ConnectToSource(shader_out)
mat.CreateVolumeOutput(mdl_token).ConnectToSource(shader_out)
mat.CreateDisplacementOutput(mdl_token).ConnectToSource(shader_out)
shader.GetImplementationSourceAttr().Set(UsdShade.Tokens.sourceAsset)
shader.SetSourceAsset(mat_path, mdl_token)
shader.SetSourceAssetSubIdentifier(mat_name, mdl_token)
self._new_mat.value = str(mat.GetPath())
def _make_valid_identifier(self, identifier):
if len(identifier) == 0:
return "_"
result = identifier[0]
if not identifier[0].isalpha():
result = "_"
for i in range(len(identifier) - 1):
if identifier[i + 1].isalnum():
result += identifier[i + 1]
else:
result += "_"
return result
def _on_file_selected_fn(self, widget):
carb.log_warn("file selected fn")
def _get_selectedold_fn(self, widget):
paths = self._selection.get_selected_prim_paths()
base_path = paths[0] if len(paths) > 0 else None
base_path = Sdf.Path(base_path) if base_path else None
if base_path:
mat = self._get_material(base_path)
self._old_mat.value = str(mat)
else:
carb.log_error("No selected prim")
def _get_selectednew_fn(self, widget):
paths = self._selection.get_selected_prim_paths()
base_path = paths[0] if len(paths) > 0 else None
base_path = Sdf.Path(base_path) if base_path else None
if base_path:
mat = self._get_material(base_path)
self._new_mat.value = str(mat)
else:
carb.log_error("No selected prim")
def _get_material(self, path):
stage = self._usd_context.get_stage()
prim = stage.GetPrimAtPath(path)
p_type = prim.GetTypeName()
if p_type == "Material":
return path
else:
return None
def on_shutdown(self):
if self._new_mat_fp:
del self._new_mat_fp
self._new_mat_fp = None
global _extension_instance
_extension_instance = None
def get_instance():
global _extension_instance
return _extension_instance
| 8,818 | Python | 36.688034 | 145 | 0.598889 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/__init__.py | from .test_material_swap import *
| 34 | Python | 16.499992 | 33 | 0.764706 |
omniverse-code/kit/exts/omni.kit.window.material_swap/omni/kit/window/material_swap/tests/test_material_swap.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 unittest
import carb
import omni.kit.test
from pxr import Usd, UsdGeom, Sdf, UsdShade
class TestMaterialSwap(omni.kit.test.AsyncTestCase):
async def setUp(self):
from omni.kit.window.material_swap.scripts.material_swap import TEST_DATA_PATH
self._usd_path = TEST_DATA_PATH.absolute()
async def tearDown(self):
pass
async def test_material_swap(self):
def get_bound_material(path: str) -> str:
prim = omni.usd.get_context().get_stage().GetPrimAtPath(path)
mat, rel = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial()
if mat:
return mat.GetPath().pathString
return ""
test_file_path = self._usd_path.joinpath("material_swap_test.usda").absolute()
await omni.usd.get_context().open_stage_async(str(test_file_path))
await omni.kit.app.get_app().next_update_async()
material_swap = omni.kit.window.material_swap.get_instance()
selection = omni.usd.get_context().get_selection()
# verify initial state
self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/GroundMat")
self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/GroundMat")
# select old material
selection.set_selected_prim_paths(["/World/Looks/GroundMat"], True)
material_swap._get_selectedold_fn(None)
await omni.kit.app.get_app().next_update_async()
# select new material
selection.set_selected_prim_paths(["/World/Looks/PreviewSurfaceTexture"], True)
material_swap._get_selectednew_fn(None)
await omni.kit.app.get_app().next_update_async()
# swap material
material_swap._on_swap_fn(None)
await omni.kit.app.get_app().next_update_async()
await omni.kit.app.get_app().next_update_async()
# verify change
self.assertEqual(get_bound_material('/World/studiohemisphere/Sphere'), "/World/Looks/PreviewSurfaceTexture")
self.assertEqual(get_bound_material('/World/studiohemisphere/Floor'), "/World/Looks/PreviewSurfaceTexture")
| 2,592 | Python | 41.508196 | 116 | 0.689043 |
omniverse-code/kit/exts/omni.kit.window.material_swap/docs/CHANGELOG.md | # Changelog
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [1.0.3] - 2021-06-30
### Changes
- Material test optimization
## [1.0.2] - 2021-03-02
### Changes
- Added test
## [1.0.1] - 2020-11-23
### Changes
- Updated to use new FilePicker
## [1.0.0] - 2020-08-20
### Changes
- converted to extension 2.0
- fixed issues with ui errors fixed issue with incorrect usage of GetBoundMaterial fixed issues with hidden and valid mesh types
| 474 | Markdown | 21.619047 | 128 | 0.689873 |
omniverse-code/kit/exts/omni.kit.window.material_swap/docs/index.rst | omni.kit.window.material_swap
##############################
Material Swap
.. toctree::
:maxdepth: 1
CHANGELOG
| 125 | reStructuredText | 7.4 | 30 | 0.496 |
omniverse-code/kit/exts/omni.rtx.settings.core/PACKAGE-LICENSES/omni.rtx.settings.core-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.rtx.settings.core/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "0.5.8"
# Lists people or organizations that are considered the "authors" of the package.
authors = ["NVIDIA"]
# The title and description fields are primarily for displaying extension info in UI
title = "RTX Realtime/PT Renderer Settings"
description="Renderer Settings for RTX Realtime/PathTracer"
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Rendering"
# Keywords for the extension
keywords = ["kit", "rtx", "rendering"]
# Location of change log file in target (final) folder of extension, relative to the root. Can also be just a content
# of it instead of file path. More info on writing changelog: https://keepachangelog.com/en/1.0.0/
changelog="docs/CHANGELOG.md"
# Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file).
# Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image.
preview_image = "data/preview.png"
# Icon is shown in Extensions window, it is recommended to be square, of size 256x256.
icon = "data/icon.png"
[dependencies]
"omni.kit.commands" = {}
"omni.ui" = {}
"omni.rtx.window.settings" = { }
"omni.usd" = {}
# Should always load after omni.hydra.rtx, but keep as an optional dependency
"omni.hydra.rtx" = {optional = true}
# Main python module this extension provides, it will be publicly available as "import omni.example.hello".
[[python.module]]
name = "omni.rtx.settings.core"
[[test]]
timeout = 600 # OM-51983
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--/app/renderer/resolution/width=128",
"--/app/renderer/resolution/height=128",
"--no-window"
]
stdoutFailPatterns.exclude = [
]
dependencies = [
"omni.kit.renderer.capture",
"omni.kit.mainwindow",
"omni.kit.ui_test",
"omni.hydra.rtx",
"omni.kit.window.viewport"
]
| 2,080 | TOML | 29.15942 | 118 | 0.718269 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/extension.py | import omni.ext
from omni.rtx.window.settings import RendererSettingsFactory
from .widgets.common_widgets import CommonSettingStack
from .widgets.post_widgets import PostSettingStack
from .widgets.pt_widgets import PTSettingStack
from .widgets.rt_widgets import RTSettingStack
class RTXSettingsExtension(omni.ext.IExt):
MENU_PATH = "Rendering"
rendererNames = ["Real-Time", "Interactive (Path Tracing)"]
stackNames = ["Common", "Ray Tracing", "Path Tracing", "Post Processing"]
def on_startup(self):
RendererSettingsFactory.register_stack(self.stackNames[0], CommonSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[1], RTSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[2], PTSettingStack)
RendererSettingsFactory.register_stack(self.stackNames[3], PostSettingStack)
RendererSettingsFactory.register_renderer(
self.rendererNames[0], [self.stackNames[0], self.stackNames[1], self.stackNames[3]]
)
RendererSettingsFactory.register_renderer(
self.rendererNames[1], [self.stackNames[0], self.stackNames[2], self.stackNames[3]]
)
RendererSettingsFactory.build_ui()
def on_shutdown(self):
for renderer in self.rendererNames:
RendererSettingsFactory.unregister_renderer(renderer)
for stack in self.stackNames:
RendererSettingsFactory.unregister_stack(stack)
RendererSettingsFactory.build_ui()
| 1,496 | Python | 40.583332 | 95 | 0.731952 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/__init__.py | from .extension import *
| 25 | Python | 11.999994 | 24 | 0.76 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/common_widgets.py | import omni.ui as ui
from omni.kit.widget.settings import SettingType
import omni.kit.commands
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
from omni.kit.widget.settings import SettingsWidgetBuilder
import carb
class GeometrySettingsFrame(SettingsCollectionFrame):
""" Geometry """
def _build_ui(self):
tbnMode = ["Auto", "CPU", "GPU", "Force GPU"]
scale_option = {"Default": -1, "Small - 1cm": 0.01, "Medium - 10 cm": 0.1, "Big - 100 cm": 1}
with ui.CollapsableFrame("Misc Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo("Normal & Tangent Space Generation Mode", "/rtx/hydra/TBNFrameMode", tbnMode,
tooltip="\nMode selection for vertex Normals and Tangents generation. Options are:"
"\n-AUTO: Selects the mode depending on available data and data update pattern."
"\n-CPU: Uses mikktspace to generate tangent basis on the CPU."
"\n-GPU: Allows normal and tangent basis update on the GPU to avoid the CPU overhead, such as for deforming meshes."
"\n-Force GPU: Forces GPU mode.")
self._add_setting(SettingType.BOOL, "Back Face Culling", "/rtx/hydra/faceCulling/enabled",
tooltip="\nEnables back face culling for 'Single Sided' primitives."
"\nThis applies to UsdGeom prims set to 'Single Sided' since the Double Sided flag is ignored.")
self._add_setting(SettingType.BOOL, "USD ST Main Texcoord as Default UV Set", "/rtx/hydra/uvsets/stIsDefaultUvSet", tooltip="\nIf enabled, ST is considered to be the default UV set name.")
self._add_setting(SettingType.BOOL, "Hide Geometry That Uses Opacity (debug)", "/rtx/debug/onlyOpaqueRayFlags", tooltip="\nAllows hiding all objects which have opacity enabled in their material.")
self._add_setting(SettingType.BOOL, "Instance Selection", "/rtx/hydra/instancePickingEnabled", tooltip="\nEnables the picking of instances.")
# if set to zero, override to scene unit, which means the scale factor would be 1
self._add_setting_combo("Renderer-Internal Meters Per Unit", "/rtx/scene/renderMeterPerUnit", scale_option,
tooltip="\nNumber of units per meter used by the renderer relative to the scene scale."
"\nSome materials depend on scene scale, such as subsurface scattering and volumetric shading.")
self._add_setting(SettingType.FLOAT, "Ray Offset (0 = auto)", "/rtx/raytracing/rayOffset", 0.0, 5.0, 0.001, tooltip="\nOffset used to prevent ray-triangle self intersections." )
self._add_setting(SettingType.FLOAT, "Points Default Width", "/persistent/rtx/hydra/points/defaultWidth", tooltip="\nUses this value if width is not specified in UsdGeomPoints.")
with ui.CollapsableFrame("Wireframe Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Per-primitive Wireframe uses World Space Thickness", "/rtx/wireframe/wireframeThicknessWorldSpace", tooltip="\nInterprets the per-primitive wireframe thickness value in world space instead of screen space.")
self._add_setting(SettingType.BOOL, "Global Wireframe uses World Space Thickness", "/rtx/wireframe/globalWireframeThicknessWorldSpace", tooltip="\nInterprets the global wireframe thickness value in world space instead of screen space.")
self._add_setting(SettingType.FLOAT, "Thickness", "/rtx/wireframe/wireframeThickness", 0.1, 100, 0.1, tooltip="\nWireframe thickness in wireframe mode.")
def clear_refinement_overrides():
omni.kit.commands.execute("ClearRefinementOverrides")
with ui.CollapsableFrame("Subdivision Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.INT, "Global Refinement Level", "/rtx/hydra/subdivision/refinementLevel", 0, 8, hard_range=True,
tooltip="\nThe refinement level for all primitives with Subdivision Schema not set to None."
"\nEach increment increases the mesh triangle count by a factor of 4.")
self._add_setting(SettingType.BOOL, "Feature-Adaptive Refinement", "/rtx/hydra/subdivision/adaptiveRefinement",
tooltip="\nIncreases or reduces the refinement level based on geometric features."
"\nThis reduces the number of triangles used in flat areas for example.")
ui.Button("Clear Refinement Override in All Prims", clicked_fn=clear_refinement_overrides, tooltip="\nClears the Refinement Override set in all Prims.")
def clear_splits_overrides():
omni.kit.commands.execute("ClearCurvesSplitsOverridesCommand")
with ui.CollapsableFrame("Curves Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.INT, "Global Number of BVH Splits", "/rtx/hydra/curves/splits", 1, 8, hard_range=True,
tooltip="\nHigher number of splits results in faster rendering but longer BVH build time."
"\nThe speed up depends on the geometry: long and thin curve segments tend to benefit from more splits."
"\nMemory used by the BVH grows linearly with the number of splits.")
ui.Button("Clear Number of BVH Splits Overrides in All Prims", clicked_fn=clear_splits_overrides, tooltip="\nClears the Number of BVH Splits Refinement Override set in all Prims.")
class MaterialsSettingsFrame(SettingsCollectionFrame):
""" Materials """
def _on_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/app/renderer/skipMaterialLoading", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx-transient/resourcemanager/enableTextureStreaming", self._on_change)
# The setting is maxMipCount, to make it more user friendly we expose it in the API as max resolution
texture_mip_sizes = {
"64": 7,
"128": 8,
"256": 9,
"512": 10,
"1024": 11,
"2048": 12,
"4096": 13,
"8192": 14,
"16384": 15,
"32768": 16,
}
self._add_setting(SettingType.BOOL, "Disable Material Loading", "/app/renderer/skipMaterialLoading", tooltip="\nScenes will be loaded without materials. This can lower scene loading time.")
if not self._settings.get("/app/renderer/skipMaterialLoading"):
with ui.CollapsableFrame("Texture Compression Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo("Max Resolution", "/rtx-transient/resourcemanager/maxMipCount", texture_mip_sizes, tooltip="\nTextures larger than this will be downsampled at this resolution.")
self._add_setting(SettingType.INT, "Compression Size Threshold", "/rtx-transient/resourcemanager/compressionMipSizeThreshold", 0, 8192, tooltip="\nTextures smaller than this size won't be compressed. 0 disables compression.")
self._add_setting(SettingType.BOOL, "Normal Map Mip-Map Generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/genMipsForNormalMaps", tooltip="\nEnables mip-map generation for normal maps to reduce memory usage at the expense of quality.")
# if self._settings.get("/rtx-transient/resourcemanager/genMipsForNormalMaps"):
# self._add_setting(SettingType.BOOL, "Normal Map Roughness generation (toggling requires scene reload)", "/rtx-transient/resourcemanager/createNormalRoughness", tooltip="\nEnables roughness generation for normal maps for improved specular reflection with mip mapping enabled.")
with ui.CollapsableFrame("Texture Streaming Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Enable Texture Streaming (toggling requires scene reload)", "/rtx-transient/resourcemanager/enableTextureStreaming", tooltip="\nEnables texture streaming.")
if self._settings.get("/rtx-transient/resourcemanager/enableTextureStreaming"):
self._add_setting(SettingType.FLOAT, " Memory Budget (% of GPU memory)", "/rtx-transient/resourcemanager/texturestreaming/memoryBudget", 0, 1, tooltip="\nLimits the GPU memory budget used for texture streaming.")
self._add_setting(SettingType.INT, " Budget Per Request (in MB)", "/rtx-transient/resourcemanager/texturestreaming/streamingBudgetMB", 0, 10000,
tooltip="\nMaximum budget per streaming request. 0 = unlimited but could lead to stalling during streaming."
"\nHigh or unlimited budget could lead to stalling during streaming.")
with ui.CollapsableFrame("MDL Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.FLOAT, "Animation Time Override", "/rtx/animationTime", tooltip="\nOverrides the time value provided to MDL materials.")
self._add_setting(SettingType.BOOL, "Animation Time Use Wallclock", "/rtx/animationTimeUseWallclock", tooltip="\nUse actual elapsed time for animation instead of simulated time.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
super().destroy()
class LightingSettingsFrame(SettingsCollectionFrame):
""" Lighting """
def _build_ui(self):
with ui.CollapsableFrame("Light Visibility Settings", height=0):
with ui.VStack(height=0, spacing=5):
# Common show light setting for all render modes - this makes the /pathracing/showLights and /directLighting/showLights deprecated and should be used instead
# see LightTypes.hlslh for enum
show_lights_settings = {
"Per-Light Enable": 0,
"Force Enable": 1,
"Force Disable": 2
}
self._add_setting_combo("Show Area Lights In Primary Rays", "/rtx/raytracing/showLights", show_lights_settings, tooltip="\nDefines if area lights are visible or invisible in primary rays.")
self._add_setting(SettingType.FLOAT, "Invisible Lights Roughness Threshold", "/rtx/raytracing/invisLightRoughnessThreshold", 0, 1, 0.001,
tooltip="\nDefines the roughness threshold below which lights invisible in primary rays"
"\nare also invisible in reflections and refractions.")
self._add_setting(SettingType.BOOL, "Use First Distant Light & First Dome Light Only", "/rtx/scenedb/skipMostLights", tooltip="\nDisable all lights except the first distant light and first dome light.")
self._add_setting(SettingType.FLOAT, "Shadow Bias", "/rtx/raytracing/shadowBias", 0.0, 5.0, 0.001, tooltip="\nOffset applied for shadow ray origin along the surface normal. Reduces self-shadowing artifacts.")
with ui.CollapsableFrame("Dome Light Settings", height=0):
with ui.VStack(height=0, spacing=5):
dome_lighting_sampling_type = {
"Image-Based Lighting": 0,
"Approximated Image-Based Lighting": 4,
"Environment Mapped Image-Based Lighting": 3
}
self._add_setting_combo("Lighting Mode", "/rtx/domeLight/upperLowerStrategy", dome_lighting_sampling_type,
tooltip="\n-Image-Based Lighting: Most accurate even for high-frequency Dome Light textures. Can introduce sampling artefacts in real-time mode."
"\n-Approximated Image-Based Lighting: Fast and artefacts-free sampling in real-time mode but only works well with a low-frequency texture,"
"\nfor example a sky with no sun disc where the sun is instead a separate Distant Light. Requires enabling Direct Lighting denoiser."
"\n-Limited Image-Based Lighting: Only sampled for reflection and refraction. Fastest, but least accurate. Good for cases where the Dome Light"
"\ncontributes less than other light sources.")
dome_texture_resolution_items = {
"16": 16,
"32": 32,
"64": 64,
"128": 128,
"256": 256,
"512": 512,
"1024": 1024,
"2048": 2048,
"4096": 4096,
"8192": 8192,
}
self._add_setting_combo("Baking Resolution", "/rtx/domeLight/baking/resolution", dome_texture_resolution_items, tooltip="\nThe baking resolution of the Dome Light texture when an MDL material is used as its image source.")
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" Global Volumetric Effects Common Settings RT & PT """
def _frame_setting_path(self):
return "/rtx/raytracing/globalVolumetricEffects/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Fog Height", "/rtx/raytracing/inscattering/atmosphereHeight", -2000, 100000, 10, tooltip="\nHeight in world units (centimeters) at which the medium ends. Useful for atmospheres with distant lights or dome lights.")
self._add_setting(SettingType.FLOAT, "Fog Height Fall Off", "/rtx/pathtracing/ptvol/fogHeightFallOff", 10, 2000, 1, tooltip="\nExponential decay of the fog above the Fog Height.")
self._add_setting(SettingType.FLOAT, "Maximum inscattering Distance", "/rtx/raytracing/inscattering/maxDistance", 10, 1000000,
tooltip="\nMaximum depth in world units (centimeters) the voxel grid is allocated to."
"\nIf set to 10,000 with 10 depth slices, each slice will span 1,000 units (assuming a slice distribution exponent of 1)."
"\nIdeally this should be kept as low as possible without causing artifacts to make the most of the fixed number of depth slices.")
self._add_setting(SettingType.FLOAT, "Density Multiplier", "/rtx/raytracing/inscattering/densityMult", 0, 2, 0.001, tooltip="\nScales the fog density.")
self._add_setting(SettingType.FLOAT, "Transmittance Measurment Distance", "/rtx/raytracing/inscattering/transmittanceMeasurementDistance", 0.0001, 1000000, 10, tooltip="\nControls how far light can travel through fog. Lower values yield thicker fog.")
self._add_setting(SettingType.COLOR3, "Transmittance Color", "/rtx/raytracing/inscattering/transmittanceColor",
tooltip="\nAssuming a white light, it represents its tint after traveling a number of units through"
"\nthe volume as specified in Transmittance Measurement Distance.")
self._add_setting(SettingType.COLOR3, "Single Scattering Albedo", "/rtx/raytracing/inscattering/singleScatteringAlbedo", tooltip="\nThe ratio of scattered-light to attenuated-light for an interaction with the volume. Values closer to 1 indicate high scattering.")
self._add_setting(SettingType.FLOAT, "Anisotropy Factor (g)", "/rtx/raytracing/inscattering/anisotropyFactor", -0.999, 0.999, 0.01,
tooltip="\nAnisotropy of the volumetric phase function, or the degree of light scattering asymmetry."
"\n-1 is back-scattered, 0 is isotropic, 1 is forward-scattered.")
with ui.CollapsableFrame("Density Noise Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Apply Density Noise", "/rtx/raytracing/inscattering/useDetailNoise", tooltip="\nEnables modulating the density with a noise. Enabling this option can reduce performance.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/useDetailNoise", self._on_change)
if self._settings.get("/rtx/raytracing/inscattering/useDetailNoise"):
self._add_setting(SettingType.FLOAT, " World Scale", "/rtx/raytracing/inscattering/detailNoiseScale", 0.0, 1, 0.00001, tooltip="\nA scale multiplier for the noise. Smaller values produce more sparse noise.")
self._add_setting(SettingType.FLOAT, " Animation Speed X", "/rtx/raytracing/inscattering/noiseAnimationSpeedX", -1.0, 1.0, 0.01, tooltip="\nThe X vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Animation Speed Y", "/rtx/raytracing/inscattering/noiseAnimationSpeedY", -1.0, 1.0, 0.01, tooltip="\nThe Y vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Animation Speed Z", "/rtx/raytracing/inscattering/noiseAnimationSpeedZ", -1.0, 1.0, 0.01, tooltip="\nThe Z vector for the noise shift when animated.")
self._add_setting(SettingType.FLOAT, " Scale Min", "/rtx/raytracing/inscattering/noiseScaleRangeMin", -1.0, 5.0, 0.01,
tooltip="\nA range to map the noise values of each noise octave."
"\nTypically these should be 0 and 1."
"\nTo make sparse points in the noise less sparse a higher Min can be used, or a lower Max for dense points to be less dense.")
self._add_setting(SettingType.FLOAT, " Scale Max", "/rtx/raytracing/inscattering/noiseScaleRangeMax", -1.0, 5.0, 0.01,
tooltip="\nA range to map the noise values of each noise octave."
"\nTypically these should be 0 and 1. To make sparse points in the noise less sparse"
"\na higher Min can be used, or a lower Max for dense points to be less dense.")
self._add_setting(SettingType.INT, " Octave Count", "/rtx/raytracing/inscattering/noiseNumOctaves", 1, 8, tooltip="\nA higher octave count results in greater noise detail, at the cost of performance.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class SimpleFogSettingsFrame(SettingsCollectionFrame):
""" Simple Fog """
def _frame_setting_path(self):
return "/rtx/fog/enabled"
def _build_ui(self):
self._add_setting(SettingType.COLOR3, "Color", "/rtx/fog/fogColor", tooltip="\nThe color or tint of the fog volume.")
self._add_setting(SettingType.FLOAT, "Intensity", "/rtx/fog/fogColorIntensity", 1, 1000000, 1, tooltip="\nThe intensity of the fog effect.")
self._add_setting(SettingType.BOOL, "Height-based Fog - Use +Z Axis", "/rtx/fog/fogZup/enabled", tooltip="\nUse positive Z axis for height-based fog. Otherwise use the positive Y axis.")
self._add_setting(SettingType.FLOAT, "Height-based Fog - Plane Height", "/rtx/fog/fogStartHeight", -1000000, 1000000, 0.01, tooltip="\nThe starting height (in meters) for height-based fog.")
self._add_setting(SettingType.FLOAT, "Height Density", "/rtx/fog/fogHeightDensity", 0, 1, 0.001, tooltip="\nDensity of the height-based fog. Higher values result in thicker fog.")
self._add_setting(SettingType.FLOAT, "Height Falloff", "/rtx/fog/fogHeightFalloff", 0, 1000, 0.002, tooltip="\nRate at which the height-based fog falls off.")
self._add_setting(SettingType.FLOAT, "Start Distance to Camera", "/rtx/fog/fogStartDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog begins.")
self._add_setting(SettingType.FLOAT, "End Distance to Camera", "/rtx/fog/fogEndDist", 0, 1000000, 0.1, tooltip="\nDistance from the camera at which the fog achieves maximum density.")
self._add_setting(SettingType.FLOAT, "Distance Density", "/rtx/fog/fogDistanceDensity", 0, 1, 0.001, tooltip="\nThe fog density at the End Distance.")
def destroy(self):
super().destroy()
class FlowSettingsFrame(SettingsCollectionFrame):
""" Flow """
def _frame_setting_path(self):
return "/rtx/flow/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Shadows", "/rtx/flow/rayTracedShadowsEnabled")
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Reflections", "/rtx/flow/rayTracedReflectionsEnabled")
self._add_setting(SettingType.BOOL, "Flow in Real-Time Ray Traced Translucency", "/rtx/flow/rayTracedTranslucencyEnabled")
self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode", "/rtx/flow/pathTracingEnabled")
self._add_setting(SettingType.BOOL, "Flow in Path-Traced Mode Shadows", "/rtx/flow/pathTracingShadowsEnabled")
self._add_setting(SettingType.BOOL, "Composite with Flow Library Renderer", "/rtx/flow/compositeEnabled")
self._add_setting(SettingType.BOOL, "Use Flow Library Self Shadow", "/rtx/flow/useFlowLibrarySelfShadow")
self._add_setting(SettingType.INT, "Max Blocks", "/rtx/flow/maxBlocks")
def destroy(self):
super().destroy()
class IndexCompositeSettingsFrame(SettingsCollectionFrame):
""" NVIDIA IndeX Compositing """
def _frame_setting_path(self):
return "/rtx/index/compositeEnabled"
def _build_ui(self):
ui.Label("You can activate IndeX composite rendering for individual Volume or Points prims "
"by enabling their 'Use IndeX compositing' property.", word_wrap=True)
ui.Separator()
depth_compositing_settings = {
"Disable": 0,
"Before Anti-Aliasing": 1,
"After Anti-Aliasing": 2,
"After Anti-Aliasing (Stable Depth)": 3
}
self._add_setting_combo(
"Depth Compositing",
"/rtx/index/compositeDepthMode",
depth_compositing_settings,
tooltip="Depth-correct compositing between renderers")
self._add_setting(
SettingType.FLOAT,
"Color Scaling",
"/rtx/index/colorScale",
0.0,
100.0,
tooltip="Scale factor for color output",
)
self._add_setting(
SettingType.BOOL,
"sRGB Conversion",
"/rtx/index/srgbConversion",
tooltip="Apply color space conversion to IndeX rendering",
)
self._add_setting(
SettingType.INT,
"Resolution Scaling",
"/rtx/index/resolutionScale",
1,
100,
tooltip="Reduces the IndeX rendering resolution (in percent relative to the viewport resolution)",
)
self._add_setting(
SettingType.INT,
"Rendering Samples",
"/rtx/index/renderingSamples",
1,
32,
tooltip="Number of samples per pixel used during rendering",
)
self._add_setting(
SettingType.FLOAT,
"Default Point Width",
"/rtx/index/defaultPointWidth",
tooltip="Default point width for new point clouds loaded from USD. If set to 0, a simple heuristic will be used.",
)
def destroy(self):
super().destroy()
class DebugViewSettingsFrame(SettingsCollectionFrame):
""" Debug View """
def _on_debug_view_change(self, *_):
self._rebuild()
def _build_ui(self):
debug_view_items = {
"Off": "",
"RT Developer Debug Texture": "developerDebug",
"3D Motion Vectors [WARNING: Flashing Colors]": "targetMotion",
"3D Motion Vector Arrows [WARNING: Flashing Colors]": "targetMotionArrows",
"3D Final Motion Vector Arrows [WARNING: Flashing Colors]": "finalMotion",
"Barycentrics": "barycentrics",
"Beauty After Tonemap": "beautyPostTonemap",
"Beauty Before Tonemap": "beautyPreTonemap",
"Depth": "depth",
"Instance ID": "instanceId",
"Interpolated Normal": "normal",
"Heat Map: Any Hit": "anyHitCountHeatMap",
"Heat Map: Intersection": "intersectionCountHeatMap",
"Heat Map: Timing": "timingHeatMap",
"SDG: Cross Correspondence": "sdgCrossCorrespondence",
"SDG: Motion": "sdgMotion",
"Tangent U": "tangentu",
"Tangent V": "tangentv",
"Texture Coordinates 0": "texcoord0",
"Texture Coordinates 1": "texcoord1",
"Triangle Normal": "triangleNormal",
"Triangle Normal (OctEnc)": "triangleNormalOctEnc", # ReLAX Only
"Wireframe": "wire",
"RT Ambient Occlusion": "ao",
"RT Caustics": "caustics",
"RT Denoised Dome Light": "denoisedDomeLightingTex",
"RT Denoised Sampled Lighting": "rtDenoisedSampledLighting",
"RT Denoised Sampled Lighting Diffuse": "rtDenoiseSampledLightingDiffuse", # ReLAX Only
"RT Denoised Sampled Lighting Specular": "rtDenoiseSampledLightingSpecular", # ReLAX Only
"RT Diffuse GI": "indirectDiffuse",
"RT Diffuse GI (Not Accumulated)": "indirectDiffuseNonAccum",
"RT Diffuse Reflectance": "diffuseReflectance",
"RT Material Normal": "materialGeometryNormal",
"RT Material Normal (OctEnc)": "materialGeometryNormalOctEnc", # ReLAX Only
"RT Matte Object Compositing Alpha": "matteObjectAlpha",
"RT Matte Object Mask": "matteObjectMask",
"RT Matte Object View Before Postprocessing": "matteBeforePostprocessing",
"RT Noisy Dome Light": "noisyDomeLightingTex",
"RT Noisy Sampled Lighting": "rtNoisySampledLighting",
"RT Noisy Sampled Lighting (Not Accumulated)": "rtNoisySampledLightingNonAccum",
"RT Noisy Sampled Lighting Diffuse": "rtNoisySampledLightingDiffuse", # ReLAX Only
"RT Noisy Sampled Lighting Diffuse (Not Accumulated)": "sampledLightingDiffuseNonAccum",
"RT Noisy Sampled Lighting Specular": "rtNoisySampledLightingSpecular", # ReLAX Only
"RT Noisy Sampled Lighting Specular (Not Accumulated)": "sampledLightingSpecularNonAccum",
"RT Radiance": "radiance",
"RT Subsurface Radiance": "subsurface",
"RT Subsurface Transmission Radiance": "subsurfaceTransmission",
"RT Reflections": "reflections",
"RT Reflections (Not Accumulated)": "reflectionsNonAccum",
"RT Reflections 3D Motion Vectors [WARNING: Flashing Colors]": "reflectionsMotion",
"RT Roughness": "roughness",
"RT Shadow (last light)": "shadow",
"RT Specular Reflectance": "reflectance",
"RT Translucency": "translucency",
"RT World Position": "worldPosition",
"PT Adaptive Sampling Error [WARNING: Flashing Colors]": "PTAdaptiveSamplingError",
"PT Denoised Result": "pathTracerDenoised",
"PT Noisy Result": "pathTracerNoisy",
"PT AOV Background": "PTAOVBackground",
"PT AOV Diffuse Filter": "PTAOVDiffuseFilter",
"PT AOV Direct Illumation": "PTAOVDI",
"PT AOV Global Illumination": "PTAOVGI",
"PT AOV Reflections": "PTAOVReflections",
"PT AOV Reflection Filter": "PTAOVReflectionFilter",
"PT AOV Refractions": "PTAOVRefractions",
"PT AOV Refraction Filter": "PTAOVRefractionFilter",
"PT AOV Self-Illumination": "PTAOVSelfIllum",
"PT AOV Volumes": "PTAOVVolumes",
"PT AOV World Normal": "PTAOVWorldNormals",
"PT AOV World Position": "PTAOVWorldPos",
"PT AOV Z-Depth": "PTAOVZDepth",
"PT AOV Multimatte0": "PTAOVMultimatte0",
"PT AOV Multimatte1": "PTAOVMultimatte1",
"PT AOV Multimatte2": "PTAOVMultimatte2",
"PT AOV Multimatte3": "PTAOVMultimatte3",
"PT AOV Multimatte4": "PTAOVMultimatte4",
"PT AOV Multimatte5": "PTAOVMultimatte5",
"PT AOV Multimatte6": "PTAOVMultimatte6",
"PT AOV Multimatte7": "PTAOVMultimatte7",
}
self._add_setting_searchable_combo("Render Target", "/rtx/debugView/target", debug_view_items, "Off", "\nA list of all render passes which can be visualized.")
debug_view_target = self._settings.get("/rtx/debugView/target")
# Trigger the combo update to reflect the current selection when the ui is rebuilt
self._settings.set("/rtx/debugView/target", debug_view_target);
# Subscribe this frame to the target setting so we can show the heat map controls if necessary.
# This will remove the subscription from the searchable combo, but we will have a chance to update it
# because the new callback does a rebuild.
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/debugView/target", self._on_debug_view_change)
is_timing_heat_map = debug_view_target == "timingHeatMap"
is_any_hit_count_heat_map = debug_view_target == "anyHitCountHeatMap"
is_intersection_count_heat_map = debug_view_target == "intersectionCountHeatMap"
if is_timing_heat_map or is_any_hit_count_heat_map or is_intersection_count_heat_map:
# 'heat_map_view_items' MUST perfectly match with 'HeatMapSelectablePass' in 'RtxRendererContext.h'
heat_map_view_items = {
"GBuffer RT": 1,
"Path Tracing": 2,
"Shadow RT": 3,
"Deferred LTC Lighting RT": 4,
"Deferred Sampled Lighting RT": 5,
"Reflections LTC RT ": 6,
"Reflections Sampled RT": 7,
"Back Lighting": 8,
"Translucency RT": 9,
"SSS RT": 10,
"Transmission RT": 11,
"Indirect Diffuse RT (Apply Cache)": 12,
"Ray Traced Ambient Occlusion": 13
}
# 'heat_map_color_palette_items' MUST perfectly match with condition in 'temperature' function in 'DebugView.cs.hlsl'
heat_map_color_palette_items = {
"Rainbow": 0,
"Viridis": 1,
"Turbo": 2,
"Plasma": 3
}
self._add_setting_combo(" Pass To Visualize ", "/rtx/debugView/heatMapPass", heat_map_view_items)
if is_timing_heat_map:
self._add_setting(SettingType.FLOAT, " Maximum Time (µs)", "/rtx/debugView/heatMapMaxTime", 0, 100000.0, 1.0)
elif is_any_hit_count_heat_map:
self._add_setting(SettingType.INT, " Maximum Any Hit", "/rtx/debugView/heatMapMaxAnyHitCount", 1, 100)
elif is_intersection_count_heat_map:
self._add_setting(SettingType.INT, " Maximum Intersection", "/rtx/debugView/heatMapMaxIntersectionCount", 1, 100)
self._add_setting_combo(" Color Palette", "/rtx/debugView/heatMapColorPalette", heat_map_color_palette_items)
self._add_setting(SettingType.BOOL, " Show Color Bar", "/rtx/debugView/heatMapOverlayHeatMapScale")
else:
self._add_setting(SettingType.FLOAT, " Output Value Scaling", "/rtx/debugView/scaling", -1000000, 1000000, 1.0, tooltip="\nScales the output value by this factor. Useful to accentuate differences.")
class MaterialFlattenerSettingsFrame(SettingsCollectionFrame):
""" Material Flattening """
def _build_ui(self):
import carb
if not carb.settings.get_settings().get("/rtx/materialflattener/enabled"):
ui.Label("Material flattener disabled, rerun with --/rtx/materialflattener/enabled=true")
else:
planarProjectionPlaneAxes = ["auto", "xy", "xz", "yz"]
self._add_setting_combo("Planar Projection Plane Axes", "/rtx/materialflattener/planarProjectionPlaneAxes", planarProjectionPlaneAxes)
self._add_setting(SettingType.BOOL, "Show Decal Sources", "/rtx/materialflattener/showSources")
self._add_setting(SettingType.BOOL, "Live Baking", "/rtx/materialflattener/liveBaking")
self._add_setting(SettingType.BOOL, "Rebaking", "/rtx/materialflattener/rebaking")
self._add_setting(SettingType.BOOL, "Clear before baking", "/rtx/materialflattener/clearMaterialInputsBeforeBaking")
coverageSamples = ["Disabled", "4", "16", "64", "256"]
self._add_setting_combo("Decal Antialiasing Samples", "/rtx/materialflattener/decalCoverageSamples", coverageSamples)
self._add_setting(SettingType.BOOL, "Disable tile budget", "/rtx/materialflattener/disableTileBudget")
self._add_setting(SettingType.INT, "Number of tiles per frame", "/rtx/materialflattener/maxNumTilesToBakePerFrame")
self._add_setting(SettingType.INT, "Number of texels per frame", "/rtx/materialflattener/maxNumTexelsToBakePerFrame")
self._add_setting(SettingType.INT, "Number of material components per bake pass", "/rtx/materialflattener/numMaterialComponentsPerBakePass", 1, 12)
self._add_setting(SettingType.INT, "VTex Group to bake (-1 ~ all)", "/rtx/materialflattener/vtexGroupToBake", -1, 1023)
self._add_setting(SettingType.BOOL, "Radius based tile residency", "/rtx/materialflattener/radiusBasedResidency")
self._add_setting(SettingType.FLOAT, "Radius based tile residency - radius", "/rtx/materialflattener/radiusBasedResidencyRadius", 0, 10000, 0.1)
self._add_setting(SettingType.FLOAT, "Lod: derivative scale", "/rtx/virtualtexture/derivativeScale", 0.01, 100, 0.01)
self._add_setting(SettingType.FLOAT, "Decal distance tolerance", "/rtx/materialflattener/decalDistanceTolerance", 0, 1000, 0.01)
self._add_setting(SettingType.FLOAT, "Sampling LOD Bias", "/rtx/textures/lodBias", -15, 15, 0.01)
self._add_setting(SettingType.INT, "VTex Group ID color option (0 = disabled)", "/rtx/virtualtexture/colorCodeByVtexGroupIdOption", 0, 4)
self._add_setting(SettingType.INT, "Baking LOD Bias (on top of Sampling LOD bias)", "/rtx/materialflattener/bakingLodBias", -15, 12)
class CommonSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
GeometrySettingsFrame("Geometry", parent=self)
MaterialsSettingsFrame("Materials", parent=self)
LightingSettingsFrame("Lighting", parent=self)
SimpleFogSettingsFrame("Simple Fog", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
FlowSettingsFrame("Flow", parent=self)
# Only show IndeX settings if the extension is loaded
if carb.settings.get_settings().get("/nvindex/compositeRenderingMode"):
IndexCompositeSettingsFrame("NVIDIA IndeX Compositing", parent=self)
# MaterialFlattenerSettingsFrame("Material Flattener", parent=self)
DebugViewSettingsFrame("Debug View", parent=self)
| 36,215 | Python | 69.459144 | 302 | 0.638133 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/post_widgets.py | import omni.kit.app
import omni.ui as ui
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
import carb.settings
class ToneMappingSettingsFrame(SettingsCollectionFrame):
""" Tone Mapping """
def _on_tonemap_change(self, *_):
self._rebuild()
def _build_ui(self):
# The main tonemapping layout contains only the combo box. All the other options
# are saved in a different layout which can be swapped out in case the tonemapper changes.
tonemapper_ops = [
"Clamp",
"Linear (Off)",
"Reinhard",
"Modified Reinhard",
"HejlHableAlu",
"HableUc2",
"Aces",
"Iray",
]
self._add_setting_combo("Tone Mapping Operator", "/rtx/post/tonemap/op", tonemapper_ops,
tooltip="\nTone Mapping Operator selector."
"\n-Clamp: Leaves the radiance values unchanged, skipping any exposure adjustment."
"\n-Linear (Off): Applies the exposure adjustments but leaves the tone values otherwise unchanged."
"\n-Reinhard: Operator based on Erik Reinhard's tone mapping work."
"\n-Modified Reinhard: Variation of the operator based on Erik Reinhard's tone mapping work."
"\n-HejiHableAlu: John Hable's ALU approximation of Jim Heji's operator."
"\n-HableUC2: John Hable's Uncharted 2 filmic tone map."
"\n-ACES: Operator based on the Academy Color Encoding System."
"\n-Iray: Reinhard-based operator that matches the operator used by NVIDIA Iray by default.")
tonemapOpIdx = self._settings.get("/rtx/post/tonemap/op")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/tonemap/op", self._on_change)
if tonemapOpIdx == 3: # Modified Reinhard
self._add_setting(SettingType.FLOAT, " Max White Luminance", "/rtx/post/tonemap/maxWhiteLuminance", 0, 100, tooltip="\nMaximum HDR luminance value that will map to 1.0 post tonemap.")
if tonemapOpIdx == 5: # HableUc2
self._add_setting(SettingType.FLOAT, " White Scale Value", "/rtx/post/tonemap/whiteScale", 0, 100, tooltip="\nMaximum white value that will map to 1.0 post tonemap.")
if tonemapOpIdx == 7: # Iray
self._add_setting(SettingType.FLOAT, " Crush Blacks", "/rtx/post/tonemap/irayReinhard/crushBlacks", 0, 1, 0.02)
self._add_setting(SettingType.FLOAT, " Burn Highlights", "/rtx/post/tonemap/irayReinhard/burnHighlights", 0, 1, 0.02)
self._add_setting(SettingType.BOOL, " Burn Highlights per Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsPerComponent")
self._add_setting(SettingType.BOOL, " Burn Highlights max Component", "/rtx/post/tonemap/irayReinhard/burnHighlightsMaxComponent")
self._add_setting(SettingType.FLOAT, " Saturation", "/rtx/post/tonemap/irayReinhard/saturation", 0, 1, 0.02)
if tonemapOpIdx != 0: # Clamp is never using srgb conversion
self._add_setting(SettingType.BOOL, " SRGB To Gamma Conversion", "/rtx/post/tonemap/enableSrgbToGamma", tooltip="\nAvailable with Linear/Reinhard/Modified Reinhard/HejiHableAlu/HableUc2 Tone Mapping.")
self._add_setting(SettingType.FLOAT, "cm^2 Factor", "/rtx/post/tonemap/cm2Factor", 0, 2, tooltip="\nUse this factor to adjust for scene units being different from centimeters.")
self._add_setting(SettingType.FLOAT, "Film ISO", "/rtx/post/tonemap/filmIso", 50, 1600, tooltip="\nSimulates the effect on exposure of a camera's ISO setting.")
self._add_setting(SettingType.FLOAT, "Camera Shutter", "/rtx/post/tonemap/cameraShutter", 1, 5000, tooltip="\nSimulates the effect on exposure of a camera's shutter open time.")
self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/tonemap/fNumber", 1, 20, 0.1, tooltip="\nSimulates the effect on exposure of a camera's f-stop aperture.")
self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/tonemap/whitepoint", tooltip="\nA color mapped to white on the output.")
tonemapColorMode = ["sRGBLinear", "ACEScg"]
self._add_setting_combo("Tone Mapping Color Space", "/rtx/post/tonemap/colorMode", tonemapColorMode, tooltip="\nTone Mapping Color Space selector.")
self._add_setting(SettingType.FLOAT, "Wrap Value", "/rtx/post/tonemap/wrapValue", 0, 100000, tooltip="\nOffset")
self._add_setting(SettingType.FLOAT, "Dither strength", "/rtx/post/tonemap/dither", 0, .02, .001, tooltip="\nRemoves banding artifacts in final images.")
def destroy(self):
self._change_cb = None
super().destroy()
class AutoExposureSettingsFrame(SettingsCollectionFrame):
""" Auto Exposure """
def _frame_setting_path(self):
return "/rtx/post/histogram/enabled"
def _build_ui(self):
histFilter_types = ["Median", "Average"]
self._add_setting_combo("Histogram Filter", "/rtx/post/histogram/filterType", histFilter_types, tooltip="\nSelect a method to filter the histogram. Options are Median and Average.")
self._add_setting(SettingType.FLOAT, "Adaptation Speed", "/rtx/post/histogram/tau", 0.5, 10.0, 0.01, tooltip="\nHow fast automatic exposure compensation adapts to changes in overall light intensity.")
self._add_setting(SettingType.FLOAT, "White Point Scale", "/rtx/post/histogram/whiteScale", 0.01, 80.0, 0.001,
tooltip="\nControls how bright of an image the auto-exposure should aim for."
"\nLower values result in brighter images, higher values result in darker images.")
self._add_setting(SettingType.BOOL, "Exposure Value Clamping", "/rtx/post/histogram/useExposureClamping", tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/histogram/useExposureClamping", self._on_change)
if self._settings.get("/rtx/post/histogram/useExposureClamping"):
self._add_setting(SettingType.FLOAT, " Minimum Value", "/rtx/post/histogram/minEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
self._add_setting(SettingType.FLOAT, " Maximum Value", "/rtx/post/histogram/maxEV", 0.0, 1000000.0, 1, tooltip="\nClamps the exposure to a range within a specified minimum and maximum Exposure Value.")
# self._add_setting(SettingType.FLOAT, "Min Log Luminance", "/rtx/post/histogram/minloglum", -15, 5.0, 0.001)
# self._add_setting(SettingType.FLOAT, "Log Luminance Range", "/rtx/post/histogram/loglumrange", 0.00001, 50.0, 0.001)
def destroy(self):
self._change_cb = None
super().destroy()
class ColorCorrectionSettingsFrame(SettingsCollectionFrame):
""" Color Correction """
def _frame_setting_path(self):
return "/rtx/post/colorcorr/enabled"
def _on_colorcorrect_change(self, *_):
self._rebuild()
def _build_ui(self):
mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"]
self._add_setting_combo("Mode", "/rtx/post/colorcorr/mode", mode, tooltip="\nChoose between ACES (Pre-Tone mapping) or Standard (Post-Tone mapping) mode.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorcorr/mode", self._on_change)
colorCorrectionMode = ["sRGBLinear", "ACEScg"]
if self._settings.get("/rtx/post/colorcorr/mode") == 0:
self._add_setting_combo(" Output Color Space", "/rtx/post/colorcorr/outputMode", colorCorrectionMode,
tooltip="\nDefines the color space used as output of Color Correction."
"\nsRGB Linear: scene linear space"
"\nAcesCG: ACES CG color space")
self._add_setting(SettingType.COLOR3, "Saturation", "/rtx/post/colorcorr/saturation", tooltip="\nHigher values increase color saturation while lowering desaturates.")
self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorcorr/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.")
self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorcorr/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.")
self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorcorr/gain", 0, 10, 0.005, tooltip="\nA factor applied to the color values.")
self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorcorr/offset", -1, 1, 0.001, tooltip="\nAn offset applied to the color values.")
def destroy(self):
self._change_cb = None
super().destroy()
class ColorGradingSettingsFrame(SettingsCollectionFrame):
""" Color Grading """
def _frame_setting_path(self):
return "/rtx/post/colorgrad/enabled"
def _on_colorgrade_change(self, *_):
self._rebuild()
def _build_ui(self):
mode = ["ACES (Pre-Tonemap)", "Standard (Post-Tonemap)"]
self._add_setting_combo("Mode", "/rtx/post/colorgrad/mode", mode, tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/colorgrad/mode", self._on_change)
colorGradingMode = ["sRGBLinear", "ACEScg"]
if self._settings.get("/rtx/post/colorgrad/mode") == 0:
self._add_setting_combo(" Output Color Space", "/rtx/post/colorgrad/outputMode", colorGradingMode,
tooltip="\nChoose between ACES (Pre-Tonemap) or Standard (Post-Tonemap) Mode."
"\nsRGB Linear: scene linear space"
"\nAcesCG: ACES CG color space")
self._add_setting(SettingType.COLOR3, "Black Point", "/rtx/post/colorgrad/blackpoint", -1, 1, 0.005, tooltip="\nDefines the Black Point value.")
self._add_setting(SettingType.COLOR3, "White Point", "/rtx/post/colorgrad/whitepoint", 0, 10, 0.005, tooltip="\nDefines the White Point value.")
self._add_setting(SettingType.COLOR3, "Contrast", "/rtx/post/colorgrad/contrast", 0, 10, 0.005, tooltip="\nHigher values increase the contrast of darks/lights and colors.")
self._add_setting(SettingType.COLOR3, "Lift", "/rtx/post/colorgrad/lift", -10, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.")
self._add_setting(SettingType.COLOR3, "Gain", "/rtx/post/colorgrad/gain", 0, 10, 0.005, tooltip="\nColor is multiplied by (Lift - Gain) and later Lift is added back.")
self._add_setting(SettingType.COLOR3, "Multiply", "/rtx/post/colorgrad/multiply", 0, 10, 0.005, tooltip="\nA factor applied to the color values.")
self._add_setting(SettingType.COLOR3, "Offset", "/rtx/post/colorgrad/offset", -1, 1, 0.001, tooltip="\nColor offset: an offset applied to the color values.")
self._add_setting(SettingType.COLOR3, "Gamma", "/rtx/post/colorgrad/gamma", 0.2, 10, 0.005, tooltip="\nGamma value in inverse gamma curve applied before output.")
def destroy(self):
self._change_cb = None
super().destroy()
class MatteObjectSettingsFrame(SettingsCollectionFrame):
def _frame_setting_path(self):
return "/rtx/matteObject/enabled"
def _build_ui(self):
self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.")
self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.")
self._add_setting(SettingType.BOOL, "Shadow Catcher", "/rtx/post/matteObject/enableShadowCatcher",
tooltip="\Treats all matte objects as shadow catchers. Matte objects receives only shadow and"
"\nnot reflections or GI which improves rendering performance." )
class XRCompositingSettingsFrame(SettingsCollectionFrame):
def _frame_setting_path(self):
return "/rtx/post/backgroundZeroAlpha/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Composite in Editor", "/rtx/post/backgroundZeroAlpha/backgroundComposite",
tooltip="\nEnables alpha compositing with a backplate texture, instead of"
"\noutputting the rendered image with an alpha channel for compositing externally,"
"\nby saving to EXR images.")
self._add_setting(SettingType.BOOL, "Output Alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/outputAlphaInComposite",
tooltip="\nOutputs the matte compositing alpha in the composited image."
"\nOnly activates when not compositing in editor."
"\nThis option can interfere with DLSS, producing jaggied edges.")
self._add_setting(SettingType.BOOL, "Output Black Background in Composited Image", "/rtx/post/backgroundZeroAlpha/blackBackgroundInComposite",
tooltip="\nOutputs a black background in the composited image, for XR compositing."
"\nOnly activates when not compositing in editor.")
self._add_setting(SettingType.BOOL, "Multiply color value by alpha in Composited Image", "/rtx/post/backgroundZeroAlpha/premultiplyColorByAlpha",
tooltip="\nWhen enabled, the RGB color will be RGB * alpha.")
self._add_setting(SettingType.COLOR3, "Backplate Color", "/rtx/post/backgroundZeroAlpha/backgroundDefaultColor", tooltip="\nA constant color used if no backplate texture is set.")
self._add_setting("ASSET", "Backplate Texture", "/rtx/post/backgroundZeroAlpha/backplateTexture", tooltip="\nThe path to a texture to use as a backplate.")
self._add_setting(SettingType.BOOL, " Is linear", "/rtx/post/backgroundZeroAlpha/backplateTextureIsLinear", tooltip="\nSets the color space for the Backplate Texture to linear space.")
self._add_setting(SettingType.FLOAT, "Backplate Luminance Scale", "/rtx/post/backgroundZeroAlpha/backplateLuminanceScaleV2", tooltip="\nScales the Backplate Texture/Color luminance.")
self._add_setting(SettingType.BOOL, "Lens Distortion", "/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection",
tooltip="\nEnables distortion of the rendered image using a set of lens distortion and undistortion maps."
"\nEach of these should refer to a <UDIM> EXR texture set, containing one image for each"
"\nof the discrete focal length values specified in the array of float settings under"
"\n/rtx/post/lensDistortion/lensFocalLengthArray (not currently exposed).")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection", self._on_change)
if self._settings.get("/rtx/post/backgroundZeroAlpha/enableLensDistortionCorrection"):
self._add_setting("ASSET", " Distortion Map", "/rtx/post/lensDistortion/distortionMap", tooltip="\n<UDIM> EXR texture path to store the distortion maps for specified focal lengths.")
self._add_setting("ASSET", " Undistortion Map", "/rtx/post/lensDistortion/undistortionMap", tooltip="\n<UDIM> EXR texture path to store the un-distortion maps for specified focal lengths.")
def destroy(self):
self._change_cb = None
super().destroy()
class ChromaticAberrationSettingsFrame(SettingsCollectionFrame):
""" Chromatic Aberration """
def _frame_setting_path(self):
return "/rtx/post/chromaticAberration/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Strength Red", "/rtx/post/chromaticAberration/strengthR", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Red channel.")
self._add_setting(SettingType.FLOAT, "Strength Green", "/rtx/post/chromaticAberration/strengthG", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Green channel.")
self._add_setting(SettingType.FLOAT, "Strength Blue", "/rtx/post/chromaticAberration/strengthB", -1.0, 1.0, 0.01, tooltip="\nThe strength of the distortion applied on the Blue channel.")
chromatic_aberration_ops = ["Radial", "Barrel"]
self._add_setting_combo("Algorithm Red", "/rtx/post/chromaticAberration/modeR", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Red channel.")
self._add_setting_combo("Algorithm Green", "/rtx/post/chromaticAberration/modeG", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Green channel.")
self._add_setting_combo("Algorithm Blue", "/rtx/post/chromaticAberration/modeB", chromatic_aberration_ops, tooltip="\nSelects between Radial and Barrel distortion for the Blue channel.")
self._add_setting(SettingType.BOOL, "Use Lanczos Sampler", "/rtx/post/chromaticAberration/enableLanczos", tooltip="\nUse a Lanczos sampler when sampling the input image being distorted.")
with ui.CollapsableFrame("Boundary Blending", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting(SettingType.BOOL, "Repeat Mirrored", "/rtx/post/chromaticAberration/mirroredRepeat", tooltip="\nEnables mirror repeat for texture lookups in out-of-lens regions. When disabled, out-of-lens regions are black.")
self._add_setting(SettingType.FLOAT, "Blend Region Size", "/rtx/post/chromaticAberration/boundaryBlendRegionSize", 0.0, 1.0, 0.01, tooltip="\nDetermines the blend region size.")
self._add_setting(SettingType.FLOAT, "Blend Region Falloff", "/rtx/post/chromaticAberration/boundaryBlendFalloff", 0.001, 5.0, 0.001, tooltip="\nDetermines the falloff in the blending region.")
class DepthOfFieldSettingsFrame(SettingsCollectionFrame):
""" Depth of Field Camera Overrides """
def _frame_setting_path(self):
return "/rtx/post/dof/overrideEnabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Enable DOF", "/rtx/post/dof/enabled", tooltip="\nEnables Depth of Field. If disabled, camera parameters affecting Depth of Field are ignored.")
self._add_setting(SettingType.FLOAT, "Subject Distance", "/rtx/post/dof/subjectDistance", -10000, 10000.0, tooltip="\nObjects at this distance from the camera will be in focus.")
self._add_setting(SettingType.FLOAT, "Focal Length (mm)", "/rtx/post/dof/focalLength", 0, 1000, tooltip="\nThe focal length of the lens (in mm). The focal length divided by the f-stop is the aperture diameter.")
self._add_setting(SettingType.FLOAT, "F-stop", "/rtx/post/dof/fNumber", 0, 1000, tooltip="\nF-stop (aperture) of the lens. Lower f-stop numbers decrease the distance range from the Subject Distance where objects remain in focus.")
self._add_setting(SettingType.FLOAT, "Anisotropy", "/rtx/post/dof/anisotropy", -1, 1, 0.01, tooltip="\nAnisotropy of the lens. A value of -0.5 simulates the depth of field of an anamorphic lens.")
class MotionBlurSettingsFrame(SettingsCollectionFrame):
""" Motion Blur """
def _frame_setting_path(self):
return "/rtx/post/motionblur/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Blur Diameter Fraction", "/rtx/post/motionblur/maxBlurDiameterFraction", 0, 0.5, 0.01, tooltip="\nThe fraction of the largest screen dimension to use as the maximum motion blur diameter.")
self._add_setting(SettingType.FLOAT, "Exposure Fraction", "/rtx/post/motionblur/exposureFraction", 0, 5.0, 0.01, tooltip="\nExposure time fraction in frames (1.0 = one frame duration) to sample.")
self._add_setting(SettingType.INT, "Number of Samples", "/rtx/post/motionblur/numSamples", 4, 32, 1, tooltip="\nNumber of samples to use in the filter. A higher number improves quality at the cost of performance.")
class FFTBloomSettingsFrame(SettingsCollectionFrame):
""" FFT Bloom """
def _frame_setting_path(self):
return "/rtx/post/lensFlares/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Scale", "/rtx/post/lensFlares/flareScale", -1000, 1000, tooltip="\nOverall intensity of the bloom effect.")
self._add_setting(SettingType.DOUBLE3, "Cutoff Point", "/rtx/post/lensFlares/cutoffPoint", tooltip="\nA cutoff color value to tune the radiance range for which Bloom will have any effect. ")
self._add_setting(SettingType.FLOAT, "Cutoff Fuzziness", "/rtx/post/lensFlares/cutoffFuzziness", 0.0, 1.0,
tooltip="\nIf greater than 0, defines the width of a 'fuzzy cutoff' region around the Cutoff Point values."
"\nInstead of a sharp cutoff, a smooth transition between 0 and the original values is used.")
self._add_setting(SettingType.FLOAT, "Alpha channel scale", "/rtx/post/lensFlares/alphaExposureScale", 0.0, 100.0, tooltip="\nAlpha channel intensity of the bloom effect.")
self._add_setting(SettingType.BOOL, "Energy Constrained", "/rtx/post/lensFlares/energyConstrainingBlend", tooltip="\nConstrains the total light energy generated by bloom.")
self._add_setting(SettingType.BOOL, "Physical Model", "/rtx/post/lensFlares/physicalSettings", tooltip="\nChoose between a Physical or Non-Physical bloom model.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/post/lensFlares/physicalSettings", self._on_change)
if self._settings.get("/rtx/post/lensFlares/physicalSettings") == 1:
self._add_setting(SettingType.INT, " Blades", "/rtx/post/lensFlares/blades", 0, 10, tooltip="\nThe number of physical blades of a simulated camera diaphragm causing the bloom effect.")
self._add_setting(SettingType.FLOAT, " Aperture Rotation", "/rtx/post/lensFlares/apertureRotation", -1000, 1000, tooltip="\nRotation of the camera diaphragm.")
self._add_setting(SettingType.FLOAT, " Sensor Diagonal", "/rtx/post/lensFlares/sensorDiagonal", -1000, 1000, tooltip="\nDiagonal of the simulated sensor.")
self._add_setting(SettingType.FLOAT, " Sensor Aspect Ratio", "/rtx/post/lensFlares/sensorAspectRatio", -1000, 1000, tooltip="\nAspect ratio of the simulated sensor, results in the bloom effect stretching in one direction.")
self._add_setting(SettingType.FLOAT, " F-stop", "/rtx/post/lensFlares/fNumber", -1000, 1000, tooltip="\nIncreases/Decreases the sharpness of the bloom effect.")
self._add_setting(SettingType.FLOAT, " Focal Length (mm)", "/rtx/post/lensFlares/focalLength", -1000, 1000, tooltip="\nFocal length of the lens modeled to simulate the bloom effect.")
else:
self._add_setting(SettingType.DOUBLE3, " Halo Radius", "/rtx/post/lensFlares/haloFlareRadius", tooltip="\nControls the size of each RGB component of the halo flare effect.")
self._add_setting(SettingType.DOUBLE3, " Halo Flare Falloff", "/rtx/post/lensFlares/haloFlareFalloff", tooltip="\nControls the falloff of each RGB component of the halo flare effect.")
self._add_setting(SettingType.FLOAT, " Halo Flare Weight", "/rtx/post/lensFlares/haloFlareWeight", -1000, 1000, tooltip="\nControls the intensity of the halo flare effect.")
self._add_setting(SettingType.DOUBLE3, " Aniso Falloff Y", "/rtx/post/lensFlares/anisoFlareFalloffY", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the X direction.")
self._add_setting(SettingType.DOUBLE3, " Aniso Falloff X", "/rtx/post/lensFlares/anisoFlareFalloffX", tooltip="\nControls the falloff of each RGB component of the anistropic flare effect in the Y direction.")
self._add_setting(SettingType.FLOAT, " Aniso Flare Weight", "/rtx/post/lensFlares/anisoFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the anisotropic flare effect.")
self._add_setting(SettingType.DOUBLE3, " Isotropic Flare Falloff", "/rtx/post/lensFlares/isotropicFlareFalloff", tooltip="\nControls the falloff of each RGB component of the isotropic flare effect.")
self._add_setting(SettingType.FLOAT, " Isotropic Flare Weight", "/rtx/post/lensFlares/isotropicFlareWeight", -1000, 1000, tooltip="\nControl the intensity of the isotropic flare effect.")
def destroy(self):
self._change_cb = None
super().destroy()
class TVNoiseGrainSettingsFrame(SettingsCollectionFrame):
""" TV Noise | Film Grain """
def _frame_setting_path(self):
return "/rtx/post/tvNoise/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Enable Scanlines", "/rtx/post/tvNoise/enableScanlines", tooltip="\nEmulates a Scanline Distortion typical of old televisions.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableScanlines", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableScanlines"):
self._add_setting(SettingType.FLOAT, " Scanline Spreading", "/rtx/post/tvNoise/scanlineSpread", 0.0, 2.0, 0.01, tooltip="\nHow wide the Scanline distortion will be.")
self._add_setting(SettingType.BOOL, "Enable Scroll Bug", "/rtx/post/tvNoise/enableScrollBug", tooltip="\nEmulates sliding typical on old televisions.")
self._add_setting(SettingType.BOOL, "Enable Vignetting", "/rtx/post/tvNoise/enableVignetting", tooltip="\nBlurred darkening around the screen edges.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableVignetting", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableVignetting"):
self._add_setting(SettingType.FLOAT, " Vignetting Size", "/rtx/post/tvNoise/vignettingSize", 0.0, 255, tooltip="\nControls the size of vignette region.")
self._add_setting(SettingType.FLOAT, " Vignetting Strength", "/rtx/post/tvNoise/vignettingStrength", 0.0, 2.0, 0.01, tooltip="\nControls the intensity of the vignette.")
self._add_setting(SettingType.BOOL, " Enable Vignetting Flickering", "/rtx/post/tvNoise/enableVignettingFlickering", tooltip="\nEnables a slight flicker effect on the vignette.")
self._add_setting(SettingType.BOOL, "Enable Ghost Flickering", "/rtx/post/tvNoise/enableGhostFlickering", tooltip="\nIntroduces a blurred flicker to help emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Wavy Distortion", "/rtx/post/tvNoise/enableWaveDistortion", tooltip="\nIntroduces a Random Wave Flicker to emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Vertical Lines", "/rtx/post/tvNoise/enableVerticalLines", tooltip="\nIntroduces random vertical lines to emulate an old television.")
self._add_setting(SettingType.BOOL, "Enable Random Splotches", "/rtx/post/tvNoise/enableRandomSplotches", tooltip="\nIntroduces random splotches typical of old dirty television.")
self._add_setting(SettingType.BOOL, "Enable Film Grain", "/rtx/post/tvNoise/enableFilmGrain", tooltip="\nEnables a film grain effect to emulate the graininess in high speed (ISO) film.")
# Filmgrain is a subframe in TV Noise
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/post/tvNoise/enableFilmGrain", self._on_change)
if self._settings.get("/rtx/post/tvNoise/enableFilmGrain"):
self._add_setting(SettingType.FLOAT, " Grain Amount", "/rtx/post/tvNoise/grainAmount", 0, 0.2, 0.002, tooltip="\nThe intensity of the film grain effect.")
self._add_setting(SettingType.FLOAT, " Color Amount", "/rtx/post/tvNoise/colorAmount", 0, 1.0, 0.02, tooltip="\nThe amount of color offset each grain will be allowed to use.")
self._add_setting(SettingType.FLOAT, " Luminance Amount", "/rtx/post/tvNoise/lumAmount", 0, 1.0, 0.02, tooltip="\nThe amount of offset in luminance each grain will be allowed to use.")
self._add_setting(SettingType.FLOAT, " Grain Size", "/rtx/post/tvNoise/grainSize", 1.5, 2.5, 0.02, tooltip="\nThe size of the film grains.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
super().destroy()
class ReshadeSettingsFrame(SettingsCollectionFrame):
""" ReShade """
def _frame_setting_path(self):
return "/rtx/reshade/enable"
def _build_ui(self):
self._add_setting("ASSET", "Preset File Path", "/rtx/reshade/presetFilePath", tooltip="\nThe path to a preset.init file containing the Reshade preset to use.")
widget = self._add_setting("ASSET", "Effect search dir path", "/rtx/reshade/effectSearchDirPath", tooltip="\nThe path to a directory containing the Reshade files that the preset can reference.")
widget.is_folder=True
widget = self._add_setting("ASSET", "Texture search dir path", "/rtx/reshade/textureSearchDirPath", tooltip="\nThe path to a directory containing the Reshade texture files that the preset can reference.")
widget.is_folder=True
class PostSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
ToneMappingSettingsFrame("Tone Mapping", parent=self)
AutoExposureSettingsFrame("Auto Exposure", parent=self)
ColorCorrectionSettingsFrame("Color Correction", parent=self)
ColorGradingSettingsFrame("Color Grading", parent=self)
XRCompositingSettingsFrame("XR Compositing", parent=self)
MatteObjectSettingsFrame("Matte Object", parent=self)
ChromaticAberrationSettingsFrame("Chromatic Aberration", parent=self)
DepthOfFieldSettingsFrame("Depth of Field Camera Overrides", parent=self)
MotionBlurSettingsFrame("Motion Blur", parent=self)
FFTBloomSettingsFrame("FFT Bloom", parent=self)
TVNoiseGrainSettingsFrame("TV Noise & Film Grain", parent=self)
ReshadeSettingsFrame("ReShade", parent=self)
ui.Spacer()
| 30,479 | Python | 84.617977 | 243 | 0.696578 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/pt_widgets.py | import omni.ui as ui
import omni.kit.app
import carb.settings
import math
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
class AntiAliasingSettingsFrame(SettingsCollectionFrame):
""" Anti-Aliasing """
def _build_ui(self):
pt_aa_ops = ["Box", "Triangle", "Gaussian", "Uniform"]
self._add_setting_combo("Anti-Aliasing Sample Pattern", "/rtx/pathtracing/aa/op", pt_aa_ops, tooltip="\nSampling pattern used for Anti-Aliasing. Select between Box, Triangle, Gaussian and Uniform.")
self._add_setting(SettingType.FLOAT, "Anti-Aliasing Radius", "/rtx/pathtracing/aa/filterRadius", 0.0001, 5.0, 0.001, tooltip="\nSampling footprint radius, in pixels, when generating samples with the selected antialiasing sample pattern.")
class FireflyFilterSettingsFrame(SettingsCollectionFrame):
""" Firefly Filtering """
def _frame_setting_path(self):
return "/rtx/pathtracing/fireflyFilter/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Max Ray Intensity Glossy", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSample", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for glossy bounces. Can help prevent fireflies, but may result in energy loss.")
self._add_setting(SettingType.FLOAT, "Max Ray Intensity Diffuse", "/rtx/pathtracing/fireflyFilter/maxIntensityPerSampleDiffuse", 0, 100000, 100, tooltip="\nClamps the maximium ray intensity for diffuse bounces. Can help prevent fireflies, but may result in energy loss.")
class PathTracingSettingsFrame(SettingsCollectionFrame):
""" Path-Tracing """
def _build_ui(self):
clampSpp = self._settings.get("/rtx/pathtracing/clampSpp")
if clampSpp is not None and clampSpp > 1: # better 0, but setting range = (1,1) completely disables the UI control range
self._add_setting(SettingType.INT, "Samples per Pixel per Frame(1 to {})".format(clampSpp), "/rtx/pathtracing/spp", 1, clampSpp, tooltip="\nTotal number of samples for each rendered pixel, per frame.")
else:
self._add_setting(SettingType.INT, "Samples per Pixel per Frame", "/rtx/pathtracing/spp", 1, 1048576, tooltip="\nTotal number of samples for each rendered pixel, per frame.")
self._add_setting(SettingType.INT, "Total Samples per Pixel (0 = inf)", "/rtx/pathtracing/totalSpp", 0, 100000,
tooltip="\nMaximum number of samples to accumulate per pixel. When this count is reached the rendering stops until"
"\na scene or setting change is detected, restarting the rendering process. Set to 0 to remove this limit.")
self._add_setting(SettingType.BOOL, "Adaptive Sampling", "/rtx/pathtracing/adaptiveSampling/enabled", tooltip="\nWhen enabled, noise values are computed for each pixel, and upon threshold level eached, the pixel is no longer sampled")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/adaptiveSampling/enabled", self._on_change)
if self._settings.get("/rtx/pathtracing/adaptiveSampling/enabled"):
self._add_setting(SettingType.FLOAT, " Target Error", "/rtx/pathtracing/adaptiveSampling/targetError", 0.00001, 1, tooltip="\nThe noise value treshold after which the pixel would no longer be sampled.")
ui.Line()
self._add_setting(SettingType.INT, "Max Bounces", "/rtx/pathtracing/maxBounces", 0, 64, tooltip="\nMaximum number of ray bounces for any ray type. Higher values give more accurate results, but worse performance.")
self._add_setting(SettingType.INT, "Max Specular and Transmission Bounces", "/rtx/pathtracing/maxSpecularAndTransmissionBounces", 1, 128, tooltip="\nMaximum number of ray bounces for specular and trasnimission.")
self._add_setting(SettingType.INT, "Max SSS Volume Scattering Bounces", "/rtx/pathtracing/maxVolumeBounces", 0, 1024, tooltip="\nMaximum number of ray bounces for SSS.")
self._add_setting(SettingType.INT, "Max Fog Scattering Bounces", "/rtx/pathtracing/ptfog/maxBounces", 1, 10, tooltip="\nMaximum number of bounces for volume scattering within a fog/sky volume.")
# self._add_setting(SettingType.BOOL, "Dome Lights: High Quality Primary Rays", "/rtx/pathtracing/domeLight/primaryRaysEvaluateDomelightMdlDirectly")
ui.Line()
# self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/pathtracing/showLights/enabled") # depreacted, use /rtx/raytracing/showLights instead
self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/pathtracing/fractionalCutoutOpacity",
tooltip="\nIf enabled, fractional cutout opacity values are treated as a measure of surface 'presence',"
"\nresulting in a translucency effect similar to alpha-blending. Path-traced mode uses stochastic"
"\nsampling based on these values to determine whether a surface hit is valid or should be skipped.")
self._add_setting(SettingType.BOOL, "Reset Accumulation on Time Change", "/rtx/resetPtAccumOnAnimTimeChange",
tooltip="\nIf enabled, rendering is restarted every time the MDL animation time changes.")
def destroy(self):
self._change_cb = None
super().destroy()
class SamplingAndCachingSettingsFrame(SettingsCollectionFrame):
""" Sampling & Caching """
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Caching", "/rtx/pathtracing/cached/enabled", tooltip="\nEnables caching path-tracing results for improved performance at the cost of some accuracy.")
self._add_setting(SettingType.BOOL, "Many-Light Sampling", "/rtx/pathtracing/lightcache/cached/enabled",
tooltip="\nEnables many-light sampling algorithm, resulting in faster rendering of scenes with many lights."
"\nThis should generally be always enabled, and is exposed as an option for debugging potential algorithm artifacts.")
self._add_setting(SettingType.BOOL, "Mesh-Light Sampling", "/rtx/pathtracing/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.")
# ui.Label("Neural Radiance Caching does not work on Multi-GPU and requires (spp=1)", alignment=ui.Alignment.CENTER)
# self._add_setting(SettingType.BOOL, "Enable Neural Radiance Cache (Experimental)", "/rtx/pathtracing/nrc/enabled")
class DenoisingSettingsFrame(SettingsCollectionFrame):
""" Denoising """
def _frame_setting_path(self):
return "/rtx/pathtracing/optixDenoiser/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "OptiX Denoiser Blend Factor", "/rtx/pathtracing/optixDenoiser/blendFactor", 0, 1, 0.001,
tooltip="\nA blend factor indicating how much to blend the denoised image with the original non-denoised image."
"\n0 shows only the denoised image, 1.0 shows the image with no denoising applied.")
self._add_setting(SettingType.BOOL, "Denoise AOVs", "/rtx/pathtracing/optixDenoiser/AOV", tooltip="\nIf enabled, the OptiX Denoiser will also denoise the AOVs.")
class NonUniformVolumesSettingsFrame(SettingsCollectionFrame):
""" Path-Traced Volume """
def _frame_setting_path(self):
return "/rtx/pathtracing/ptvol/enabled"
def _build_ui(self):
""" Path-Traced Volume """
pt_vol_tr_ops = ["Biased Ray Marching", "Ratio Tracking"]
self._add_setting_combo("Transmittance Method", "/rtx/pathtracing/ptvol/transmittanceMethod", pt_vol_tr_ops, tooltip="\nChoose between Biased Ray Marching or Ratio Tracking. Biased ray marching is the ideal option in all cases.")
self._add_setting(SettingType.INT, "Max Ray Steps (Scattering)", "/rtx/pathtracing/ptvol/maxCollisionCount", 0, 1024, 32, tooltip="\nMaximum delta tracking steps between bounces. Increase to more than 32 for highly scattering volumes like clouds.")
self._add_setting(SettingType.INT, "Max Ray Steps (Shadow)", "/rtx/pathtracing/ptvol/maxLightCollisionCount", 0, 1024, 16, tooltip="\nMaximum ratio tracking delta steps for shadow rays. Increase to more than 32 for highly scattering volumes like clouds.")
self._add_setting(SettingType.INT, "Max Non-uniform Volume Scattering Bounces", "/rtx/pathtracing/ptvol/maxBounces", 1, 1024, 1, tooltip="\nMaximum number of bounces in non-uniform volumes.")
class AOVSettingsFrame(SettingsCollectionFrame):
""" AOV Settings"""
def _build_ui(self):
""" AOV Settings """
self._add_setting(SettingType.FLOAT, "Minimum Z-Depth", "/rtx/pathtracing/zDepthMin", 0, 10000, 1)
self._add_setting(SettingType.FLOAT, "Maximum Z-Depth", "/rtx/pathtracing/zDepthMax", 0, 10000, 1)
self._add_setting(SettingType.BOOL, "32 Bit Depth AOV", "/rtx/pathtracing/depth32BitAov", tooltip="\nUses a 32-bit format for the depth AOV")
ui.Label("Enables AOV Preview in Debug View", alignment=ui.Alignment.CENTER)
self._add_setting(SettingType.BOOL, "Background", "/rtx/pathtracing/backgroundAOV", tooltip="\nShading of the background, such as the background resulting from rendering a Dome Light.")
self._add_setting(SettingType.BOOL, "Diffuse Filter", "/rtx/pathtracing/diffuseFilterAOV", tooltip="\nThe raw color of the diffuse texture.")
self._add_setting(SettingType.BOOL, "Direct Illumation", "/rtx/pathtracing/diAOV", tooltip="\nShading from direct paths to light sources.")
self._add_setting(SettingType.BOOL, "Global Illumination", "/rtx/pathtracing/giAOV", tooltip="\nDiffuse shading from indirect paths to light sources.")
self._add_setting(SettingType.BOOL, "Reflection", "/rtx/pathtracing/reflectionsAOV", tooltip="\nShading from indirect reflection paths to light sources.")
self._add_setting(SettingType.BOOL, "Reflection Filter", "/rtx/pathtracing/reflectionFilterAOV", tooltip="\nThe raw color of the reflection, before being multiplied for its final intensity.")
self._add_setting(SettingType.BOOL, "Refraction", "/rtx/pathtracing/refractionsAOV", tooltip="\nShading from refraction paths to light sources.")
self._add_setting(SettingType.BOOL, "Refraction Filter", "/rtx/pathtracing/refractionFilterAOV", tooltip="\nThe raw color of the refraction, before being multiplied for its final intensity.")
self._add_setting(SettingType.BOOL, "Self-Illumination", "/rtx/pathtracing/selfIllumAOV", tooltip="\nShading of the surface's own emission value.")
self._add_setting(SettingType.BOOL, "Volumes", "/rtx/pathtracing/volumesAOV", tooltip="\nShading from VDB volumes.")
self._add_setting(SettingType.BOOL, "World Normal", "/rtx/pathtracing/worldNormalsAOV", tooltip="\nThe surface's normal in world-space.")
self._add_setting(SettingType.BOOL, "World Position", "/rtx/pathtracing/worldPosAOV", tooltip="\nThe surface's position in world-space.")
self._add_setting(SettingType.BOOL, "Z-Depth", "/rtx/pathtracing/zDepthAOV", tooltip="\nThe surface's depth relative to the view position.")
class MultiMatteSettingsFrame(SettingsCollectionFrame):
def _on_multimatte_change(self, *_):
self._rebuild()
def _build_ui(self):
self._add_setting(SettingType.INT, "Channel Count:", "/rtx/pathtracing/multimatte/channelCount", 0, 24, 1,
tooltip="\nMultimatte allows rendering AOVs of meshes which have a Multimatte ID index matching a Multimatte AOV's channel index."
"\nChannel Count determines how many channels can be used, which are distributed among the Multimatte AOVs' color channels."
"\nYou can preview a Multimatte AOV by selecting one in the Debug View.")
self._change_channels = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/multimatte/channelCount", self._on_multimatte_change)
def clamp(num, min_value, max_value):
return max(min(num, max_value), min_value)
value = self._settings.get("/rtx/pathtracing/multimatte/channelCount")
channelCount = clamp(self._settings.get("/rtx/pathtracing/multimatte/channelCount"), 0, 24) if value is not None else 0
if channelCount != 0:
mapCount = math.ceil(channelCount / 3)
channelIndex = 0
for i in range(0, mapCount):
ui.Label("Multimatte" + str(i), alignment=ui.Alignment.CENTER)
self._add_setting(SettingType.INT, "Red Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the red channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
self._add_setting(SettingType.INT, "Green Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the green channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
self._add_setting(SettingType.INT, "Blue Channel Multimatte ID Index", "/rtx/pathtracing/multimatte/channel" + str(channelIndex), -1, 1000000, 1, tooltip="\nThe Multimatte ID index to match for the blue channel of this Multimatte AOV.")
channelIndex += 1
if channelIndex >= channelCount:
break
# self._add_setting(SettingType.BOOL, "is material ID " + str(i), "/rtx/pathtracing/multimatte/channel" + str(i) + "_isMat")
def destroy(self):
self._change_channels = None
super().destroy()
class MultiGPUSettingsFrame(SettingsCollectionFrame):
""" Multi-GPU """
def _frame_setting_path(self):
return "/rtx/pathtracing/mgpu/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Auto Load Balancing","/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", tooltip="\nAutomatically balance the amount of total path-tracing work to be performed by each GPU in a multi-GPU configuration.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled", self._on_change)
if not self._settings.get("/rtx/pathtracing/mgpu/autoLoadBalancing/enabled") :
self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/pathtracing/mgpu/weightGpu0", 0, 1, 0.001,
tooltip="\nThe amount of total Path-Tracing work (between 0 and 1) to be performed by the first GPU in a Multi-GPU configuration."
"\nA value of 1 means the first GPU will perform the same amount of work assigned to any other GPU.")
self._add_setting(SettingType.BOOL, "Compress Radiance", "/rtx/pathtracing/mgpu/compressRadiance", tooltip="Enables lossy compression of per-pixel output radiance values.")
self._add_setting(SettingType.BOOL, "Compress Albedo", "/rtx/pathtracing/mgpu/compressAlbedo", tooltip="Enables lossy compression of per-pixel output albedo values (needed by OptiX denoiser).")
self._add_setting(SettingType.BOOL, "Compress Normals", "/rtx/pathtracing/mgpu/compressNormals", tooltip="Enables lossy compression of per-pixel output normal values (needed by OptiX denoiser).")
self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="Enabling multi-threading improves UI responsiveness.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" PT Only Global Volumetric Effects Settings"""
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Rayleigh Atmosphere", "/rtx/pathtracing/ptvol/raySky", tooltip="\nEnables an additional medium of Rayleigh-scattering particles to simulate a physically-based sky.")
self._change_cb = omni.kit.app.SettingChangeSubscription("/rtx/pathtracing/ptvol/raySky", self._on_change)
if self._settings.get("/rtx/pathtracing/ptvol/raySky"):
self._add_setting(SettingType.FLOAT, " Rayleigh Atmosphere Scale", "/rtx/pathtracing/ptvol/raySkyScale", 0.01, 100, 1, tooltip="\nScales the size of the Rayleigh sky.")
self._add_setting(SettingType.BOOL, " Skip Background", "/rtx/pathtracing/ptvol/raySkyDomelight",
tooltip="\nIf a domelight is rendered for the sky color, the Rayleight Atmosphere is applied to the"
"\nforeground while the background sky color is left unaffected.")
def destroy(self):
self._change_cb = None
super().destroy()
class PTSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
PathTracingSettingsFrame("Path-Tracing", parent=self)
SamplingAndCachingSettingsFrame("Sampling & Caching", parent=self)
AntiAliasingSettingsFrame("Anti-Aliasing", parent=self)
FireflyFilterSettingsFrame("Firefly Filtering", parent=self)
DenoisingSettingsFrame("Denoising", parent=self)
NonUniformVolumesSettingsFrame("Non-uniform Volumes", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
AOVSettingsFrame("AOV", parent=self)
MultiMatteSettingsFrame("Multi Matte", parent=self)
gpu_count = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount") or 0
if gpu_count > 1:
MultiGPUSettingsFrame("Multi-GPU", parent=self)
| 18,001 | Python | 79.366071 | 279 | 0.70135 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/widgets/rt_widgets.py | import omni.kit.app
import omni.ui as ui
import carb.settings
from omni.kit.widget.settings import SettingType
from omni.rtx.window.settings.rtx_settings_stack import RTXSettingsStack
from omni.rtx.window.settings.settings_collection_frame import SettingsCollectionFrame
DEBUG_OPTIONS = False
sampled_lighting_spp_items = {"1": 1, "2": 2, "4": 4, "8": 8}
class EcoMode(SettingsCollectionFrame):
""" ECO Mode """
def _frame_setting_path(self):
return "/rtx/ecoMode/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Stop Rendering After This Many Frames Without Changes", "/rtx/ecoMode/maxFramesWithoutChange", 0, 100)
class AntiAliasingSettingsFrame(SettingsCollectionFrame):
""" DLSS """
def _on_antialiasing_change(self, *_):
self._rebuild()
def _build_ui(self):
# Note: order depends on rtx::postprocessing::AntialiasingMethod
antialiasing_ops = dict()
if self._settings.get("/rtx-transient/post/dlss/supported") is True:
antialiasing_ops["DLSS"] = 3
antialiasing_ops["DLAA"] = 4
if self._settings.get("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270"):
self._add_setting(SettingType.BOOL, "Frame Generation", "/rtx-transient/dlssg/enabled",
tooltip="\nDLSS Frame Generation boosts performance by using AI to generate more frames."
"\nDLSS analyzes sequential frames and motion data to create additional high quality frames. This feature requires an Ada Lovelace architecture GPU.")
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx-transient/hashed/995bcbda752ace40e33a4d131067d270", self._on_antialiasing_change)
self._add_setting(SettingType.BOOL, "Ray Reconstruction", "/rtx/newDenoiser/enabled", tooltip="\nDLSS Ray Reconstruction enhances image quality for ray-traced scenes with an NVIDIA"
"\nsupercomputer-trained AI network that generates higher-quality pixels in between sampled rays.")
self._add_setting_combo("Super Resolution", "/rtx/post/aa/op", antialiasing_ops, tooltip="\nDLSS Super Resolution boosts performance by using AI to output higher resolution frames from a lower resolution input."
"\nDLSS samples multiple lower resolution images and uses motion data and feedback from prior frames to reconstruct native quality images.")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/op", self._on_antialiasing_change)
antialiasingOpIdx = self._settings.get("/rtx/post/aa/op")
exposure_ops = {
"Force self evaluated" : 0,
"PostProcess Autoexposure" : 1,
"Fixed" : 2
}
if antialiasingOpIdx == 1:
""" TAA """
self._add_setting(SettingType.FLOAT, "Static scaling", "/rtx/post/scaling/staticRatio", 0.33, 1, 0.01)
self._add_setting(SettingType.INT, "TAA Samples", "/rtx/post/taa/samples", 1, 16)
self._add_setting(SettingType.FLOAT, "TAA history scale", "/rtx/post/taa/alpha", 0, 1, 0.1)
elif antialiasingOpIdx == 2:
""" FXAA """
self._add_setting(SettingType.FLOAT, "Subpixel Quality", "/rtx/post/fxaa/qualitySubPix", 0.0, 1.0, 0.02)
self._add_setting(SettingType.FLOAT, "Edge Threshold", "/rtx/post/fxaa/qualityEdgeThreshold", 0.0, 1.0, 0.02)
self._add_setting(SettingType.FLOAT, "Edge Threshold Min", "/rtx/post/fxaa/qualityEdgeThresholdMin", 0.0, 1.0, 0.02)
elif antialiasingOpIdx == 3 or antialiasingOpIdx == 4:
""" DLSS and DLAA """
if antialiasingOpIdx == 3:
# needs to be in sync with DLSSMode enum
dlss_opts = {"Auto": 3, "Performance": 0, "Balanced": 1, "Quality": 2}
self._add_setting_combo(" Mode", "/rtx/post/dlss/execMode", dlss_opts, tooltip="\nAuto: Selects the best DLSS Mode for the current output resolution.\nPerformance: Higher performance than balanced mode.\nBalanced: Balanced for optimized performance and image quality.\nQuality: Higher image quality than balanced mode.")
self._add_setting(SettingType.FLOAT, " Sharpness", "/rtx/post/aa/sharpness", 0.0, 1.0, 0.5, tooltip="\nHigher values produce sharper results.")
self._add_setting_combo(" Exposure Mode", "/rtx/post/aa/autoExposureMode", exposure_ops, tooltip="\nChoose between Force self evaluated, PostProcess AutoExposure, Fixed.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/post/aa/autoExposureMode", self._on_antialiasing_change)
autoExposureIdx = self._settings.get("/rtx/post/aa/autoExposureMode")
if autoExposureIdx == 1:
self._add_setting(SettingType.FLOAT, " Auto Exposure Multiplier", "/rtx/post/aa/exposureMultiplier", 0.00001, 10.0, 0.00001, tooltip="\nFactor with which to multiply the selected exposure mode.")
elif autoExposureIdx == 2:
self._add_setting(SettingType.FLOAT, " Fixed Exposure Value", "/rtx/post/aa/exposure", 0.00001, 1.0, 0.00001)
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
super().destroy()
class DirectLightingSettingsFrame(SettingsCollectionFrame):
""" Direct Lighting """
def _frame_setting_path(self):
return "/rtx/directLighting/enabled"
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/autoEnable", self._on_change)
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/domeLight/enabled", self._on_change)
self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change)
self._change_cb5 = omni.kit.app.SettingChangeSubscription("/rtx/shadows/enabled", self._on_change)
self._add_setting(SettingType.BOOL, "Shadows", "/rtx/shadows/enabled", tooltip="\nWhen disabled, lights will not cast shadows.")
self._add_setting(SettingType.BOOL, "Sampled Direct Lighting Mode", "/rtx/directLighting/sampledLighting/enabled", tooltip="\nMode which favors performance with many lights (10 or more), at the cost of image quality.")
self._add_setting(SettingType.BOOL, "Auto-enable Sampled Direct Lighting Above Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnable", tooltip="\nAutomatically enables Sampled Direct Lighting when the light count is greater than the Light Count Threshold.")
if self._settings.get("/rtx/directLighting/sampledLighting/autoEnable"):
self._add_setting(SettingType.INT, " Light Count Threshold", "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold", tooltip="\nLight count threshold above which Sampled Direct Lighting is automatically enabled.")
if not self._settings.get("/rtx/directLighting/sampledLighting/enabled"):
with ui.CollapsableFrame("Non-Sampled Lighting Settings", height=0):
with ui.VStack(height=0, spacing=5):
if self._settings.get("/rtx/shadows/enabled"):
self._add_setting(SettingType.INT, " Shadow Samples per Pixel", "/rtx/shadows/sampleCount", 1, 16, tooltip="\nHigher values increase the quality of shadows at the cost of performance.")
if not self._settings.get("/rtx/newDenoiser/enabled"):
self._add_setting(SettingType.BOOL, " Low Resolution Shadow Denoiser", "/rtx/shadows/denoiser/quarterRes", tooltip="\nReduces the shadow denoiser resolution to gain performance at the cost of quality.")
self._add_setting(SettingType.BOOL, " Dome Lighting", "/rtx/directLighting/domeLight/enabled", tooltip="\nEnables dome light contribution to diffuse BSDFs if Dome Light mode is IBL.")
if self._settings.get("/rtx/directLighting/domeLight/enabled"):
self._add_setting(SettingType.BOOL, " Dome Lighting in Reflections", "/rtx/directLighting/domeLight/enabledInReflections", tooltip="\nEnables Dome Light sampling in reflections at the cost of performance.")
self._add_setting(SettingType.INT, " Dome Light Samples per Pixel", "/rtx/directLighting/domeLight/sampleCount", 0, 32, tooltip="\nHigher values increase dome light sampling quality at the cost of performance.")
else:
with ui.CollapsableFrame("Sampled Direct Lighting Settings", height=0):
with ui.VStack(height=0, spacing=5):
self._add_setting_combo(" Samples per Pixel", "/rtx/directLighting/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the direct lighting quality at the cost of performance.")
# self._add_setting(SettingType.BOOL, "Clamp Sample Count to Light Count", "/rtx/directLighting/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Samples per Pixel\" to the number of lights in the scene")
self._add_setting(SettingType.FLOAT, " Max Ray Intensity", "/rtx/directLighting/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.")
# self._add_setting(SettingType.BOOL, "Reflections: Clamp Sample Count to Light Count", "/rtx/reflections/sampledLighting/clampSamplesPerPixelToNumberOfLights", tooltip="\n\t When enabled, clamps the \"Reflections: Light Samples per Pixel\" to the number of lights in the scene")
self._add_setting_combo(" Reflections: Light Samples per Pixel", "/rtx/reflections/sampledLighting/samplesPerPixel", sampled_lighting_spp_items, tooltip="\nHigher values increase the reflections quality at the cost of performance.")
self._add_setting(SettingType.FLOAT, " Reflections: Max Ray Intensity", "/rtx/reflections/sampledLighting/maxRayIntensity", 0.0, 1000000, 100, tooltip="\nClamps the brightness of a sample, which helps reduce fireflies, but may result in some loss of energy.")
if not self._settings.get("/rtx/newDenoiser/enabled"):
firefly_filter_types = {"None" : "None", "Median" : "Cross-Bilateral Median", "RCRS" : "Cross-Bilateral RCRS"}
self._add_setting_combo(" Firefly Filter", "/rtx/lightspeed/ReLAX/fireflySuppressionType", firefly_filter_types, tooltip="\nChoose the filter type (None, Median, RCRS). Clamps overly bright pixels to a maximum value.")
self._add_setting(SettingType.BOOL, " History Clamping", "/rtx/lightspeed/ReLAX/historyClampingEnabled", tooltip="\nReduces temporal lag.")
self._add_setting(SettingType.INT, " Denoiser Iterations", "/rtx/lightspeed/ReLAX/aTrousIterations", 1, 10, tooltip="\nNumber of times the frame is denoised.")
# disabled with macro in the .hlsl as was causing extra spills & wasnt really used at all
# self._add_setting(SettingType.BOOL, "Enable Extended Diffuse Backscattering", "/rtx/directLighting/diffuseBackscattering/enabled")
# self._add_setting(SettingType.FLOAT, "Shadow Ray Offset", "/rtx/directLighting/diffuseBackscattering/shadowOffset", 0.1, 1000, 0.5)
# self._add_setting(SettingType.FLOAT, "Extinction", "/rtx/directLighting/diffuseBackscattering/extinction", 0.001, 100, 0.01)
self._add_setting(SettingType.BOOL, " Mesh-Light Sampling", "/rtx/directLighting/sampledLighting/ris/meshLights", tooltip="\nEnables direct illumination sampling of geometry with emissive materials.")
# Hiding this to simplify things for now. Will be auto-enabled if /rtx/raytracing/fractionalCutoutOpacity is enabled
# self._add_setting(SettingType.BOOL, "Enable Fractional Opacity", "/rtx/shadows/fractionalCutoutOpacity")
# self._add_setting(SettingType.BOOL, "Show Lights", "/rtx/directLighting/showLights") #deprecated, use /rtx/raytracing/showLights
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
self._change_cb4 = None
self._change_cb5 = None
super().destroy()
class ReflectionsSettingsFrame(SettingsCollectionFrame):
""" Reflections """
def _frame_setting_path(self):
return "/rtx/reflections/enabled"
def _build_ui(self):
self._add_setting(SettingType.FLOAT, "Roughness Cache Threshold", "/rtx/reflections/maxRoughness", 0.0, 1.0, 0.02, tooltip="\nRoughness threshold for approximated reflections. Higher values result in better quality, at the cost of performance.")
self._add_setting(SettingType.INT, "Max Reflection Bounces", "/rtx/reflections/maxReflectionBounces", 0, 100, tooltip="\nNumber of bounces for reflection rays.")
class TranslucencySettingsFrame(SettingsCollectionFrame):
""" Translucency (Refraction) """
def _frame_setting_path(self):
return "/rtx/translucency/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Max Refraction Bounces", "/rtx/translucency/maxRefractionBounces", 0, 100, tooltip="\nNumber of bounces for refraction rays.")
self._add_setting(SettingType.BOOL, "Reflection Seen Through Refraction", "/rtx/translucency/reflectAtAllBounce", tooltip="\n\t When enabled, reflection seen through refraction is rendered. When disabled, reflection is limited to first bounce only. More accurate, but worse performance")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/translucency/reflectAtAllBounce", self._on_change)
if self._settings.get("/rtx/translucency/reflectAtAllBounce"):
self._add_setting(SettingType.FLOAT, "Secondary Bounce Reflection Throughput Threshold", "/rtx/translucency/reflectionThroughputThreshold", 0.0, 1.0, 0.005, tooltip="\nThreshold below which reflection paths due to fresnel are no longer traced. Lower values result in higher quality at the cost of performance.")
self._add_setting(SettingType.BOOL, "Fractional Cutout Opacity", "/rtx/raytracing/fractionalCutoutOpacity", tooltip="\nEnables fractional cutout opacity values resulting in a translucency-like effect similar to alpha-blending.")
self._add_setting(SettingType.BOOL, "Depth Correction for DoF", "/rtx/translucency/virtualDepth", tooltip="\nImproves DoF for translucent (refractive) objects, but can result in worse performance.")
self._add_setting(SettingType.BOOL, "Motion Vector Correction (experimental)", "/rtx/translucency/virtualMotion", tooltip="\nEnables motion vectors for translucent (refractive) objects, which can improve temporal rendering such as denoising, but can result in worse performance.")
self._add_setting(SettingType.FLOAT, "World Epsilon Threshold", "/rtx/translucency/worldEps", 0.0001, 5, 0.01, tooltip="\nTreshold below which image-based reprojection is used to compute refractions. Lower values result in higher quality at the cost performance.")
self._add_setting(SettingType.BOOL, "Roughness Sampling (experimental)", "/rtx/translucency/sampleRoughness", tooltip="\nEnables sampling roughness, such as for simulating frosted glass, but can result in worse performance.")
def destroy(self):
self._change_cb1 = None
super().destroy()
class CausticsSettingsFrame(SettingsCollectionFrame):
""" Caustics """
def _frame_setting_path(self):
return "/rtx/caustics/enabled"
def _build_ui(self):
self._add_setting(SettingType.INT, "Photon Count Multiplier", "/rtx/raytracing/caustics/photonCountMultiplier", 1, 5000, tooltip="\nFactor multiplied by 1024 to compute the total number of photons to generate from each light.")
self._add_setting(SettingType.INT, "Photon Max Bounces", "/rtx/raytracing/caustics/photonMaxBounces", 1, 20, tooltip="\nMaximum number of bounces to compute for each light/photon path.")
self._add_setting(SettingType.FLOAT, "Position Phi", "/rtx/raytracing/caustics/positionPhi", 0.1, 50)
self._add_setting(SettingType.FLOAT, "Normal Phi", "/rtx/raytracing/caustics/normalPhi", 0.3, 1)
self._add_setting(SettingType.INT, "Filter Iterations", "/rtx/raytracing/caustics/eawFilteringSteps", 0, 10, tooltip="\nNumber of iterations for the denoiser applied to the results of the caustics tracing pass.")
class IndirectDiffuseLightingSettingsFrame(SettingsCollectionFrame):
def _on_denoiser_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/ambientOcclusion/enabled", self._on_change)
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/enabled", self._on_change)
self._change_cb3 = omni.kit.app.SettingChangeSubscription("/rtx/indirectDiffuse/denoiser/method", self._on_change)
self._change_cb4 = omni.kit.app.SettingChangeSubscription("/rtx/newDenoiser/enabled", self._on_change)
self._add_setting(SettingType.BOOL, "Indirect Diffuse GI", "/rtx/indirectDiffuse/enabled", tooltip="\nEnables indirect diffuse GI sampling.")
if self._settings.get("/rtx/indirectDiffuse/enabled"):
gi_denoising_techniques_ops = ["NVRTD", "NRD:Reblur"]
self._add_setting(SettingType.INT, " Samples Per Pixel", "/rtx/indirectDiffuse/fetchSampleCount", 0, 4, tooltip="\nNumber of samples made for indirect diffuse GI. Higher number gives better GI quality, but worse performance.")
self._add_setting(SettingType.INT, " Max Bounces", "/rtx/indirectDiffuse/maxBounces", 0, 16, tooltip="\nNumber of bounces approximated with indirect diffuse GI.")
self._add_setting(SettingType.FLOAT, " Intensity", "/rtx/indirectDiffuse/scalingFactor", 0.0, 20.0, 0.1, tooltip="\nMultiplier for the indirect diffuse GI contribution.")
self._add_setting_combo(" Denoising Mode", "/rtx/indirectDiffuse/denoiser/method", gi_denoising_techniques_ops)
if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 0:
self._add_setting(SettingType.INT, " Kernel Radius", "/rtx/indirectDiffuse/denoiser/kernelRadius", 1, 64, tooltip="\nControls the spread of local denoising area. Higher values results in smoother GI.")
self._add_setting(SettingType.INT, " Iteration Count", "/rtx/indirectDiffuse/denoiser/iterations", 1, 10, tooltip="\nThe number of denoising passes. Higher values results in smoother looking GI.")
self._add_setting(SettingType.INT, " Max History Length", "/rtx/indirectDiffuse/denoiser/temporal/maxHistory", 1, 100, tooltip="\nControls latency in GI updates. Higher values results in smoother looking GI.")
if self._settings.get("/rtx/indirectDiffuse/denoiser/method") == 1:
self._add_setting(SettingType.INT, " Frames In History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxAccumulatedFrameNum", 0, 63)
self._add_setting(SettingType.INT, " Frames In Fast History", "/rtx/lightspeed/NRD_ReblurDiffuse/maxFastAccumulatedFrameNum", 0, 63)
self._add_setting(SettingType.FLOAT, " Plane Distance Sensitivity", "/rtx/lightspeed/NRD_ReblurDiffuse/planeDistanceSensitivity", 0, 1, 0.01)
self._add_setting(SettingType.FLOAT, " Blur Radius", "/rtx/lightspeed/NRD_ReblurDiffuse/blurRadius", 0, 100, 5)
self._add_setting(SettingType.BOOL, "Ambient Occlusion", "/rtx/ambientOcclusion/enabled", tooltip="\nEnables ambient occlusion.")
if self._settings.get("/rtx/ambientOcclusion/enabled"):
self._add_setting(SettingType.FLOAT, " Ray Length (cm)", "/rtx/ambientOcclusion/rayLength", 0.0, 2000.0, tooltip="\nThe radius around the intersection point which the ambient occlusion affects.")
self._add_setting(SettingType.INT, " Minimum Samples Per Pixel", "/rtx/ambientOcclusion/minSamples", 1, 16, tooltip="\nMinimum number of samples per frame for ambient occlusion sampling.")
self._add_setting(SettingType.INT, " Maximum Samples Per Pixel", "/rtx/ambientOcclusion/maxSamples", 1, 16, tooltip="\nMaximum number of samples per frame for ambient occlusion sampling.")
aoDenoiserMode = {
"None" : 0,
"Aggressive" : 1,
"Simple" : 2,
}
if not self._settings.get("/rtx/newDenoiser/enabled"):
self._add_setting_combo(" Denoiser", "/rtx/ambientOcclusion/denoiserMode", aoDenoiserMode, tooltip="\nAllows for increased AO denoising at the cost of more blurring.")
self._add_setting(SettingType.COLOR3, "Ambient Light Color", "/rtx/sceneDb/ambientLightColor", tooltip="\nColor of the global environment lighting.")
self._add_setting(SettingType.FLOAT, "Ambient Light Intensity", "/rtx/sceneDb/ambientLightIntensity", 0.0, 10.0, 0.1, tooltip="\nBrightness of the global environment lighting.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
self._change_cb3 = None
self._change_cb4 = None
super().destroy()
class RTMultiGPUSettingsFrame(SettingsCollectionFrame):
""" Multi-GPU """
def _frame_setting_path(self):
return "/rtx/realtime/mgpu/enabled"
def _build_ui(self):
self._add_setting(SettingType.BOOL, "Automatic Tiling", "/rtx/realtime/mgpu/autoTiling/enabled",
tooltip="\nAutomatically determines the image-space grid used to distribute rendering to available GPUs."
"\nThe image rendering is split into a large tile per GPU with a small overlap region between them."
"\nNote that by default not necessarily all GPUs are used. The approximate number of tiles is viewport"
"\nresolution divided by the Minimum Megapixels Per Tile setting, since at low resolution small tiles distributed"
"\nacross too many devices decreases performance due to multi-GPU overheads."
"\nDisable automatic tiling to manually specify the number of tiles to be distributed across devices.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/realtime/mgpu/autoTiling/enabled", self._on_change)
if self._settings.get("/rtx/realtime/mgpu/autoTiling/enabled"):
self._add_setting(SettingType.FLOAT, " Minimum Megapixels Per Tile", "/rtx/realtime/mgpu/autoTiling/minMegaPixelsPerTile", 0.1, 2.0, 0.1, tooltip="\nThe minimum number of Megapixels each tile should have after screen-space subdivision.")
else:
currentGpuCount = self._settings.get("/renderer/multiGpu/currentGpuCount")
self._add_setting(SettingType.INT, "Tile Count", "/rtx/realtime/mgpu/tileCount", 2, currentGpuCount, tooltip="\nNumber of tiles to split the image into. Usually this should match the number of GPUs, but can be less.")
self._add_setting(SettingType.INT, "Tile Overlap (Pixels)", "/rtx/realtime/mgpu/tileOverlap", 0, 256, 0.1, tooltip="\nWidth, in pixels, of the overlap region between any two neighboring tiles.")
self._add_setting(SettingType.FLOAT, "GPU 0 Weight", "/rtx/realtime/mgpu/masterDeviceLoadBalancingWeight", 0, 1, 0.001,
tooltip="\nThis normalized weight can be used to decrease the rendering workload on the primary device for each viewport"
"\nin relation to the other secondary devices, which can be helpful for load balancing in situations where the primary"
"\ndevice also needs to perform additional expensive operations such as denoising and post-processing.")
self._add_setting(SettingType.BOOL, "Multi-Threading", "/rtx/multiThreading/enabled", tooltip="\nExecute per-device render command recording in separate threads.")
class SubsurfaceScatteringSettingsFrame(SettingsCollectionFrame):
""" Subsurface Scattering """
def _frame_setting_path(self):
return "/rtx/raytracing/subsurface/enabled"
def _on_change(self, *_):
self._rebuild()
def _build_ui(self):
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/directLighting/sampledLighting/enabled", self._on_change)
self._add_setting(SettingType.INT, "Max Samples Per Frame", "/rtx/raytracing/subsurface/maxSamplePerFrame", 1, 128, tooltip="\nMax samples per frame for the infinitely-thick geometry SSS approximation.")
# self._add_setting(SettingType.FLOAT, "History Weight", "/rtx/raytracing/subsurface/historyWeight", 0.001, 0.5, 0.02)
# self._add_setting(SettingType.FLOAT, "Variance Threshold", "/rtx/raytracing/subsurface/targetVariance", 0.001, 1, 0.05)
# self._add_setting(SettingType.FLOAT, "World space sample projection Threshold", "/rtx/raytracing/subsurface/shadowRayThreshold", 0, 1, 0.01)
self._add_setting(SettingType.BOOL, "Firefly Filtering", "/rtx/raytracing/subsurface/fireflyFiltering/enabled", tooltip="\nEnables firefly filtering for the subsurface scattering. The maximum filter intensity is determined by '/rtx/directLighting/sampledLighting/maxRayIntensity'.")
self._add_setting(SettingType.BOOL, "Denoiser", "/rtx/raytracing/subsurface/denoiser/enabled", tooltip="\nEnables denoising for the subsurface scattering.")
if self._settings.get("/rtx/directLighting/sampledLighting/enabled"):
self._add_setting(SettingType.BOOL, "Denoise Irradiance Input", "/rtx/directLighting/sampledLighting/irradiance/denoiser/enabled",
tooltip="\nDenoise the irradiance output from sampled lighting pass before it's used, helps in complex lighting conditions"
"\nor if there are large area lights which makes irradiance estimation difficult with low sampled lighting sample count.")
self._add_setting(SettingType.BOOL, "Transmission", "/rtx/raytracing/subsurface/transmission/enabled", tooltip="\nEnables transmission of light through the medium, but requires additional samples and denoising.")
self._change_cb2 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/subsurface/transmission/enabled", self._on_change)
if self._settings.get("/rtx/raytracing/subsurface/transmission/enabled"):
self._add_setting(SettingType.INT, " BDSF Sample Count", "/rtx/raytracing/subsurface/transmission/bsdfSampleCount", 0, 8, tooltip="\nTransmission sample count per frame.")
self._add_setting(SettingType.INT, " Samples Per BSDF Sample", "/rtx/raytracing/subsurface/transmission/perBsdfScatteringSampleCount", 0, 16, tooltip="\nTransmission samples count per BSDF Sample. Samples per pixel per frame = BSDF Sample Count * Samples Per BSDF Sample.")
self._add_setting(SettingType.FLOAT, " Screen-Space Fallback Threshold", "/rtx/raytracing/subsurface/transmission/screenSpaceFallbackThresholdScale", 0.0001, 1, tooltip="\nTransmission threshold for screen-space fallback.")
self._add_setting(SettingType.BOOL, " Half-Resolution Rendering", "/rtx/raytracing/subsurface/transmission/halfResolutionBackfaceLighting", tooltip="\nEnables rendering transmission in half-resolution to improve performance at the expense of quality.")
self._add_setting(SettingType.BOOL, " Sample Guiding", "/rtx/raytracing/subsurface/transmission/ReSTIR/enabled", tooltip="\nEnables transmission sample guiding, which may help with complex lighting scenarios.")
self._add_setting(SettingType.BOOL, " Denoiser", "/rtx/raytracing/subsurface/transmission/denoiser/enabled", tooltip="\nEnables transmission denoising.")
def destroy(self):
self._change_cb1 = None
self._change_cb2 = None
super().destroy()
class GlobalVolumetricEffectsSettingsFrame(SettingsCollectionFrame):
""" RT Only Global Volumetric Effects Settings"""
def _build_ui(self):
self._add_setting(SettingType.INT, "Accumulation Frames", "/rtx/raytracing/inscattering/maxAccumulationFrames", 0, 256, tooltip="\nNumber of frames samples accumulate over temporally. High values reduce noise, but increase lighting update times.")
self._add_setting(SettingType.INT, "Depth Slices Count", "/rtx/raytracing/inscattering/depthSlices", 16, 1024, tooltip="\nNumber of layers in the voxel grid to be allocated. High values result in higher precision at the cost of memory and performance.")
self._add_setting(SettingType.INT, "Pixel Density", "/rtx/raytracing/inscattering/pixelRatio", 4, 64, tooltip="\nLower values result in higher fidelity volumetrics at the cost of performance and memory (depending on the # of depth slices).")
self._add_setting(SettingType.FLOAT, "Slice Distribution Exponent", "/rtx/raytracing/inscattering/sliceDistributionExponent", 1, 16, tooltip="\nControls the number (and relative thickness) of the depth slices.")
self._add_setting(SettingType.INT, "Inscatter Upsample", "/rtx/raytracing/inscattering/inscatterUpsample", 1, 64, tooltip="\n")
self._add_setting(SettingType.FLOAT, "Inscatter Blur Sigma", "/rtx/raytracing/inscattering/blurSigma", 0.0, 10.0, 0.01, tooltip="\nSigma parameter for the Gaussian filter used to spatially blur the voxel grid. 1 = no blur, higher values blur further.")
self._add_setting(SettingType.FLOAT, "Inscatter Dithering Scale", "/rtx/raytracing/inscattering/ditheringScale", 0, 10000, tooltip="\nThe scale of the noise dithering. Used to reduce banding from quantization on smooth gradients.")
self._add_setting(SettingType.FLOAT, "Spatial Sample Jittering Scale", "/rtx/raytracing/inscattering/spatialJitterScale", 0.0, 1, 0.0001, tooltip="\nScales how far light samples within a voxel are spatially jittered: 0 = only from the center, 1 = the entire voxel's volume.")
self._add_setting(SettingType.FLOAT, "Temporal Reprojection Jittering Scale", "/rtx/raytracing/inscattering/temporalJitterScale", 0.0, 1, 0.0001,
tooltip="\nScales how far to offset temporally-reprojected samples within a voxel: 0 = only from the center, 1 = the entire voxel's volume."
"\nActs like a temporal blur and helps reduce noise under motion.")
self._add_setting(SettingType.BOOL, "Use 32-bit Precision", "/rtx/raytracing/inscattering/use32bitPrecision", tooltip="\nAllocate the voxel grid with 32-bit per channel color instead of 16-bit. This doubles memory usage and reduces performance, generally avoided.")
self._add_setting(SettingType.BOOL, "Flow Sampling", "/rtx/raytracing/inscattering/enableFlowSampling", tooltip="\n")
self._change_cb1 = omni.kit.app.SettingChangeSubscription("/rtx/raytracing/inscattering/enableFlowSampling", self._on_change)
if self._settings.get("/rtx/raytracing/inscattering/enableFlowSampling"):
self._add_setting(SettingType.INT, " Min Layer", "/rtx/raytracing/inscattering/minFlowLayer", 0, 64, tooltip="\n")
self._add_setting(SettingType.INT, " Max Layer", "/rtx/raytracing/inscattering/maxFlowLayer", 0, 64, tooltip="\n")
self._add_setting(SettingType.FLOAT, " Density Scale", "/rtx/raytracing/inscattering/flowDensityScale", 0.0, 100.0, tooltip="\n")
self._add_setting(SettingType.FLOAT, " Density Offset", "/rtx/raytracing/inscattering/flowDensityOffset", 0.0, 100.0, tooltip="\n")
def destroy(self):
self._change_cb1 = None
super().destroy()
class RTSettingStack(RTXSettingsStack):
def __init__(self) -> None:
self._stack = ui.VStack(spacing=7, identifier=__class__.__name__)
with self._stack:
EcoMode("Eco Mode", parent=self)
AntiAliasingSettingsFrame("NVIDIA DLSS", parent=self)
DirectLightingSettingsFrame("Direct Lighting", parent=self)
IndirectDiffuseLightingSettingsFrame("Indirect Diffuse Lighting", parent=self)
ReflectionsSettingsFrame("Reflections", parent=self)
translucency = TranslucencySettingsFrame("Translucency", parent=self)
SubsurfaceScatteringSettingsFrame("Subsurface Scattering", parent=translucency)
CausticsSettingsFrame("Caustics", parent=self)
GlobalVolumetricEffectsSettingsFrame("Global Volumetric Effects", parent=self)
gpuCount = carb.settings.get_settings().get("/renderer/multiGpu/currentGpuCount")
if gpuCount and gpuCount > 1:
RTMultiGPUSettingsFrame("Multi-GPU", parent=self)
| 33,283 | Python | 90.189041 | 338 | 0.698314 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/__init__.py | from .test_settings import TestRTXCoreSettingsUI | 49 | Python | 48.999951 | 49 | 0.877551 |
omniverse-code/kit/exts/omni.rtx.settings.core/omni/rtx/settings/core/tests/test_settings.py |
import carb
import omni.kit.test
import omni.usd
import tempfile
import pathlib
import rtx.settings
from omni.kit import ui_test
from omni.rtx.tests.test_common import wait_for_update
settings = carb.settings.get_settings()
EXTENSION_FOLDER_PATH = pathlib.Path(omni.kit.app.get_app().get_extension_manager().get_extension_path_by_module(__name__))
USD_DIR = EXTENSION_FOLDER_PATH.joinpath("data/usd")
class TestRTXCoreSettingsUI(omni.kit.test.AsyncTestCase):
VALUE_EPSILON = 0.00001
async def setUp(self):
super().setUp()
# We need to trigger Iray load to get the default render-settings values written to carb.settings
# Viewports state is valid without any open stage, and only loads renderer when stage is opened.
await omni.usd.get_context().new_stage_async()
await omni.kit.app.get_app().next_update_async()
# After running each test
async def tearDown(self):
omni.kit.window.property.managed_frame.reset_collapsed_state()
def get_render_setings_window(self):
render_settings_window = ui_test.find("Render Settings")
render_settings_window.widget.height = 1200
render_settings_window.widget.width = 600
render_settings_window.widget.visible = True
return render_settings_window
def set_renderer(self, render_settings_window, index):
#select the combo box item
box = render_settings_window.find("Frame/VStack[0]/HStack[0]/ComboBox[*]")
box.model.get_item_value_model(None, 0).set_value(index)
def compare_floats(self, a, b, epsilon):
self.assertEqual(len(a), len(b))
for i in range(0, len(a)):
self.assertLessEqual(
abs(a[i] - b[i]), epsilon, "a[" + str(i) + "] = " + str(a[i]) + ", b[" + str(i) + "] = " + str(b[i])
)
def compare_float(self, a, b, epsilon):
self.assertLessEqual(abs(a - b), epsilon)
def open_usd(self, usdSubpath: pathlib.Path):
path = USD_DIR.joinpath(usdSubpath)
omni.usd.get_context().open_stage(str(path))
async def test_bool_checkbox_setting(self):
'''
check that we can switch on/off back face culling in Common/Geometry
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/hydra/faceCulling/enabled"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, False)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Geometry and open it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
#This is the back face culling hstack
back_face_culling_setting = collapsable_frame.find("/**/HStack_Back_Face_Culling")
self.assertTrue(isinstance(back_face_culling_setting.widget, omni.ui.HStack))
check_box = back_face_culling_setting.find("**/CheckBox[0]")
self.assertTrue(isinstance(check_box.widget, omni.ui.CheckBox))
await check_box.click(human_delay_speed=10)
face_culling_value = settings.get(setting_name)
self.assertTrue(face_culling_value)
await check_box.click(human_delay_speed=10)
face_culling_value = settings.get(setting_name)
self.assertFalse(face_culling_value)
async def test_combo_box_setting(self):
'''
check that we can set TBNFrame mode Combo Box in Common/Geometry
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/hydra/TBNFrameMode"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, 0)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Geometry and open it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
tangent_space_setting = collapsable_frame.find("/**/HStack_Normal_&_Tangent_Space_Generation_Mode")
self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack))
combo_box = tangent_space_setting.find("ComboBox[0]")
self.assertTrue(isinstance(combo_box.widget, omni.ui.ComboBox))
combo_box.model.get_item_value_model(None, 0).set_value(1)
tbn_frame_mode_setting = settings.get(setting_name)
self.assertTrue(tbn_frame_mode_setting == 1)
async def test_float_setting(self):
'''
check that we can set float MDL Animation Time Override in Common/Materials
'''
render_settings_window = self.get_render_setings_window()
setting_name = "/rtx/animationTime"
#Cycle through Realtime, path-tracing renders
for index in range(0, 2):
self.set_renderer(render_settings_window, index)
# Set initial value
settings.set(setting_name, -1.0)
await omni.kit.app.get_app().next_update_async()
#choose the "Common" tab in each case
button = render_settings_window.find("Frame/VStack[0]/VStack[0]/HStack[0]/RadioButton[0]")
await button.click()
#Get the collapsable frame for Materials and expand it
collapsable_frame = render_settings_window.find("**/Geometry")
collapsable_frame.widget.collapsed = True
collapsable_frame = render_settings_window.find("**/Materials")
collapsable_frame.widget.collapsed = False
await omni.kit.app.get_app().next_update_async()
tangent_space_setting = collapsable_frame.find("**/HStack_Animation_Time_Override")
self.assertTrue(isinstance(tangent_space_setting.widget, omni.ui.HStack))
slider = tangent_space_setting.find("FloatDrag[0]")
self.assertTrue(isinstance(slider.widget, omni.ui.FloatDrag))
await ui_test.human_delay(50)
await slider.input("20.0")
tbn_frame_mode_setting = settings.get(setting_name)
self.assertAlmostEqual(tbn_frame_mode_setting, 20.0, 2, f"was actually {tbn_frame_mode_setting}")
async def run_render_settings_storage_helper(self, must_save=False):
with tempfile.TemporaryDirectory() as tmpdirname:
usd_context = omni.usd.get_context()
await omni.kit.app.get_app().next_update_async()
# save the file with various types of setting value types.
# Note: if ever any of these were removed, replace them with a new setting of the same type.
setting_fog_b = "/rtx/fog/enabled" # bool
setting_meter_unit_f = "/rtx/scene/renderMeterPerUnit" # float
setting_heatmap_i = "/rtx/debugView/heatMapPass" # int
setting_max_bounce_i = "/rtx/pathtracing/maxBounces" # int, pathtracer
setting_mat_white_s = "/rtx/debugMaterialWhite" # string
setting_ambinet_arr_f = "/rtx/sceneDb/ambientLightColor" # array of float3
setting_saturation_arr_f = "/rtx/post/colorcorr/saturation" # array of double3
# settings with special kSettingFlagTransient, treated like rtx-transient.
setting_mthread_transient_b = "/rtx/multiThreading/enabled" # uses kSettingFlagTransient in C++
setting_dir_light_b = "/rtx-transient/disable/directLightingSampled" # manual transient
setting_place_col_b = "/persistent/rtx/resourcemanager/placeholderTextureColor" # persistent
# set as transient in [[test]]
setting_fog_dist_i = "/rtx/fog/fogEndDist" # int
setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float
settings.set_bool(setting_fog_b, True)
settings.set_float(setting_meter_unit_f, 0.5)
settings.set_int(setting_heatmap_i, 3)
settings.set_int(setting_max_bounce_i, 33)
settings.set_string(setting_mat_white_s, "NoActualMat") # a random non-existent material
settings.set_float_array(setting_ambinet_arr_f, [0.4, 0.5, 0.6])
settings.set_float_array(setting_saturation_arr_f, [0.7, 0.8, 0.9])
# with special flags
# Note: we can't test sync/async settings, since they are needed for the loading stage.
settings.set_bool(setting_mthread_transient_b, False)
settings.set_bool(setting_dir_light_b, True)
settings.set_float_array(setting_place_col_b, [0.4, 0.4, 0.4])
# this was set in [[test]] as transient
settings.set(setting_fog_dist_i, 999)
settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21])
# verify rtx-flags is set as transient in [[test]]
setting_fog_dist_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_dist_i);
setting_fog_color_flags = rtx.settings.get_associated_setting_flags_path(setting_fog_color_arr_f);
value_fog_dist_flags = settings.get(setting_fog_dist_flags)
value_fog_color_flags = settings.get(setting_fog_color_flags)
self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
tmp_usd_path = pathlib.Path(tmpdirname) / "tmp_rtx_setting.usd"
result = usd_context.save_as_stage(str(tmp_usd_path))
self.assertTrue(result)
stage = usd_context.get_stage()
# Make stage dirty so reload will work
stage.DefinePrim("/World", "Xform")
await omni.kit.app.get_app().next_update_async()
# Change settings
settings.set_bool(setting_fog_b, False)
settings.set_float(setting_meter_unit_f, 0.3)
settings.set_int(setting_heatmap_i, 2)
settings.set_int(setting_max_bounce_i, 9)
settings.set_string(setting_mat_white_s, "NoActualMat2") # a random non-existent material
settings.set_float_array(setting_ambinet_arr_f, [0.2, 0.2, 0.2])
settings.set_float_array(setting_saturation_arr_f, [0.3, 0.3, 0.3])
# with special flags
settings.set_bool(setting_mthread_transient_b, True)
settings.set_bool(setting_dir_light_b, False)
settings.set_float_array(setting_place_col_b, [0.6, 0.6, 0.6])
await omni.kit.app.get_app().next_update_async()
# Reload stage will reload all the rtx settings
# Reload with native API stage.Reload will not reopen settings
# but only lifecycle API in Kit.
await usd_context.reopen_stage_async()
await omni.kit.app.get_app().next_update_async()
value_fog_b = settings.get(setting_fog_b)
value_meter_unit_f = settings.get(setting_meter_unit_f)
value_heatmap_i = settings.get(setting_heatmap_i)
value_max_bounce_i = settings.get(setting_max_bounce_i)
value_mat_white_s = settings.get(setting_mat_white_s)
value_ambinet_arr_f = settings.get(setting_ambinet_arr_f)
value_saturation_arr_f = settings.get(setting_saturation_arr_f)
# with special flags
value_mthread_transient_b = settings.get(setting_mthread_transient_b)
value_dir_light_b = settings.get(setting_dir_light_b)
value_place_col_b = settings.get(setting_place_col_b)
# Temporarily transient via rtx-flags specified in [[test]]
value_fog_dist_i = settings.get(setting_fog_dist_i)
value_fog_dist_flags = settings.get(setting_fog_dist_flags)
value_fog_color_arr_f = settings.get(setting_fog_color_arr_f)
value_fog_color_flags = settings.get(setting_fog_color_flags)
# New stage to release the temp usd file
await usd_context.new_stage_async()
if must_save:
self.assertEqual(value_fog_b, True)
self.compare_float(value_meter_unit_f, 0.5, self.VALUE_EPSILON)
self.assertEqual(value_heatmap_i, 3)
self.assertEqual(value_max_bounce_i, 33)
self.assertEqual(value_mat_white_s, "NoActualMat")
self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON)
self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON)
else:
self.assertNotEqual(value_fog_b, True)
self.assertNotAlmostEqual(value_meter_unit_f, 0.5, delta=self.VALUE_EPSILON)
self.assertNotEqual(value_heatmap_i, 3)
self.assertNotEqual(value_max_bounce_i, 33)
self.assertNotEqual(value_mat_white_s, "NoActualMat")
# self.compare_floats(value_ambinet_arr_f, [0.4, 0.5, 0.6], self.VALUE_EPSILON)
# self.compare_floats(value_saturation_arr_f, [0.7, 0.8, 0.9], self.VALUE_EPSILON))
# The ones with special flags should NOT be saved or loaded from USD
# same with persistent and rtx-transient
self.assertEqual(value_mthread_transient_b, True)
self.assertEqual(value_dir_light_b, False)
self.compare_floats(value_place_col_b, [0.6, 0.6, 0.6], self.VALUE_EPSILON)
# Temporarily transient via rtx-flags. Should not be saved to or loaded from USD
self.assertEqual(value_fog_dist_i, 999)
self.assertEqual(value_fog_dist_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON)
self.assertEqual(value_fog_color_flags, rtx.settings.SETTING_FLAGS_TRANSIENT)
async def run_render_settings_loading_helper(self, must_load=True, must_reset=True):
usd_context = omni.usd.get_context()
await omni.kit.app.get_app().next_update_async()
# Custom values already stored in the USD test
setting_tonemap_arr_f = "/rtx/post/tonemap/whitepoint"
setting_sample_threshold_i = "/rtx/directLighting/sampledLighting/autoEnableLightCountThreshold"
setting_max_roughness_f = "/rtx/reflections/maxRoughness"
setting_reflections_b = "/rtx/reflections/enabled"
# setting with kSettingFlagTransient, that should not be loaded if saved in the old USD files.
setting_mthread_transient_b = "/rtx/multiThreading/enabled"
setting_mat_syncload_b = "/rtx/materialDb/syncLoads"
setting_hydra_mat_syncload_b = "/rtx/hydra/materialSyncLoads"
# set as transient in [[test]]
setting_fog_dist_i = "/rtx/fog/fogEndDist" # int
setting_fog_color_arr_f = "/rtx/fog/fogColor" # array of float
await omni.kit.app.get_app().next_update_async()
settings.set_float_array(setting_tonemap_arr_f, [0.15, 0.16, 0.17])
settings.set(setting_sample_threshold_i, 43)
# change settings with kSettingFlagTransient
settings.set_bool(setting_mthread_transient_b, True)
settings.set_bool(setting_mat_syncload_b, True)
settings.set_bool(setting_hydra_mat_syncload_b, False)
# this was set in [[test]] as transient and not saved in USD.
settings.set(setting_fog_dist_i, 999)
settings.set_float_array(setting_fog_color_arr_f, [0.21, 0.21, 0.21])
await omni.kit.app.get_app().next_update_async()
self.open_usd("cubeRtxSettings.usda")
await wait_for_update()
value_tonemap_arr_f = settings.get(setting_tonemap_arr_f)
value_sample_threshold_i = settings.get(setting_sample_threshold_i)
value_max_roughness_f = settings.get(setting_max_roughness_f)
value_reflections_b = settings.get(setting_reflections_b)
value_mthread_transient_b = settings.get(setting_mthread_transient_b)
value_mat_syncload_b = settings.get(setting_mat_syncload_b)
value_hydra_mat_syncload_b = settings.get(setting_hydra_mat_syncload_b)
# Not stored in USD file, testing the default value
value_fog_dist_i = settings.get(setting_fog_dist_i)
value_fog_color_arr_f = settings.get(setting_fog_color_arr_f)
if must_load:
# Must match to what we stored in USD
self.compare_floats(value_tonemap_arr_f, [0.1, 0.2, 0.3], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 77)
self.compare_float(value_max_roughness_f, 0.53, self.VALUE_EPSILON)
self.assertEqual(value_reflections_b, False)
else:
if must_reset:
# Current default values set in C++ code.
self.compare_floats(value_tonemap_arr_f, [1.0, 1.0, 1.0], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 10)
else:
# what we set before loading the USD and not defaults.
self.compare_floats(value_tonemap_arr_f, [0.15, 0.16, 0.17], self.VALUE_EPSILON)
self.assertEqual(value_sample_threshold_i, 43)
self.assertNotAlmostEqual(value_max_roughness_f, 0.53, delta=self.VALUE_EPSILON)
self.assertNotEqual(value_reflections_b, False)
# Must skip loading setting that use kSettingFlagTransient flag from USD
# Such settings are not saved or loaded in USD, ut may exist in old USD files, such as cubeRtxSettings.usda.
# if usd was re-saved, you need to manually add those transient setting for this test. Otherwise, they will be removed.
self.assertEqual(value_mthread_transient_b, True)
self.assertEqual(value_mat_syncload_b, True)
self.assertEqual(value_hydra_mat_syncload_b, False)
# Temporarily transient via rtx-flags. Should not be saved to or loaded from USD
self.assertEqual(value_fog_dist_i, 999)
self.compare_floats(value_fog_color_arr_f, [0.21, 0.21, 0.21], self.VALUE_EPSILON)
async def test_render_settings_storage(self):
await self.run_render_settings_storage_helper(must_save=True)
async def test_render_settings_not_storing(self):
# Test to make sure rtx settings are not stored in USD, when asked.
storeRenderSettingsToStage = "/app/omni.usd/storeRenderSettingsToUsdStage";
settings.set_bool(storeRenderSettingsToStage, False)
await self.run_render_settings_storage_helper(must_save=False)
settings.set_bool(storeRenderSettingsToStage, True)
async def test_render_settings_loading(self):
await self.run_render_settings_loading_helper()
async def test_render_settings_not_loading(self):
# Test to make sure rtx settings are not loaded from USD, when asked.
loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage";
settings.set_bool(loadRenderSettingsFromStage, False)
await self.run_render_settings_loading_helper(must_load=False)
settings.set_bool(loadRenderSettingsFromStage, True)
async def test_render_settings_not_loading_not_reset(self):
# Test to make sure rtx settings are not loaded from USD, when asked.
loadRenderSettingsFromStage = "/app/omni.usd/loadRenderSettingsFromUsdStage";
resetRenderSettingsStage = "/app/omni.usd/resetRenderSettingsInUsdStage";
settings.set_bool(loadRenderSettingsFromStage, False)
settings.set_bool(resetRenderSettingsStage, False)
await self.run_render_settings_loading_helper(must_load=False, must_reset=False)
settings.set_bool(loadRenderSettingsFromStage, True)
settings.set_bool(resetRenderSettingsStage, True)
| 20,535 | Python | 48.484337 | 127 | 0.645142 |
omniverse-code/kit/exts/omni.rtx.settings.core/docs/CHANGELOG.md | # CHANGELOG
This document records all notable changes to ``omni.rtx.settings.dev`` extension.
This project adheres to `Semantic Versioning <https://semver.org/>`.
## [0.5.10] - 2022-11-22
### Changed
- Renamed all Debug Views that are intended to be RT-specific with RT prefix.
- Moved RT and PT MGPU settings frames to the bottom to be consistent with one another.
## [0.5.9] - 2022-11-16
### Changed
- For photosentivity/seizure concerns, included [WARNING: Flashing Colors] to Debug View names known to flash.
## [0.5.8] - 2022-10-26
### Added
- Added tooltips for all render settings.
- Added BVH Splits settings to 'Common/Geometry/Curves Settings'.
- Added Heat Map views to 'Common/Debug View'.
- Added an 'Invisible Lights Roughness Threshold' setting to 'Common/Lighting'.
- Added 'Frame Generation' setting to 'Real-Time/NVIDIA DLSS'.
- Added 'New Denoiser (experimental)' setting to 'Real-Time/Direct Lighting'.
- Added 'Multi Matte' settings in 'Interactive (Path Tracing)'.
- Added 'Adaptive Sampling' settings in 'Interactive (Path Tracing)/Path-Tracing'.
### Changed
- Refactored 'Lighting Mode' settings for Dome Lights in 'Common/Lighting'; now provides 'Image-Based Lighting' (simply a rename of the previous default) and 'Limited Image-Based Lighting'.
- Improved UI for setting-dependency clarity; settings which depend on others now tend to be indented under them, and hidden when the parent setting is not enabled.
- Improved PT AOV names for clarity.
## [0.5.7] - 2022-06-04
### Changed
- Make sure a stage is loaded to trigger RTX loading in Viewport.
## [0.5.6] - 2022-05-23
### Changed
- Add omni.hydra.rtx as test depenency
## [0.5.5] - 2022-03-11
### Changed
- Rename 'Path Traced' to 'Interactive (Path Tracing)'
## [0.5.4] - 2020-11-27
### Changed
- Update to use new RenderSettingsFactory entry point in rtx.window.settings
## [0.5.3] - 2020-11-25
### Changed
- Registration/Unregistration process
- Added Reset RTX settings button
- Added texture compression setting in common settings
- Updated to match current Render Settings 1.0
- make Enable/Disable of settings consistent
## [0.5.2] - 2020-11-18
### Changed
- Updated to match current Render Settings 1.0
## [0.5.1] - 2020-11-16
### Changed
- Shortened any labels that went over the new width (220)
## [0.5.0] - 2020-11-04
### Changed
- initial release
| 2,364 | Markdown | 30.959459 | 189 | 0.726734 |
omniverse-code/kit/exts/omni.rtx.settings.core/docs/README.md | # Developer RTX Settings [omni.rtx.settings.dev]
This is a example of RTX settings extensions that can register custom settings
| 129 | Markdown | 31.499992 | 78 | 0.806202 |
omniverse-code/kit/exts/omni.rtx.settings.core/docs/index.rst | omni.rtx.settings.core: omni.rtx.settings.dev
##############################################
.. toctree::
:maxdepth: 1
CHANGELOG
| 139 | reStructuredText | 12.999999 | 46 | 0.446043 |
omniverse-code/kit/exts/omni.activity.pump/PACKAGE-LICENSES/omni.activity.pump-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.activity.pump/config/extension.toml | [package]
title = "Omni Activity Pump"
category = "Telemetry"
version = "1.0.0"
description = "The activity and the progress processor gets pumped every frame"
authors = ["NVIDIA"]
keywords = ["activity"]
[[python.module]]
name = "omni.activity.pump"
[[native.plugin]]
path = "bin/*.plugin"
[dependencies]
"omni.activity.core" = {}
[[test]]
args = [
"--/app/window/dpiScaleOverride=1.0",
"--/app/window/scaleToMonitor=false",
"--no-window"
]
dependencies = [
"omni.kit.mainwindow",
"omni.kit.renderer.capture",
"omni.ui",
] | 552 | TOML | 18.068965 | 79 | 0.655797 |
omniverse-code/kit/exts/omni.activity.pump/omni/activity/pump/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
# Required to be able to instantiate the object types
import omni.core
| 508 | Python | 41.416663 | 77 | 0.793307 |
omniverse-code/kit/exts/omni.activity.pump/omni/activity/pump/tests/__init__.py | ## Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
##
## NVIDIA CORPORATION and its licensors retain all intellectual property
## and proprietary rights in and to this software, related documentation
## and any modifications thereto. Any use, reproduction, disclosure or
## distribution of this software and related documentation without an express
## license agreement from NVIDIA CORPORATION is strictly prohibited.
##
from .test_pump import TestPump
| 469 | Python | 41.727269 | 77 | 0.793177 |
omniverse-code/kit/exts/omni.activity.pump/omni/activity/pump/tests/test_pump.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 omni.activity.core as act
import omni.kit.app
import omni.kit.test
class TestPump(omni.kit.test.AsyncTestCase):
async def test_general(self):
called = []
def callback(node: act.INode):
self.assertEqual(node.name, "Test")
self.assertEqual(node.child_count, 1)
child = node.get_child(0)
self.assertEqual(child.name, "SubTest")
self.assertEqual(child.event_count, 2)
began = child.get_event(0)
ended = child.get_event(1)
self.assertEqual(began.event_type, act.EventType.BEGAN)
self.assertEqual(ended.event_type, act.EventType.ENDED)
self.assertEqual(began.payload["progress"], 0.0)
self.assertEqual(ended.payload["progress"], 1.0)
called.append(True)
id = act.get_instance().create_callback_to_pop(callback)
act.enable()
act.began("Test|SubTest", progress=0.0)
act.ended("Test|SubTest", progress=1.0)
act.disable()
for _ in range(50):
await omni.kit.app.get_app().next_update_async()
act.get_instance().remove_callback(id)
self.assertEquals(len(called), 1)
| 1,650 | Python | 32.019999 | 77 | 0.652121 |
omniverse-code/kit/exts/omni.usd_resolver/omni/usd_resolver/__init__.py | import os
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omni_usd_resolver import *
else:
from ._omni_usd_resolver import *
| 341 | Python | 27.499998 | 65 | 0.662757 |
omniverse-code/kit/exts/omni.usd_resolver/omni/usd_resolver/_omni_usd_resolver.pyi | from __future__ import annotations
import omni.usd_resolver._omni_usd_resolver
import typing
import omni.usd_resolver
__all__ = [
"Event",
"EventState",
"Subscription",
"get_version",
"register_event_callback",
"set_checkpoint_message",
"set_mdl_builtins"
]
class Event():
"""
Members:
RESOLVING
READING
WRITING
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
READING: omni.usd_resolver.Event # value = <Event.READING: 1>
RESOLVING: omni.usd_resolver.Event # value = <Event.RESOLVING: 0>
WRITING: omni.usd_resolver.Event # value = <Event.WRITING: 2>
__members__: dict # value = {'RESOLVING': <Event.RESOLVING: 0>, 'READING': <Event.READING: 1>, 'WRITING': <Event.WRITING: 2>}
pass
class EventState():
"""
Members:
STARTED
SUCCESS
FAILURE
"""
def __eq__(self, other: object) -> bool: ...
def __getstate__(self) -> int: ...
def __hash__(self) -> int: ...
def __index__(self) -> int: ...
def __init__(self, value: int) -> None: ...
def __int__(self) -> int: ...
def __ne__(self, other: object) -> bool: ...
def __repr__(self) -> str: ...
def __setstate__(self, state: int) -> None: ...
@property
def name(self) -> str:
"""
:type: str
"""
@property
def value(self) -> int:
"""
:type: int
"""
FAILURE: omni.usd_resolver.EventState # value = <EventState.FAILURE: 2>
STARTED: omni.usd_resolver.EventState # value = <EventState.STARTED: 0>
SUCCESS: omni.usd_resolver.EventState # value = <EventState.SUCCESS: 1>
__members__: dict # value = {'STARTED': <EventState.STARTED: 0>, 'SUCCESS': <EventState.SUCCESS: 1>, 'FAILURE': <EventState.FAILURE: 2>}
pass
class Subscription():
def __enter__(self) -> _omni_usd_resolver.Subscription: ...
def __exit__(self, arg0: object, arg1: object, arg2: object) -> None: ...
def unregister(self) -> None: ...
pass
def get_version() -> str:
"""
Get the version of USD Resolver being used.
Returns:
Returns a human readable version string.
"""
def register_event_callback(callback: typing.Callable[[str, omni.usd_resolver.Event, omni.usd_resolver.EventState, int], None]) -> omni.usd_resolver.Subscription:
"""
Register a function that will be called any time something interesting happens.
Args:
callback: Callback to be called with the event.
Returns:
Subscription Object. Callback will be unregistered once subcription is released.
"""
def set_checkpoint_message(message: str) -> None:
"""
Set the message to be used for atomic checkpoints created when saving files.
Args:
message (str): Checkpoint message.
"""
def set_mdl_builtins(arg0: typing.List[str]) -> None:
"""
Set a list of built-in MDLs.
Resolving an MDL in this list will return immediately rather than performing a full resolution.
"""
| 3,521 | unknown | 28.35 | 162 | 0.573701 |
omniverse-code/kit/exts/omni.usd_resolver/omni/spectree/__init__.py | import os
from typing import Tuple, List, Callable
if hasattr(os, "add_dll_directory"):
scriptdir = os.path.dirname(os.path.realpath(__file__))
dlldir = os.path.abspath(os.path.join(scriptdir, "../../.."))
with os.add_dll_directory(dlldir):
from ._omni_spec_tree import *
else:
from ._omni_spec_tree import *
| 335 | Python | 26.999998 | 65 | 0.656716 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnLoaded.rst | .. _omni_graph_action_OnLoaded_1:
.. _omni_graph_action_OnLoaded:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Loaded
:keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-loaded
On Loaded
=========
.. <description>
Triggers the output on the first update of the graph after it is created or loaded. This will run before any other event node, and will only run once after this node is created.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execOut", "``execution``", "Executes after graph creation or loading", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnLoaded"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Loaded"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnLoadedDatabase"
"Python Module", "omni.graph.action"
| 1,487 | reStructuredText | 24.220339 | 177 | 0.581708 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnRationalTimeSyncGate.rst | .. _omni_graph_action_RationalTimeSyncGate_1:
.. _omni_graph_action_RationalTimeSyncGate:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Rational Sync Gate
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action rational-time-sync-gate
Rational Sync Gate
==================
.. <description>
This node triggers when all its input executions have triggered successively at the same rational time.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
"Sync Denominator (*inputs:rationalTimeDenominator*)", "``uint64``", "Denominator of the synchronization time.", "0"
"Sync Numerator (*inputs:rationalTimeNumerator*)", "``int64``", "Numerator of the synchronization time.", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None"
"Sync Denominator (*outputs:rationalTimeDenominator*)", "``uint64``", "Denominator of the synchronization time.", "None"
"Sync Numerator (*outputs:rationalTimeNumerator*)", "``int64``", "Numerator of the synchronization time.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.RationalTimeSyncGate"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Rational Sync Gate"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnRationalTimeSyncGateDatabase"
"Python Module", "omni.graph.action"
| 2,174 | reStructuredText | 29.208333 | 124 | 0.612695 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnForLoop.rst | .. _omni_graph_action_ForLoop_1:
.. _omni_graph_action_ForLoop:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: For Loop
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action for-loop
For Loop
========
.. <description>
Executes the a loop body once for each value within a range. When step is positive, the values in the range are determined by the formula:
r[i] = start + step*i, i >= 0 & r[i] < stop.
When step is negative the constraint is instead r[i] > stop. A step of zero is an error.
The break input can be used to break out of the loop before the last index. The finished output is executed after all iterations are complete, or when the loop was broken
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Break (*inputs:breakLoop*)", "``execution``", "Breaks out of the loop when the loop body traversal reaches it", "None"
"In (*inputs:execIn*)", "``execution``", "Input execution", "None"
"Start (*inputs:start*)", "``int``", "The first value in the range", "0"
"Step (*inputs:step*)", "``int``", "The step size of the range", "1"
"Stop (*inputs:stop*)", "``int``", "The limiting value of the range", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:finished", "``execution``", "Executed when the loop is finished", "None"
"outputs:index", "``int``", "The current or last index within the range", "None"
"outputs:loopBody", "``execution``", "Executed for each index in the range", "None"
"outputs:value", "``int``", "The current or last value of the range", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:i", "``int``", "The next position in the range or -1 when loop is not active", "-1"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.ForLoop"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.ForLoop.svg"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"tags", "range"
"uiName", "For Loop"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnForLoopDatabase"
"Python Module", "omni.graph.action"
| 2,806 | reStructuredText | 30.539325 | 172 | 0.596222 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSendCustomEvent.rst | .. _omni_graph_action_SendCustomEvent_1:
.. _omni_graph_action_SendCustomEvent:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Send Custom Event
:keywords: lang-en omnigraph node graph:action,event action send-custom-event
Send Custom Event
=================
.. <description>
Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Bundle (*inputs:bundle*)", "``bundle``", "Bundle to be sent with the event", "None"
"Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", ""
"inputs:execIn", "``execution``", "Input Execution", "None"
"Path (*inputs:path*)", "``token``", "The path associated with the event", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execOut", "``execution``", "Output Execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.SendCustomEvent"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Send Custom Event"
"Categories", "graph:action,event"
"Generated Class Name", "OgnSendCustomEventDatabase"
"Python Module", "omni.graph.action"
| 1,883 | reStructuredText | 25.535211 | 122 | 0.580988 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnDelay.rst | .. _omni_graph_action_Delay_1:
.. _omni_graph_action_Delay:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Delay
:keywords: lang-en omnigraph node graph:action,time threadsafe action delay
Delay
=====
.. <description>
This node suspends the graph for a period of time before continuing. This node, and nodes upstream of this node are locked for the duration of the delay, which means any subsequent executions will be ignored.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Duration (*inputs:duration*)", "``double``", "The duration of the delay (Seconds)", "0.0"
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Finished (*outputs:finished*)", "``execution``", "Triggered when the delay is finished", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Delay"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"uiName", "Delay"
"Categories", "graph:action,time"
"Generated Class Name", "OgnDelayDatabase"
"Python Module", "omni.graph.action"
| 1,767 | reStructuredText | 24.623188 | 208 | 0.580079 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnVariableChange.rst | .. _omni_graph_action_OnVariableChange_1:
.. _omni_graph_action_OnVariableChange:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Variable Change
:keywords: lang-en omnigraph node graph:action,event threadsafe action on-variable-change
On Variable Change
==================
.. <description>
Executes an output execution pulse when the chosen variable changes
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
"Variable Name (*inputs:variableName*)", "``token``", "The name of the graph variable to use.", ""
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Changed (*outputs:changed*)", "``execution``", "The execution output", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnVariableChange"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Variable Change"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnVariableChangeDatabase"
"Python Module", "omni.graph.action"
| 1,849 | reStructuredText | 25.056338 | 140 | 0.574905 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSequence.rst | .. _omni_graph_action_Sequence_1:
.. _omni_graph_action_Sequence:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sequence
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action sequence
Sequence
========
.. <description>
Outputs an execution pulse along output A and B in sequence
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:execIn", "``execution``", "Input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"A (*outputs:a*)", "``execution``", "The first output path", "None"
"B (*outputs:b*)", "``execution``", "The second outputs path", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Sequence"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.Sequence.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"hidden", "true"
"uiName", "Sequence"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnSequenceDatabase"
"Python Module", "omni.graph.action"
| 1,665 | reStructuredText | 22.464788 | 97 | 0.561562 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnPlaybackTick.rst | .. _omni_graph_action_OnPlaybackTick_1:
.. _omni_graph_action_OnPlaybackTick:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Playback Tick
:keywords: lang-en omnigraph node graph:action,event threadsafe action on-playback-tick
On Playback Tick
================
.. <description>
Executes an output execution pulse during playback
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Delta Seconds (*outputs:deltaSeconds*)", "``double``", "The number of seconds elapsed since the last update", "None"
"Frame (*outputs:frame*)", "``double``", "The global playback time in frames, equivalent to (time * fps)", "None"
"Tick (*outputs:tick*)", "``execution``", "The execution output", "None"
"Time (*outputs:time*)", "``double``", "The global playback time in seconds", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnPlaybackTick"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Playback Tick"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnPlaybackTickDatabase"
"Python Module", "omni.graph.action"
| 1,715 | reStructuredText | 26.677419 | 121 | 0.581924 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSetPrimActive.rst | .. _omni_graph_action_SetPrimActive_1:
.. _omni_graph_action_SetPrimActive:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Set Prim Active
:keywords: lang-en omnigraph node graph:action,sceneGraph WriteOnly action set-prim-active
Set Prim Active
===============
.. <description>
Set a Prim active or not in the stage.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:active", "``bool``", "Wheter to set the prim active or not", "False"
"inputs:execIn", "``execution``", "Input execution", "None"
"Prim Path (*inputs:prim*)", "``path``", "The prim to be (de)activated", ""
"Prim (*inputs:primTarget*)", "``target``", "The prim to be (de)activated", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.SetPrimActive"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Set Prim Active"
"Categories", "graph:action,sceneGraph"
"Generated Class Name", "OgnSetPrimActiveDatabase"
"Python Module", "omni.graph.action"
| 1,809 | reStructuredText | 24.492957 | 97 | 0.565506 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnMessageBusEvent.rst | .. _omni_graph_action_OnMessageBusEvent_1:
.. _omni_graph_action_OnMessageBusEvent:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On MessageBus Event
:keywords: lang-en omnigraph node graph:action,event compute-on-request action on-message-bus-event
On MessageBus Event
===================
.. <description>
Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python: msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example, 42 would be copied to outputs:arg1 if possible
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", ""
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Received (*outputs:execOut*)", "``execution``", "Executes when the event is received", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnMessageBusEvent"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On MessageBus Event"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnMessageBusEventDatabase"
"Python Module", "omni.graph.action"
| 2,227 | reStructuredText | 30.380281 | 424 | 0.607993 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnKeyboardInput.rst | .. _omni_graph_action_OnKeyboardInput_3:
.. _omni_graph_action_OnKeyboardInput:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Keyboard Input
:keywords: lang-en omnigraph node graph:action,input:keyboard compute-on-request action on-keyboard-input
On Keyboard Input
=================
.. <description>
Event node which fires when a keyboard event occurs. The event can be a combination of keys, containing key modifiers of ctrl, alt and shift, and a normal key of any key. keyIn.
For key combinations, the press event requires all keys to be pressed, with the normal key pressed last. The release event is only triggered once when one of the chosen keys released after pressed event happens.
For example: if the combination is ctrl-shift-D, the pressed event happens once right after D is pressed while both ctrl and shit are held. And the release event happens only once when the user releases any key of ctrl, shift and D while holding them.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Alt (*inputs:altIn*)", "``bool``", "When true, the node will check with a key modifier Alt", "False"
"", "*literalOnly*", "1", ""
"Ctrl (*inputs:ctrlIn*)", "``bool``", "When true, the node will check with a key modifier Control", "False"
"", "*literalOnly*", "1", ""
"Key In (*inputs:keyIn*)", "``token``", "The key to trigger the downstream execution ", "A"
"", "*displayGroup*", "parameters", ""
"", "*literalOnly*", "1", ""
"", "*allowedTokens*", "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Apostrophe,Backslash,Backspace,CapsLock,Comma,Del,Down,End,Enter,Equal,Escape,F1,F10,F11,F12,F2,F3,F4,F5,F6,F7,F8,F9,GraveAccent,Home,Insert,Key0,Key1,Key2,Key3,Key4,Key5,Key6,Key7,Key8,Key9,Left,LeftAlt,LeftBracket,LeftControl,LeftShift,LeftSuper,Menu,Minus,NumLock,Numpad0,Numpad1,Numpad2,Numpad3,Numpad4,Numpad5,Numpad6,Numpad7,Numpad8,Numpad9,NumpadAdd,NumpadDel,NumpadDivide,NumpadEnter,NumpadEqual,NumpadMultiply,NumpadSubtract,PageDown,PageUp,Pause,Period,PrintScreen,Right,RightAlt,RightBracket,RightControl,RightShift,RightSuper,ScrollLock,Semicolon,Slash,Space,Tab,Up", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
"Shift (*inputs:shiftIn*)", "``bool``", "When true, the node will check with a key modifier Shift", "False"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:isPressed", "``bool``", "True if the key was pressed, False if it was released", "None"
"Key Out (*outputs:keyOut*)", "``token``", "The key that was pressed or released", "None"
"Pressed (*outputs:pressed*)", "``execution``", "Executes when key was pressed", "None"
"Released (*outputs:released*)", "``execution``", "Executes when key was released", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnKeyboardInput"
"Version", "3"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Keyboard Input"
"Categories", "graph:action,input:keyboard"
"Generated Class Name", "OgnOnKeyboardInputDatabase"
"Python Module", "omni.graph.action"
| 3,870 | reStructuredText | 45.083333 | 662 | 0.652196 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnGamepadInput.rst | .. _omni_graph_action_OnGamepadInput_1:
.. _omni_graph_action_OnGamepadInput:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Gamepad Input
:keywords: lang-en omnigraph node graph:action,input:gamepad compute-on-request action on-gamepad-input
On Gamepad Input
================
.. <description>
Event node which fires when a gamepad event occurs. This node only capture events on buttons, excluding triggers and sticks
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Gamepad Element In (*inputs:gamepadElementIn*)", "``token``", "The gamepad button to trigger the downstream execution.", "Face Button Bottom"
"", "*displayGroup*", "parameters", ""
"", "*literalOnly*", "1", ""
"", "*allowedTokens*", "Face Button Bottom,Face Button Right,Face Button Left,Face Button Top,Left Shoulder,Right Shoulder,Special Left,Special Right,Left Stick Button,Right Stick Button,D-Pad Up,D-Pad Right,D-Pad Down,D-Pad Left", ""
"Gamepad ID (*inputs:gamepadId*)", "``uint``", "Gamepad id number starting from 0. Each gamepad will be registered automatically with an unique ID monotonically increasing in the order they are connected. If gamepad is disconnected, the ID assigned to the remaining gamepad will be adjusted accordingly so the IDs are always continues and start from 0 Change this value to a non-existing ID will result an error prompt in the console and the node will not listen to any gamepad input.", "0"
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:isPressed", "``bool``", "True if the gamepad button was pressed, False if it was released", "None"
"Pressed (*outputs:pressed*)", "``execution``", "Executes when gamepad element was pressed", "None"
"Released (*outputs:released*)", "``execution``", "Executes when gamepad element was released", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnGamepadInput"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"uiName", "On Gamepad Input"
"Categories", "graph:action,input:gamepad"
"Generated Class Name", "OgnOnGamepadInputDatabase"
"Python Module", "omni.graph.action"
| 3,008 | reStructuredText | 38.077922 | 494 | 0.639295 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnForEach.rst | .. _omni_graph_action_ForEach_1:
.. _omni_graph_action_ForEach:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: For Each Loop
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action for-each
For Each Loop
=============
.. <description>
Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are complete
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Input Array (*inputs:arrayIn*)", "``['bool[]', 'colord[3][]', 'colord[4][]', 'colorf[3][]', 'colorf[4][]', 'colorh[3][]', 'colorh[4][]', 'double[2][]', 'double[3][]', 'double[4][]', 'double[]', 'float[2][]', 'float[3][]', 'float[4][]', 'float[]', 'frame[4][]', 'half[2][]', 'half[3][]', 'half[4][]', 'half[]', 'int64[]', 'int[2][]', 'int[3][]', 'int[4][]', 'int[]', 'matrixd[3][]', 'matrixd[4][]', 'normald[3][]', 'normalf[3][]', 'normalh[3][]', 'pointd[3][]', 'pointf[3][]', 'pointh[3][]', 'quatd[4][]', 'quatf[4][]', 'quath[4][]', 'texcoordd[2][]', 'texcoordd[3][]', 'texcoordf[2][]', 'texcoordf[3][]', 'texcoordh[2][]', 'texcoordh[3][]', 'timecode[]', 'token[]', 'transform[4][]', 'uchar[]', 'uint64[]', 'uint[]', 'vectord[3][]', 'vectorf[3][]', 'vectorh[3][]']``", "The array to loop over", "None"
"inputs:execIn", "``execution``", "Input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:arrayIndex", "``int``", "The current or last index visited", "None"
"outputs:element", "``['bool', 'colord[3]', 'colord[4]', 'colorf[3]', 'colorf[4]', 'colorh[3]', 'colorh[4]', 'double', 'double[2]', 'double[3]', 'double[4]', 'float', 'float[2]', 'float[3]', 'float[4]', 'frame[4]', 'half', 'half[2]', 'half[3]', 'half[4]', 'int', 'int64', 'int[2]', 'int[3]', 'int[4]', 'matrixd[3]', 'matrixd[4]', 'normald[3]', 'normalf[3]', 'normalh[3]', 'pointd[3]', 'pointf[3]', 'pointh[3]', 'quatd[4]', 'quatf[4]', 'quath[4]', 'texcoordd[2]', 'texcoordd[3]', 'texcoordf[2]', 'texcoordf[3]', 'texcoordh[2]', 'texcoordh[3]', 'timecode', 'token', 'transform[4]', 'uchar', 'uint', 'uint64', 'vectord[3]', 'vectorf[3]', 'vectorh[3]']``", "The current or last element of the array visited", "None"
"outputs:finished", "``execution``", "Executed when the loop is finished", "None"
"outputs:loopBody", "``execution``", "Executed for each element of the array", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.ForEach"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.ForEach.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "For Each Loop"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnForEachDatabase"
"Python Module", "omni.graph.action"
| 3,366 | reStructuredText | 45.123287 | 806 | 0.553179 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnAddPrimRelationship.rst | .. _omni_graph_action_AddPrimRelationship_1:
.. _omni_graph_action_AddPrimRelationship:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Add Prim Relationship
:keywords: lang-en omnigraph node sceneGraph WriteOnly action add-prim-relationship
Add Prim Relationship
=====================
.. <description>
Adds a target path to a relationship property. If the relationship property does not exist it will be created. Duplicate targets will not be added.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:execIn", "``execution``", "The input execution port.", "None"
"Relationship Name (*inputs:name*)", "``token``", "Name of the relationship property.", ""
"Prim Path (*inputs:path*)", "``path``", "Path of the prim with the relationship property.", ""
"Target Path (*inputs:target*)", "``path``", "The target path to be added, which may be a prim, attribute or another relationship.", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Is Successful (*outputs:isSuccessful*)", "``bool``", "Whether the node has successfully added the new target to the relationship.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.AddPrimRelationship"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Add Prim Relationship"
"Categories", "sceneGraph"
"Generated Class Name", "OgnAddPrimRelationshipDatabase"
"Python Module", "omni.graph.action"
| 2,100 | reStructuredText | 28.591549 | 147 | 0.601429 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnMultisequence.rst | .. _omni_graph_action_Multisequence_1:
.. _omni_graph_action_Multisequence:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sequence
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action multisequence
Sequence
========
.. <description>
Outputs an execution pulse along each of its N outputs in sequence. For every single input execution pulse, each and every output will be exclusively enabled in order.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:output0", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Multisequence"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.Multisequence.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Sequence"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnMultisequenceDatabase"
"Python Module", "omni.graph.action"
| 1,722 | reStructuredText | 23.971014 | 167 | 0.589431 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnTick.rst | .. _omni_graph_action_OnTick_1:
.. _omni_graph_action_OnTick:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Tick
:keywords: lang-en omnigraph node graph:action,event threadsafe action on-tick
On Tick
=======
.. <description>
Executes an output execution pulse at a regular multiple of the refresh rate
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Update Period (Ticks) (*inputs:framePeriod*)", "``uint``", "The number of updates between each output pulse. The default 0 means every update, 1 means every other update. This can be used to rate-limit updates.", "0"
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Absolute Simulation Time (Seconds) (*outputs:absoluteSimTime*)", "``double``", "The accumulated total of elapsed times between rendered frames", "None"
"Delta (Seconds) (*outputs:deltaSeconds*)", "``double``", "The number of seconds elapsed since the last output pulse", "None"
"Animation Time (Frames) (*outputs:frame*)", "``double``", "The global animation time in frames, equivalent to (time * fps), during playback", "None"
"Is Playing (*outputs:isPlaying*)", "``bool``", "True during global animation timeline playback", "None"
"Tick (*outputs:tick*)", "``execution``", "The execution output", "None"
"Animation Time (Seconds) (*outputs:time*)", "``double``", "The global animation time in seconds during playback", "None"
"Time Since Start (Seconds) (*outputs:timeSinceStart*)", "``double``", "Elapsed time since the App started", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:accumulatedSeconds", "``double``", "Accumulated time since the last output pulse", "0"
"state:frameCount", "``uint``", "Accumulated frames since the last output pulse", "0"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnTick"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Tick"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnTickDatabase"
"Python Module", "omni.graph.action"
| 2,971 | reStructuredText | 33.160919 | 221 | 0.609896 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnStageEvent.rst | .. _omni_graph_action_OnStageEvent_3:
.. _omni_graph_action_OnStageEvent:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Stage Event
:keywords: lang-en omnigraph node graph:action,event compute-on-request action on-stage-event
On Stage Event
==============
.. <description>
Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed by the system:
Saved: USD file saved.
Selection Changed: USD Prim selection has changed.
Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved.
OmniGraph Start Play: OmniGraph started
OmniGraph Stop Play: OmniGraph stopped
Simulation Start Play: Simulation started
Simulation Stop Play: Simulation stopped
Animation Start Play: Animation playback has started
Animation Stop Play: Animation playback has stopped
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:eventName", "``token``", "The event of interest", ""
"", "*allowedTokens*", "Saved,Selection Changed,Hierarchy Changed,OmniGraph Start Play,OmniGraph Stop Play,Simulation Start Play,Simulation Stop Play,Animation Start Play,Animation Stop Play", ""
"", "*default*", "Animation Start Play", ""
"", "*displayGroup*", "parameters", ""
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:execOut", "``execution``", "The execution output", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnStageEvent"
"Version", "3"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Stage Event"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnStageEventDatabase"
"Python Module", "omni.graph.action"
| 2,580 | reStructuredText | 30.096385 | 199 | 0.631008 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnMultigate.rst | .. _omni_graph_action_Multigate_1:
.. _omni_graph_action_Multigate:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Multigate
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action multigate
Multigate
=========
.. <description>
This node cycles through each of its N outputs. On each input, one output will be activated. Outputs will be activated in sequence, eg: 0->1->2->3->4->0->1...
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:output0", "``execution``", "Output execution", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Multigate"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.Multigate.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Multigate"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnMultigateDatabase"
"Python Module", "omni.graph.action"
| 1,693 | reStructuredText | 23.550724 | 158 | 0.573538 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnGate.rst | .. _omni_graph_action_Gate_1:
.. _omni_graph_action_Gate:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Gate
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action gate
Gate
====
.. <description>
This node controls a flow of execution based on the state of its gate. The gate can be opened or closed by execution pulses sent to the gate controls
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Enter (*inputs:enter*)", "``execution``", "Incoming execution flow controlled by the gate", "None"
"Start Closed (*inputs:startClosed*)", "``bool``", "If true the gate will start in a closed state", "False"
"Toggle (*inputs:toggle*)", "``execution``", "The gate is opened or closed", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Exit (*outputs:exit*)", "``execution``", "The enter pulses will be passed to this output if the gate is open", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Gate"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.Gate.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Gate"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnGateDatabase"
"Python Module", "omni.graph.action"
| 1,911 | reStructuredText | 25.929577 | 149 | 0.583987 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSwitchToken.rst | .. _omni_graph_action_SwitchToken_1:
.. _omni_graph_action_SwitchToken:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Switch On Token
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action switch-token
Switch On Token
===============
.. <description>
Outputs an execution pulse along a branch which matches the input token. For example if inputs:value is set to 'A' it will continue downstream from outputs:outputNN if there is an inputs:branchNN is set to 'A'
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:execIn", "``execution``", "Input execution", "None"
"Value (*inputs:value*)", "``token``", "The value to switch on", ""
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.SwitchToken"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Switch On Token"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnSwitchTokenDatabase"
"Python Module", "omni.graph.action"
| 1,594 | reStructuredText | 25.583333 | 209 | 0.584693 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnClosing.rst | .. _omni_graph_action_OnClosing_1:
.. _omni_graph_action_OnClosing:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Closing
:keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-closing
On Closing
==========
.. <description>
Executes an output execution when the USD stage is about to be closed.
Note that only simple necessary actions should be taken during closing since the application is in the process of cleaning up the existing state and some systems may be in a transitional state
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Closing (*outputs:execOut*)", "``execution``", "The execution output", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnClosing"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Closing"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnClosingDatabase"
"Python Module", "omni.graph.action"
| 1,575 | reStructuredText | 25.266666 | 193 | 0.59619 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnce.rst | .. _omni_graph_action_Once_1:
.. _omni_graph_action_Once:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Once
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action once
Once
====
.. <description>
Controls flow of execution by passing input through differently on the first time
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:execIn", "``execution``", "Input execution", "None"
"inputs:reset", "``execution``", "Resets the gate state to closed. The next execIn impulse will pass the gate.", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:after", "``execution``", "Executes after the first time", "None"
"outputs:once", "``execution``", "Executes the first time (or the first time after a 'reset'.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Once"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Once"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnOnceDatabase"
"Python Module", "omni.graph.action"
| 1,738 | reStructuredText | 23.842857 | 123 | 0.573648 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnCustomEvent.rst | .. _omni_graph_action_OnCustomEvent_2:
.. _omni_graph_action_OnCustomEvent:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Custom Event
:keywords: lang-en omnigraph node graph:action,event compute-on-request action on-custom-event
On Custom Event
===============
.. <description>
Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Event Name (*inputs:eventName*)", "``token``", "The name of the custom event", ""
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Bundle (*outputs:bundle*)", "``bundle``", "Bundle received with the event", "None"
"Received (*outputs:execOut*)", "``execution``", "Executes when the event is received", "None"
"Path (*outputs:path*)", "``token``", "The path associated with the received custom event", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnCustomEvent"
"Version", "2"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Custom Event"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnCustomEventDatabase"
"Python Module", "omni.graph.action"
| 2,074 | reStructuredText | 27.424657 | 140 | 0.584378 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnCounter.rst | .. _omni_graph_action_Counter_1:
.. _omni_graph_action_Counter:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Counter
:keywords: lang-en omnigraph node graph:action,function threadsafe action counter
Counter
=======
.. <description>
This node counts the number of times it is computed since being reset
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
"Reset (*inputs:reset*)", "``execution``", "Reset the internal counter", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Count (*outputs:count*)", "``int``", "The count value", "None"
"Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:count", "``int``", "The counter state", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Counter"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"uiName", "Counter"
"Categories", "graph:action,function"
"Generated Class Name", "OgnCounterDatabase"
"Python Module", "omni.graph.action"
| 1,865 | reStructuredText | 22.620253 | 97 | 0.560322 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnObjectChange.rst | .. _omni_graph_action_OnObjectChange_4:
.. _omni_graph_action_OnObjectChange:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On USD Object Change
:keywords: lang-en omnigraph node graph:action,event threadsafe action on-object-change
On USD Object Change
====================
.. <description>
Executes an output execution pulse when the watched USD Object changes
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Property Name (*inputs:name*)", "``token``", "The name of the property to watch if prim input is set", "None"
"", "*literalOnly*", "1", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
"Path (*inputs:path*)", "``path``", "The path of object of interest (property or prim). If the prim input has a target, this is ignored", "None"
"", "*literalOnly*", "1", ""
"Prim (*inputs:prim*)", "``target``", "The prim of interest. If this has a target, the path input will be ignored", "None"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Changed (*outputs:changed*)", "``execution``", "The execution output", "None"
"Property Name (*outputs:propertyName*)", "``token``", "The name of the property that changed", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnObjectChange"
"Version", "4"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On USD Object Change"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnObjectChangeDatabase"
"Python Module", "omni.graph.action"
| 2,312 | reStructuredText | 29.43421 | 148 | 0.580882 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnFlipFlop.rst | .. _omni_graph_action_FlipFlop_1:
.. _omni_graph_action_FlipFlop:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Flip Flop
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action flip-flop
Flip Flop
=========
.. <description>
This node alternates activating its outputs, starting with A
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute A (*outputs:a*)", "``execution``", "Executed on the 1st and odd numbered triggers", "None"
"Execute B (*outputs:b*)", "``execution``", "Executed on the even number triggers", "None"
"Is A (*outputs:isA*)", "``bool``", "Set to true when a is activated", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.FlipFlop"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.FlipFlop.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"uiName", "Flip Flop"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnFlipFlopDatabase"
"Python Module", "omni.graph.action"
| 1,805 | reStructuredText | 24.436619 | 103 | 0.571191 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnCountdown.rst | .. _omni_graph_action_Countdown_1:
.. _omni_graph_action_Countdown:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Countdown
:keywords: lang-en omnigraph node graph:action,flowControl action countdown
Countdown
=========
.. <description>
Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown is complete it triggers the finished output. The first compute does not generate a tick output.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"inputs:duration", "``int``", "The duration of the delay in ticks", "5"
"inputs:execIn", "``execution``", "The input execution", "None"
"inputs:period", "``int``", "The period of the pulse in ticks", "1"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:alpha", "``float``", "normalized progress in the range IE 'tickValue'/'duration'", "None"
"outputs:finished", "``execution``", "Triggered after duration ticks is finished", "None"
"outputs:tick", "``execution``", "Triggered every 'period' ticks", "None"
"outputs:tickValue", "``int``", "The current tick value in the range [1, duration]", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:count", "``int``", "The number of ticks elapsed, the first tick is 0", "-1"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Countdown"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "Python"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "tests"
"uiName", "Countdown"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnCountdownDatabase"
"Python Module", "omni.graph.action"
| 2,324 | reStructuredText | 27.353658 | 218 | 0.594234 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnBranch.rst | .. _omni_graph_action_Branch_1:
.. _omni_graph_action_Branch:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Branch
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action branch
Branch
======
.. <description>
Outputs an execution pulse along a branch based on a boolean condition
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Condition (*inputs:condition*)", "``bool``", "The boolean condition which determines the output direction", "False"
"inputs:execIn", "``execution``", "Input execution", "None"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"False (*outputs:execFalse*)", "``execution``", "The output path when condition is False", "None"
"True (*outputs:execTrue*)", "``execution``", "The output path when condition is True", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.Branch"
"Version", "1"
"Extension", "omni.graph.action"
"Icon", "ogn/icons/omni.graph.action.Branch.svg"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Branch"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnBranchDatabase"
"Python Module", "omni.graph.action"
| 1,811 | reStructuredText | 24.521126 | 120 | 0.580342 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnMouseInput.rst | .. _omni_graph_action_OnMouseInput_1:
.. _omni_graph_action_OnMouseInput:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Mouse Input
:keywords: lang-en omnigraph node graph:action,input:mouse threadsafe compute-on-request action on-mouse-input
On Mouse Input
==============
.. <description>
Event node which fires when a mouse event occurs.
You can choose which mouse element this node reacts to. When mouse element is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed. When scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value. You can choose to output normalized or pixel coordinates of the mouse.
Pixel coordinates are the absolute position of the mouse cursor in pixel unit. The original point is the upper left corner. The minimum value is 0, and the maximum value depends on the size of the window.
Normalized coordinates are the relative position of the mouse cursor to the window. The value is always between 0 and 1.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Mouse Element (*inputs:mouseElement*)", "``token``", "The event to trigger the downstream execution ", "Left Button"
"", "*displayGroup*", "parameters", ""
"", "*literalOnly*", "1", ""
"", "*allowedTokens*", "Left Button,Middle Button,Right Button,Normalized Move,Pixel Move,Scroll", ""
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"outputs:isPressed", "``bool``", "True if the mouse button was pressed, False if it was released or mouse element is not related to a button", "None"
"Pressed (*outputs:pressed*)", "``execution``", "Executes when mouse button was pressed. Will not execute on move or scroll events", "None"
"Released (*outputs:released*)", "``execution``", "Executes when mouse button was released. Will not execute on move or scroll events", "None"
"Delta Value (*outputs:value*)", "``float[2]``", "The meaning of this output depends on Event In. Normalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1] Pixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window] Scroll: will output the change of scroll value Otherwise: will output [0,0]", "None"
"Moved (*outputs:valueChanged*)", "``execution``", "Executes when user moves the cursor or scrolls the cursor. Will not execute on button events", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnMouseInput"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Mouse Input"
"Categories", "graph:action,input:mouse"
"Generated Class Name", "OgnOnMouseInputDatabase"
"Python Module", "omni.graph.action"
| 3,652 | reStructuredText | 44.662499 | 433 | 0.662651 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnOnImpulseEvent.rst | .. _omni_graph_action_OnImpulseEvent_2:
.. _omni_graph_action_OnImpulseEvent:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: On Impulse Event
:keywords: lang-en omnigraph node graph:action,event threadsafe compute-on-request action on-impulse-event
On Impulse Event
================
.. <description>
Triggers the output execution once when state is set
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Only Simulate On Play (*inputs:onlyPlayback*)", "``bool``", "When true, the node is only computed while Stage is being played.", "True"
"", "*literalOnly*", "1", ""
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Trigger (*outputs:execOut*)", "``execution``", "The execution output", "None"
State
-----
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"state:enableImpulse", "``bool``", "When true, execute output once and reset to false", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.OnImpulseEvent"
"Version", "2"
"Extension", "omni.graph.action"
"Has State?", "True"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "On Impulse Event"
"Categories", "graph:action,event"
"Generated Class Name", "OgnOnImpulseEventDatabase"
"Python Module", "omni.graph.action"
| 1,909 | reStructuredText | 23.487179 | 140 | 0.574123 |
omniverse-code/kit/exts/omni.graph.action/ogn/docs/OgnSyncGate.rst | .. _omni_graph_action_SyncGate_1:
.. _omni_graph_action_SyncGate:
.. ================================================================================
.. THIS PAGE IS AUTO-GENERATED. DO NOT MANUALLY EDIT.
.. ================================================================================
:orphan:
.. meta::
:title: Sync Gate
:keywords: lang-en omnigraph node graph:action,flowControl threadsafe action sync-gate
Sync Gate
=========
.. <description>
This node triggers when all its input executions have triggered successively at the same synchronization value.
.. </description>
Installation
------------
To use this node enable :ref:`omni.graph.action<ext_omni_graph_action>` in the Extension Manager.
Inputs
------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute In (*inputs:execIn*)", "``execution``", "The input execution", "None"
"Sync (*inputs:syncValue*)", "``uint64``", "Value of the synchronization reference.", "0"
Outputs
-------
.. csv-table::
:header: "Name", "Type", "Descripton", "Default"
:widths: 20, 20, 50, 10
"Execute Out (*outputs:execOut*)", "``execution``", "The output execution", "None"
"Sync (*outputs:syncValue*)", "``uint64``", "Value of the synchronization reference.", "None"
Metadata
--------
.. csv-table::
:header: "Name", "Value"
:widths: 30,70
"Unique ID", "omni.graph.action.SyncGate"
"Version", "1"
"Extension", "omni.graph.action"
"Has State?", "False"
"Implementation Language", "C++"
"Default Memory Type", "cpu"
"Generated Code Exclusions", "None"
"uiName", "Sync Gate"
"Categories", "graph:action,flowControl"
"Generated Class Name", "OgnSyncGateDatabase"
"Python Module", "omni.graph.action"
| 1,798 | reStructuredText | 24.7 | 111 | 0.579533 |
omniverse-code/kit/exts/omni.graph.action/PACKAGE-LICENSES/omni.graph.action-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.graph.action/config/extension.toml | [package]
title = "OmniGraph Action Graph"
version = "1.31.1"
category = "Graph"
feature = true
# Preview image. Folder named "data" automatically goes in git lfs (see .gitattributes file).
preview_image = "data/preview.png"
# Path (relative to the root) of the main documentation file.
readme = "docs/README.md"
changelog = "docs/CHANGELOG.md"
description = "Contains nodes for Omnigraph Action Graphs."
repository = ""
keywords = ["omnigraph", "nodes", "action"]
# Main module for the Python interface
[[python.module]]
name = "omni.graph.action"
# Watch the .ogn files for hot reloading (only works for Python files)
[fswatcher.patterns]
include = ["*.ogn", "*.py"]
exclude = ["Ogn*Database.py"]
# Other extensions that need to load before this one
[dependencies]
"omni.usd" = { version = "1.4.8" }
"omni.kit.async_engine" = {}
"omni.kit.commands" = {}
"omni.graph" = {}
"omni.graph.ui" = { optional = true }
"omni.graph.tools" = {}
"omni.kit.stage_templates" = {}
"omni.kit.pipapi" = {}
"omni.kit.window.filepicker" = { optional = true }
[[native.plugin]]
path = "bin/*.plugin"
recursive = false
# numpy is used by tests
[python.pipapi]
requirements = ["numpy"] # SWIPAT filed under: http://nvbugs/3193231
[[test]]
timeout = 300
stdoutFailPatterns.exclude = [
# Exclude carb.events leak that only shows up locally
"*[Error] [carb.events.plugin]*PooledAllocator*",
]
dependencies = [
# Required for gamepad node test
"omni.appwindow",
# Convenience for tests
"omni.graph.nodes",
"omni.inspect"
]
[documentation]
deps = [
["kit-sdk", "_build/docs/kit-sdk/latest"], # WAR to include OGN nodes until that workflow is moved
["omni.ui", "_build/docs/omni.ui/latest"], # ui_nodes.md references
]
pages = [
"docs/Overview.md",
"docs/ui_nodes.md",
"docs/CHANGELOG.md",
]
| 1,821 | TOML | 25.794117 | 102 | 0.679297 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/__init__.py | """Action Graph Functionality"""
# Required to be able to instantiate the object types
import omni.core
from ._impl.extension import _PublicExtension # noqa: F401
# Interface from the ABI bindings
from ._omni_graph_action import get_interface
| 247 | Python | 23.799998 | 59 | 0.773279 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnGateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Gate
This node controls a flow of execution based on the state of its gate. The gate can be opened or closed by execution pulses
sent to the gate controls
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnGateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Gate
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.enter
inputs.startClosed
inputs.toggle
Outputs:
outputs.exit
"""
# 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:enter', 'execution', 0, 'Enter', 'Incoming execution flow controlled by the gate', {}, True, None, False, ''),
('inputs:startClosed', 'bool', 0, 'Start Closed', 'If true the gate will start in a closed state', {}, True, False, False, ''),
('inputs:toggle', 'execution', 0, 'Toggle', 'The gate is opened or closed', {}, True, None, False, ''),
('outputs:exit', 'execution', 0, 'Exit', 'The enter pulses will be passed to this output if the gate is open', {}, True, None, False, ''),
])
@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.enter = og.AttributeRole.EXECUTION
role_data.inputs.toggle = og.AttributeRole.EXECUTION
role_data.outputs.exit = 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 enter(self):
data_view = og.AttributeValueHelper(self._attributes.enter)
return data_view.get()
@enter.setter
def enter(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.enter)
data_view = og.AttributeValueHelper(self._attributes.enter)
data_view.set(value)
@property
def startClosed(self):
data_view = og.AttributeValueHelper(self._attributes.startClosed)
return data_view.get()
@startClosed.setter
def startClosed(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.startClosed)
data_view = og.AttributeValueHelper(self._attributes.startClosed)
data_view.set(value)
@property
def toggle(self):
data_view = og.AttributeValueHelper(self._attributes.toggle)
return data_view.get()
@toggle.setter
def toggle(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.toggle)
data_view = og.AttributeValueHelper(self._attributes.toggle)
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 exit(self):
data_view = og.AttributeValueHelper(self._attributes.exit)
return data_view.get()
@exit.setter
def exit(self, value):
data_view = og.AttributeValueHelper(self._attributes.exit)
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 = OgnGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,666 | Python | 44.047297 | 146 | 0.655716 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnBranchDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Branch
Outputs an execution pulse along a branch based on a boolean condition
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnBranchDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Branch
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.condition
inputs.execIn
Outputs:
outputs.execFalse
outputs.execTrue
"""
# 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:condition', 'bool', 0, 'Condition', 'The boolean condition which determines the output direction', {}, True, False, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:execFalse', 'execution', 0, 'False', 'The output path when condition is False', {}, True, None, False, ''),
('outputs:execTrue', 'execution', 0, 'True', 'The output path when condition is True', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execFalse = og.AttributeRole.EXECUTION
role_data.outputs.execTrue = 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 condition(self):
data_view = og.AttributeValueHelper(self._attributes.condition)
return data_view.get()
@condition.setter
def condition(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.condition)
data_view = og.AttributeValueHelper(self._attributes.condition)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
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 execFalse(self):
data_view = og.AttributeValueHelper(self._attributes.execFalse)
return data_view.get()
@execFalse.setter
def execFalse(self, value):
data_view = og.AttributeValueHelper(self._attributes.execFalse)
data_view.set(value)
@property
def execTrue(self):
data_view = og.AttributeValueHelper(self._attributes.execTrue)
return data_view.get()
@execTrue.setter
def execTrue(self, value):
data_view = og.AttributeValueHelper(self._attributes.execTrue)
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 = OgnBranchDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnBranchDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnBranchDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,509 | Python | 43.896551 | 144 | 0.659087 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnMouseInputDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnMouseInput
Event node which fires when a mouse event occurs.
You can choose which mouse element this node reacts to. When mouse element
is chosen to be a button, the only meaningful outputs are: outputs:pressed, outputs:released and outputs:isPressed. When
scroll or move events are chosen, the only meaningful outputs are: outputs:valueChanged and outputs:value. You can choose
to output normalized or pixel coordinates of the mouse.
Pixel coordinates are the absolute position of the mouse cursor
in pixel unit. The original point is the upper left corner. The minimum value is 0, and the maximum value depends on the
size of the window.
Normalized coordinates are the relative position of the mouse cursor to the window. The value is always
between 0 and 1.
"""
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 OgnOnMouseInputDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnMouseInput
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.mouseElement
inputs.onlyPlayback
Outputs:
outputs.isPressed
outputs.pressed
outputs.released
outputs.value
outputs.valueChanged
Predefined Tokens:
tokens.LeftButton
tokens.MiddleButton
tokens.RightButton
tokens.NormalizedMove
tokens.PixelMove
tokens.Scroll
"""
# 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:mouseElement', 'token', 0, 'Mouse Element', 'The event to trigger the downstream execution ', {'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS: 'Left Button,Middle Button,Right Button,Normalized Move,Pixel Move,Scroll', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"LeftButton": "Left Button", "MiddleButton": "Middle Button", "RightButton": "Right Button", "NormalizedMove": "Normalized Move", "PixelMove": "Pixel Move", "Scroll": "Scroll"}', ogn.MetadataKeys.DEFAULT: '"Left Button"'}, True, "Left Button", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:isPressed', 'bool', 0, None, 'True if the mouse button was pressed, False if it was released or mouse element is not related to a button', {}, True, None, False, ''),
('outputs:pressed', 'execution', 0, 'Pressed', 'Executes when mouse button was pressed. Will not execute on move or scroll events', {}, True, None, False, ''),
('outputs:released', 'execution', 0, 'Released', 'Executes when mouse button was released. Will not execute on move or scroll events', {}, True, None, False, ''),
('outputs:value', 'float2', 0, 'Delta Value', 'The meaning of this output depends on Event In.\nNormalized Move: will output the normalized coordinates of mouse, each element of the vector is in the range of [0, 1]\nPixel Move: will output the absolute coordinates of mouse, each vector is in the range of [0, pixel width/height of the window]\nScroll: will output the change of scroll value\nOtherwise: will output [0,0]', {}, True, None, False, ''),
('outputs:valueChanged', 'execution', 0, 'Moved', 'Executes when user moves the cursor or scrolls the cursor. Will not execute on button events', {}, True, None, False, ''),
])
class tokens:
LeftButton = "Left Button"
MiddleButton = "Middle Button"
RightButton = "Right Button"
NormalizedMove = "Normalized Move"
PixelMove = "Pixel Move"
Scroll = "Scroll"
@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.outputs.pressed = og.AttributeRole.EXECUTION
role_data.outputs.released = og.AttributeRole.EXECUTION
role_data.outputs.valueChanged = 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 mouseElement(self):
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
return data_view.get()
@mouseElement.setter
def mouseElement(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.mouseElement)
data_view = og.AttributeValueHelper(self._attributes.mouseElement)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
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 isPressed(self):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
return data_view.get()
@isPressed.setter
def isPressed(self, value):
data_view = og.AttributeValueHelper(self._attributes.isPressed)
data_view.set(value)
@property
def pressed(self):
data_view = og.AttributeValueHelper(self._attributes.pressed)
return data_view.get()
@pressed.setter
def pressed(self, value):
data_view = og.AttributeValueHelper(self._attributes.pressed)
data_view.set(value)
@property
def released(self):
data_view = og.AttributeValueHelper(self._attributes.released)
return data_view.get()
@released.setter
def released(self, value):
data_view = og.AttributeValueHelper(self._attributes.released)
data_view.set(value)
@property
def value(self):
data_view = og.AttributeValueHelper(self._attributes.value)
return data_view.get()
@value.setter
def value(self, value):
data_view = og.AttributeValueHelper(self._attributes.value)
data_view.set(value)
@property
def valueChanged(self):
data_view = og.AttributeValueHelper(self._attributes.valueChanged)
return data_view.get()
@valueChanged.setter
def valueChanged(self, value):
data_view = og.AttributeValueHelper(self._attributes.valueChanged)
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 = OgnOnMouseInputDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnMouseInputDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnMouseInputDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 10,267 | Python | 48.84466 | 581 | 0.67264 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnImpulseEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnImpulseEvent
Triggers the output execution once when state is set
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnImpulseEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnImpulseEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.onlyPlayback
Outputs:
outputs.execOut
State:
state.enableImpulse
"""
# 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:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, 'Trigger', 'The execution output', {}, True, None, False, ''),
('state:enableImpulse', 'bool', 0, None, 'When true, execute output once and reset to false', {}, True, None, False, ''),
])
@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.outputs.execOut = 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 onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
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 execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
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)
@property
def enableImpulse(self):
data_view = og.AttributeValueHelper(self._attributes.enableImpulse)
return data_view.get()
@enableImpulse.setter
def enableImpulse(self, value):
data_view = og.AttributeValueHelper(self._attributes.enableImpulse)
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 = OgnOnImpulseEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnImpulseEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnImpulseEventDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,990 | Python | 45.44186 | 232 | 0.669282 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnStageEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnStageEvent
Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed
by the system:
Saved: USD file saved.
Selection Changed: USD Prim selection has changed.
Hierarchy Changed: USD stage
hierarchy has changed, e.g. a prim is added, deleted or moved.
OmniGraph Start Play: OmniGraph started
OmniGraph Stop Play:
OmniGraph stopped
Simulation Start Play: Simulation started
Simulation Stop Play: Simulation stopped
Animation Start Play:
Animation playback has started
Animation Stop Play: Animation playback has stopped
"""
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 OgnOnStageEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnStageEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.eventName
inputs.onlyPlayback
Outputs:
outputs.execOut
Predefined Tokens:
tokens.Saved
tokens.SelectionChanged
tokens.HierarchyChanged
tokens.OmniGraphStart
tokens.OmniGraphStop
tokens.SimulationStart
tokens.SimulationStop
tokens.AnimationStart
tokens.AnimationStop
"""
# 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:eventName', 'token', 0, None, 'The event of interest', {ogn.MetadataKeys.ALLOWED_TOKENS: 'Saved,Selection Changed,Hierarchy Changed,OmniGraph Start Play,OmniGraph Stop Play,Simulation Start Play,Simulation Stop Play,Animation Start Play,Animation Stop Play', 'default': 'Animation Start Play', 'displayGroup': 'parameters', ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.ALLOWED_TOKENS_RAW: '{"Saved": "Saved", "SelectionChanged": "Selection Changed", "HierarchyChanged": "Hierarchy Changed", "OmniGraphStart": "OmniGraph Start Play", "OmniGraphStop": "OmniGraph Stop Play", "SimulationStart": "Simulation Start Play", "SimulationStop": "Simulation Stop Play", "AnimationStart": "Animation Start Play", "AnimationStop": "Animation Stop Play"}'}, True, "", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, None, 'The execution output', {}, True, None, False, ''),
])
class tokens:
Saved = "Saved"
SelectionChanged = "Selection Changed"
HierarchyChanged = "Hierarchy Changed"
OmniGraphStart = "OmniGraph Start Play"
OmniGraphStop = "OmniGraph Stop Play"
SimulationStart = "Simulation Start Play"
SimulationStop = "Simulation Stop Play"
AnimationStart = "Animation Start Play"
AnimationStop = "Animation Stop Play"
@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.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback]
self._batchedReadValues = ["", True]
@property
def eventName(self):
return self._batchedReadValues[0]
@eventName.setter
def eventName(self, value):
self._batchedReadValues[0] = value
@property
def onlyPlayback(self):
return self._batchedReadValues[1]
@onlyPlayback.setter
def onlyPlayback(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 = {"execOut", "_batchedWriteValues"}
"""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 execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = 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 _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 = OgnOnStageEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnStageEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.OnStageEvent'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnOnStageEventDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnOnStageEventDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnOnStageEventDatabase(node)
try:
compute_function = getattr(OgnOnStageEventDatabase.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 OgnOnStageEventDatabase.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):
OgnOnStageEventDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnOnStageEventDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnOnStageEventDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.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.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Stage Event")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Executes when the specified Stage Event occurs. Stage Events are emitted when certain USD stage-related actions are performed by the system:\n Saved: USD file saved.\n Selection Changed: USD Prim selection has changed.\n Hierarchy Changed: USD stage hierarchy has changed, e.g. a prim is added, deleted or moved.\n OmniGraph Start Play: OmniGraph started\n OmniGraph Stop Play: OmniGraph stopped\n Simulation Start Play: Simulation started\n Simulation Stop Play: Simulation stopped\n Animation Start Play: Animation playback has started\n Animation Stop Play: Animation playback has stopped")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
__hints = node_type.get_scheduling_hints()
if __hints is not None:
__hints.compute_rule = og.eComputeRule.E_ON_REQUEST
OgnOnStageEventDatabase.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(OgnOnStageEventDatabase.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):
OgnOnStageEventDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnOnStageEventDatabase.abi, 3)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.OnStageEvent")
| 14,352 | Python | 47.489865 | 790 | 0.651965 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnForEachDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.ForEach
Executes the a loop body once for each element in the input array. The finished output is executed after all iterations are
complete
"""
from typing import Any
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnForEachDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.ForEach
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.arrayIn
inputs.execIn
Outputs:
outputs.arrayIndex
outputs.element
outputs.finished
outputs.loopBody
"""
# 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:arrayIn', 'bool[],colord[3][],colord[4][],colorf[3][],colorf[4][],colorh[3][],colorh[4][],double[2][],double[3][],double[4][],double[],float[2][],float[3][],float[4][],float[],frame[4][],half[2][],half[3][],half[4][],half[],int64[],int[2][],int[3][],int[4][],int[],matrixd[3][],matrixd[4][],normald[3][],normalf[3][],normalh[3][],pointd[3][],pointf[3][],pointh[3][],quatd[4][],quatf[4][],quath[4][],texcoordd[2][],texcoordd[3][],texcoordf[2][],texcoordf[3][],texcoordh[2][],texcoordh[3][],timecode[],token[],transform[4][],uchar[],uint64[],uint[],vectord[3][],vectorf[3][],vectorh[3][]', 1, 'Input Array', 'The array to loop over', {}, True, None, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('outputs:arrayIndex', 'int', 0, None, 'The current or last index visited', {}, True, None, False, ''),
('outputs:element', 'bool,colord[3],colord[4],colorf[3],colorf[4],colorh[3],colorh[4],double,double[2],double[3],double[4],float,float[2],float[3],float[4],frame[4],half,half[2],half[3],half[4],int,int64,int[2],int[3],int[4],matrixd[3],matrixd[4],normald[3],normalf[3],normalh[3],pointd[3],pointf[3],pointh[3],quatd[4],quatf[4],quath[4],texcoordd[2],texcoordd[3],texcoordf[2],texcoordf[3],texcoordh[2],texcoordh[3],timecode,token,transform[4],uchar,uint,uint64,vectord[3],vectorf[3],vectorh[3]', 1, None, 'The current or last element of the array visited', {}, True, None, False, ''),
('outputs:finished', 'execution', 0, None, 'Executed when the loop is finished', {}, True, None, False, ''),
('outputs:loopBody', 'execution', 0, None, 'Executed for each element of the array', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.finished = og.AttributeRole.EXECUTION
role_data.outputs.loopBody = 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 arrayIn(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute inputs.arrayIn"""
return og.RuntimeAttribute(self._attributes.arrayIn.get_attribute_data(), self._context, True)
@arrayIn.setter
def arrayIn(self, value_to_set: Any):
"""Assign another attribute's value to outputs.arrayIn"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.arrayIn.value = value_to_set.value
else:
self.arrayIn.value = value_to_set
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
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 arrayIndex(self):
data_view = og.AttributeValueHelper(self._attributes.arrayIndex)
return data_view.get()
@arrayIndex.setter
def arrayIndex(self, value):
data_view = og.AttributeValueHelper(self._attributes.arrayIndex)
data_view.set(value)
@property
def element(self) -> og.RuntimeAttribute:
"""Get the runtime wrapper class for the attribute outputs.element"""
return og.RuntimeAttribute(self._attributes.element.get_attribute_data(), self._context, False)
@element.setter
def element(self, value_to_set: Any):
"""Assign another attribute's value to outputs.element"""
if isinstance(value_to_set, og.RuntimeAttribute):
self.element.value = value_to_set.value
else:
self.element.value = value_to_set
@property
def finished(self):
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
data_view = og.AttributeValueHelper(self._attributes.finished)
data_view.set(value)
@property
def loopBody(self):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
return data_view.get()
@loopBody.setter
def loopBody(self, value):
data_view = og.AttributeValueHelper(self._attributes.loopBody)
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 = OgnForEachDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnForEachDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnForEachDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,947 | Python | 50.131428 | 676 | 0.65005 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnCustomEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnCustomEvent
Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent
"""
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnCustomEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnCustomEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.eventName
inputs.onlyPlayback
Outputs:
outputs.bundle
outputs.execOut
outputs.path
"""
# 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:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:bundle', 'bundle', 0, 'Bundle', 'Bundle received with the event', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, 'Received', 'Executes when the event is received', {}, True, None, False, ''),
('outputs:path', 'token', 0, 'Path', 'The path associated with the received custom event', {}, True, None, False, ''),
])
@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.outputs.bundle = og.AttributeRole.BUNDLE
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback]
self._batchedReadValues = ["", True]
@property
def eventName(self):
return self._batchedReadValues[0]
@eventName.setter
def eventName(self, value):
self._batchedReadValues[0] = value
@property
def onlyPlayback(self):
return self._batchedReadValues[1]
@onlyPlayback.setter
def onlyPlayback(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 = {"execOut", "path", "_batchedWriteValues"}
"""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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=False, gpu_ptr_kinds={})
self._batchedWriteValues = { }
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute outputs.bundle"""
return self.__bundles.bundle
@bundle.setter
def bundle(self, bundle: og.BundleContents):
"""Overwrite the bundle attribute outputs.bundle with a new bundle"""
if not isinstance(bundle, og.BundleContents):
carb.log_error("Only bundle attributes can be assigned to another bundle attribute")
self.__bundles.bundle.bundle = bundle
@property
def execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = value
@property
def path(self):
value = self._batchedWriteValues.get(self._attributes.path)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.path)
return data_view.get()
@path.setter
def path(self, value):
self._batchedWriteValues[self._attributes.path] = 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 _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 = OgnOnCustomEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnCustomEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.OnCustomEvent'
@staticmethod
def compute(context, node):
def database_valid():
if not db.outputs.bundle.valid:
db.log_error('Required bundle outputs.bundle is invalid, compute skipped')
return False
return True
try:
per_node_data = OgnOnCustomEventDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnOnCustomEventDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnOnCustomEventDatabase(node)
try:
compute_function = getattr(OgnOnCustomEventDatabase.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 OgnOnCustomEventDatabase.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):
OgnOnCustomEventDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnOnCustomEventDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnOnCustomEventDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.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.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On Custom Event")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when the specified custom event is sent. This node is used in combination with SendCustomEvent")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
__hints = node_type.get_scheduling_hints()
if __hints is not None:
__hints.compute_rule = og.eComputeRule.E_ON_REQUEST
OgnOnCustomEventDatabase.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(OgnOnCustomEventDatabase.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):
OgnOnCustomEventDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnOnCustomEventDatabase.abi, 2)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.OnCustomEvent")
| 13,740 | Python | 45.422297 | 232 | 0.628384 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnObjectChangeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnObjectChange
Executes an output execution pulse when the watched USD Object changes
"""
import usdrt
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnObjectChangeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnObjectChange
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.name
inputs.onlyPlayback
inputs.path
inputs.prim
Outputs:
outputs.changed
outputs.propertyName
"""
# 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:name', 'token', 0, 'Property Name', 'The name of the property to watch if prim input is set', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, None, False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:path', 'path', 0, 'Path', 'The path of object of interest (property or prim). If the prim input has a target, this is ignored', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, None, True, 'Use prim input instead'),
('inputs:prim', 'target', 0, 'Prim', 'The prim of interest. If this has a target, the path input will be ignored', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, False, [], False, ''),
('outputs:changed', 'execution', 0, 'Changed', 'The execution output', {}, True, None, False, ''),
('outputs:propertyName', 'token', 0, 'Property Name', 'The name of the property that changed', {}, True, None, False, ''),
])
@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.path = og.AttributeRole.PATH
role_data.inputs.prim = og.AttributeRole.TARGET
role_data.outputs.changed = 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 name(self):
data_view = og.AttributeValueHelper(self._attributes.name)
return data_view.get()
@name.setter
def name(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.name)
data_view = og.AttributeValueHelper(self._attributes.name)
data_view.set(value)
@property
def onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
@property
def path(self):
data_view = og.AttributeValueHelper(self._attributes.path)
return data_view.get()
@path.setter
def path(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.path)
data_view = og.AttributeValueHelper(self._attributes.path)
data_view.set(value)
self.path_size = data_view.get_array_size()
@property
def prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
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 changed(self):
data_view = og.AttributeValueHelper(self._attributes.changed)
return data_view.get()
@changed.setter
def changed(self, value):
data_view = og.AttributeValueHelper(self._attributes.changed)
data_view.set(value)
@property
def propertyName(self):
data_view = og.AttributeValueHelper(self._attributes.propertyName)
return data_view.get()
@propertyName.setter
def propertyName(self, value):
data_view = og.AttributeValueHelper(self._attributes.propertyName)
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 = OgnOnObjectChangeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnObjectChangeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnObjectChangeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 8,099 | Python | 45.285714 | 232 | 0.651068 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnVariableChangeDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnVariableChange
Executes an output execution pulse when the chosen variable changes
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnVariableChangeDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnVariableChange
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.onlyPlayback
inputs.variableName
Outputs:
outputs.changed
"""
# 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:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('inputs:variableName', 'token', 0, 'Variable Name', 'The name of the graph variable to use.', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''),
('outputs:changed', 'execution', 0, 'Changed', 'The execution output', {}, True, None, False, ''),
])
@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.outputs.changed = 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 onlyPlayback(self):
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
return data_view.get()
@onlyPlayback.setter
def onlyPlayback(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.onlyPlayback)
data_view = og.AttributeValueHelper(self._attributes.onlyPlayback)
data_view.set(value)
@property
def variableName(self):
data_view = og.AttributeValueHelper(self._attributes.variableName)
return data_view.get()
@variableName.setter
def variableName(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.variableName)
data_view = og.AttributeValueHelper(self._attributes.variableName)
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 changed(self):
data_view = og.AttributeValueHelper(self._attributes.changed)
return data_view.get()
@changed.setter
def changed(self, value):
data_view = og.AttributeValueHelper(self._attributes.changed)
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 = OgnOnVariableChangeDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnVariableChangeDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnVariableChangeDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,137 | Python | 46.215384 | 232 | 0.670034 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnPlaybackTickDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnPlaybackTick
Executes an output execution pulse during playback
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnPlaybackTickDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnPlaybackTick
Class Members:
node: Node being evaluated
Attribute Value Properties:
Outputs:
outputs.deltaSeconds
outputs.frame
outputs.tick
outputs.time
"""
# 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([
('outputs:deltaSeconds', 'double', 0, 'Delta Seconds', 'The number of seconds elapsed since the last update', {}, True, None, False, ''),
('outputs:frame', 'double', 0, 'Frame', 'The global playback time in frames, equivalent to (time * fps)', {}, True, None, False, ''),
('outputs:tick', 'execution', 0, 'Tick', 'The execution output', {}, True, None, False, ''),
('outputs:time', 'double', 0, 'Time', 'The global playback time in seconds', {}, True, None, False, ''),
])
@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.outputs.tick = 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 = []
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 deltaSeconds(self):
data_view = og.AttributeValueHelper(self._attributes.deltaSeconds)
return data_view.get()
@deltaSeconds.setter
def deltaSeconds(self, value):
data_view = og.AttributeValueHelper(self._attributes.deltaSeconds)
data_view.set(value)
@property
def frame(self):
data_view = og.AttributeValueHelper(self._attributes.frame)
return data_view.get()
@frame.setter
def frame(self, value):
data_view = og.AttributeValueHelper(self._attributes.frame)
data_view.set(value)
@property
def tick(self):
data_view = og.AttributeValueHelper(self._attributes.tick)
return data_view.get()
@tick.setter
def tick(self, value):
data_view = og.AttributeValueHelper(self._attributes.tick)
data_view.set(value)
@property
def time(self):
data_view = og.AttributeValueHelper(self._attributes.time)
return data_view.get()
@time.setter
def time(self, value):
data_view = og.AttributeValueHelper(self._attributes.time)
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 = OgnOnPlaybackTickDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnPlaybackTickDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnPlaybackTickDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,147 | Python | 43.875912 | 145 | 0.659021 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnMessageBusEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnMessageBusEvent
Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python:
msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1':
42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example,
42 would be copied to outputs:arg1 if possible
"""
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 OgnOnMessageBusEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnMessageBusEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.eventName
inputs.onlyPlayback
Outputs:
outputs.execOut
"""
# 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:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {ogn.MetadataKeys.LITERAL_ONLY: '1'}, True, "", False, ''),
('inputs:onlyPlayback', 'bool', 0, 'Only Simulate On Play', 'When true, the node is only computed while Stage is being played.', {ogn.MetadataKeys.LITERAL_ONLY: '1', ogn.MetadataKeys.DEFAULT: 'true'}, True, True, False, ''),
('outputs:execOut', 'execution', 0, 'Received', 'Executes when the event is received', {}, True, None, False, ''),
])
@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.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"eventName", "onlyPlayback", "_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.eventName, self._attributes.onlyPlayback]
self._batchedReadValues = ["", True]
@property
def eventName(self):
return self._batchedReadValues[0]
@eventName.setter
def eventName(self, value):
self._batchedReadValues[0] = value
@property
def onlyPlayback(self):
return self._batchedReadValues[1]
@onlyPlayback.setter
def onlyPlayback(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 = {"execOut", "_batchedWriteValues"}
"""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 execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = 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 _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 = OgnOnMessageBusEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnMessageBusEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.OnMessageBusEvent'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnOnMessageBusEventDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnOnMessageBusEventDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnOnMessageBusEventDatabase(node)
try:
compute_function = getattr(OgnOnMessageBusEventDatabase.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 OgnOnMessageBusEventDatabase.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):
OgnOnMessageBusEventDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnOnMessageBusEventDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnOnMessageBusEventDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.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.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "On MessageBus Event")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Event node which fires when the specified event is popped from the App Message Bus. Carb events can be sent with Python: msg = carb.events.type_from_string('my_event_name') omni.kit.app.get_app().get_message_bus_event_stream().push(msg, payload={'arg1': 42}) The event payload data will be copied in to matching dynamic output attributes if they exist. In the previous example, 42 would be copied to outputs:arg1 if possible")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
__hints = node_type.get_scheduling_hints()
if __hints is not None:
__hints.compute_rule = og.eComputeRule.E_ON_REQUEST
OgnOnMessageBusEventDatabase.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(OgnOnMessageBusEventDatabase.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):
OgnOnMessageBusEventDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnOnMessageBusEventDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.OnMessageBusEvent")
| 12,828 | Python | 47.594697 | 496 | 0.642501 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnCountdownDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Countdown
Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown
is complete it triggers the finished output. The first compute does not generate a tick output.
"""
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 OgnCountdownDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Countdown
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.duration
inputs.execIn
inputs.period
Outputs:
outputs.alpha
outputs.finished
outputs.tick
outputs.tickValue
State:
state.count
"""
# 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:duration', 'int', 0, None, 'The duration of the delay in ticks', {ogn.MetadataKeys.DEFAULT: '5'}, True, 5, False, ''),
('inputs:execIn', 'execution', 0, None, 'The input execution', {}, True, None, False, ''),
('inputs:period', 'int', 0, None, 'The period of the pulse in ticks', {ogn.MetadataKeys.DEFAULT: '1'}, True, 1, False, ''),
('outputs:alpha', 'float', 0, None, "normalized progress in the range IE 'tickValue'/'duration'", {}, True, None, False, ''),
('outputs:finished', 'execution', 0, None, 'Triggered after duration ticks is finished', {}, True, None, False, ''),
('outputs:tick', 'execution', 0, None, "Triggered every 'period' ticks", {}, True, None, False, ''),
('outputs:tickValue', 'int', 0, None, 'The current tick value in the range [1, duration]', {}, True, None, False, ''),
('state:count', 'int', 0, None, 'The number of ticks elapsed, the first tick is 0', {ogn.MetadataKeys.DEFAULT: '-1'}, True, -1, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.finished = og.AttributeRole.EXECUTION
role_data.outputs.tick = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"duration", "execIn", "period", "_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.duration, self._attributes.execIn, self._attributes.period]
self._batchedReadValues = [5, None, 1]
@property
def duration(self):
return self._batchedReadValues[0]
@duration.setter
def duration(self, value):
self._batchedReadValues[0] = value
@property
def execIn(self):
return self._batchedReadValues[1]
@execIn.setter
def execIn(self, value):
self._batchedReadValues[1] = value
@property
def period(self):
return self._batchedReadValues[2]
@period.setter
def period(self, value):
self._batchedReadValues[2] = 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 = {"alpha", "finished", "tick", "tickValue", "_batchedWriteValues"}
"""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 alpha(self):
value = self._batchedWriteValues.get(self._attributes.alpha)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.alpha)
return data_view.get()
@alpha.setter
def alpha(self, value):
self._batchedWriteValues[self._attributes.alpha] = value
@property
def finished(self):
value = self._batchedWriteValues.get(self._attributes.finished)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
self._batchedWriteValues[self._attributes.finished] = value
@property
def tick(self):
value = self._batchedWriteValues.get(self._attributes.tick)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.tick)
return data_view.get()
@tick.setter
def tick(self, value):
self._batchedWriteValues[self._attributes.tick] = value
@property
def tickValue(self):
value = self._batchedWriteValues.get(self._attributes.tickValue)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.tickValue)
return data_view.get()
@tickValue.setter
def tickValue(self, value):
self._batchedWriteValues[self._attributes.tickValue] = 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 _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 count(self):
data_view = og.AttributeValueHelper(self._attributes.count)
return data_view.get()
@count.setter
def count(self, value):
data_view = og.AttributeValueHelper(self._attributes.count)
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 = OgnCountdownDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnCountdownDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnCountdownDatabase.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(OgnCountdownDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.Countdown'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnCountdownDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnCountdownDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnCountdownDatabase(node)
try:
compute_function = getattr(OgnCountdownDatabase.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 OgnCountdownDatabase.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):
OgnCountdownDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnCountdownDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnCountdownDatabase.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(OgnCountdownDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnCountdownDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnCountdownDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnCountdownDatabase.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(OgnCountdownDatabase.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.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Countdown")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,flowControl")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Delays for a number of updates (the duration) while firing output tick activations with a given period. When the countdown is complete it triggers the finished output. The first compute does not generate a tick output.")
node_type.set_metadata(ogn.MetadataKeys.EXCLUSIONS, "tests")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnCountdownDatabase.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(OgnCountdownDatabase.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):
OgnCountdownDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnCountdownDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.Countdown")
| 14,717 | Python | 43.6 | 290 | 0.620711 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSendCustomEventDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.SendCustomEvent
Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName
"""
import sys
import traceback
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSendCustomEventDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.SendCustomEvent
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.bundle
inputs.eventName
inputs.execIn
inputs.path
Outputs:
outputs.execOut
"""
# 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:bundle', 'bundle', 0, 'Bundle', 'Bundle to be sent with the event', {}, False, None, False, ''),
('inputs:eventName', 'token', 0, 'Event Name', 'The name of the custom event', {}, True, "", False, ''),
('inputs:execIn', 'execution', 0, None, 'Input Execution', {}, True, None, False, ''),
('inputs:path', 'token', 0, 'Path', 'The path associated with the event', {}, True, "", False, ''),
('outputs:execOut', 'execution', 0, None, 'Output Execution', {}, True, None, False, ''),
])
@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.bundle = og.AttributeRole.BUNDLE
role_data.inputs.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = og.AttributeRole.EXECUTION
return role_data
class ValuesForInputs(og.DynamicAttributeAccess):
LOCAL_PROPERTY_NAMES = {"eventName", "execIn", "path", "_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.__bundles = og.BundleContainer(context, node, attributes, [], read_only=True, gpu_ptr_kinds={})
self._batchedReadAttributes = [self._attributes.eventName, self._attributes.execIn, self._attributes.path]
self._batchedReadValues = ["", None, ""]
@property
def bundle(self) -> og.BundleContents:
"""Get the bundle wrapper class for the attribute inputs.bundle"""
return self.__bundles.bundle
@property
def eventName(self):
return self._batchedReadValues[0]
@eventName.setter
def eventName(self, value):
self._batchedReadValues[0] = value
@property
def execIn(self):
return self._batchedReadValues[1]
@execIn.setter
def execIn(self, value):
self._batchedReadValues[1] = value
@property
def path(self):
return self._batchedReadValues[2]
@path.setter
def path(self, value):
self._batchedReadValues[2] = 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 = {"execOut", "_batchedWriteValues"}
"""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 execOut(self):
value = self._batchedWriteValues.get(self._attributes.execOut)
if value:
return value
else:
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
self._batchedWriteValues[self._attributes.execOut] = 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 _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 = OgnSendCustomEventDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSendCustomEventDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'get_node_type', None)
if callable(get_node_type_function):
return get_node_type_function()
return 'omni.graph.action.SendCustomEvent'
@staticmethod
def compute(context, node):
def database_valid():
return True
try:
per_node_data = OgnSendCustomEventDatabase.PER_NODE_DATA[node.node_id()]
db = per_node_data.get('_db')
if db is None:
db = OgnSendCustomEventDatabase(node)
per_node_data['_db'] = db
if not database_valid():
per_node_data['_db'] = None
return False
except:
db = OgnSendCustomEventDatabase(node)
try:
compute_function = getattr(OgnSendCustomEventDatabase.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 OgnSendCustomEventDatabase.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):
OgnSendCustomEventDatabase._initialize_per_node_data(node)
initialize_function = getattr(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'initialize', None)
if callable(initialize_function):
initialize_function(context, node)
per_node_data = OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.NODE_TYPE_CLASS, 'release', None)
if callable(release_function):
release_function(node)
OgnSendCustomEventDatabase._release_per_node_data(node)
@staticmethod
def release_instance(node, target):
OgnSendCustomEventDatabase._release_per_node_instance_data(node, target)
@staticmethod
def update_node_version(context, node, old_version, new_version):
update_node_version_function = getattr(OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.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.graph.action")
node_type.set_metadata(ogn.MetadataKeys.UI_NAME, "Send Custom Event")
node_type.set_metadata(ogn.MetadataKeys.CATEGORIES, "graph:action,event")
node_type.set_metadata(ogn.MetadataKeys.DESCRIPTION, "Sends a custom event, which will asynchronously trigger any OnCustomEvent nodes which are listening for the same eventName")
node_type.set_metadata(ogn.MetadataKeys.LANGUAGE, "Python")
OgnSendCustomEventDatabase.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(OgnSendCustomEventDatabase.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):
OgnSendCustomEventDatabase.NODE_TYPE_CLASS = node_type_class
og.register_node_type(OgnSendCustomEventDatabase.abi, 1)
@staticmethod
def deregister():
og.deregister_node_type("omni.graph.action.SendCustomEvent")
| 12,692 | Python | 44.494623 | 194 | 0.630791 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnOnLoadedDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.OnLoaded
Triggers the output on the first update of the graph after it is created or loaded. This will run before any other event
node, and will only run once after this node is created.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnOnLoadedDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.OnLoaded
Class Members:
node: Node being evaluated
Attribute Value Properties:
Outputs:
outputs.execOut
"""
# 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([
('outputs:execOut', 'execution', 0, None, 'Executes after graph creation or loading', {}, True, None, False, ''),
])
@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.outputs.execOut = 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 = []
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 execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
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 = OgnOnLoadedDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnOnLoadedDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnOnLoadedDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 4,832 | Python | 46.382352 | 121 | 0.682947 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSyncGateDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.SyncGate
This node triggers when all its input executions have triggered successively at the same synchronization value.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSyncGateDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.SyncGate
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.execIn
inputs.syncValue
Outputs:
outputs.execOut
outputs.syncValue
"""
# 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''),
('inputs:syncValue', 'uint64', 0, 'Sync', 'Value of the synchronization reference.', {}, True, 0, False, ''),
('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''),
('outputs:syncValue', 'uint64', 0, 'Sync', 'Value of the synchronization reference.', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.execOut = 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 execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def syncValue(self):
data_view = og.AttributeValueHelper(self._attributes.syncValue)
return data_view.get()
@syncValue.setter
def syncValue(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.syncValue)
data_view = og.AttributeValueHelper(self._attributes.syncValue)
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 execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
data_view.set(value)
@property
def syncValue(self):
data_view = og.AttributeValueHelper(self._attributes.syncValue)
return data_view.get()
@syncValue.setter
def syncValue(self, value):
data_view = og.AttributeValueHelper(self._attributes.syncValue)
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 = OgnSyncGateDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSyncGateDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSyncGateDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,447 | Python | 44.090909 | 121 | 0.658291 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnMultisequenceDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Multisequence
Outputs an execution pulse along each of its N outputs in sequence. For every single input execution pulse, each and every
output will be exclusively enabled in order.
"""
import carb
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnMultisequenceDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Multisequence
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.execIn
Outputs:
outputs.output0
"""
# 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''),
('outputs:output0', 'execution', 0, None, 'Output execution', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.output0 = 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 execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
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 output0(self):
data_view = og.AttributeValueHelper(self._attributes.output0)
return data_view.get()
@output0.setter
def output0(self, value):
data_view = og.AttributeValueHelper(self._attributes.output0)
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 = OgnMultisequenceDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnMultisequenceDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnMultisequenceDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 5,467 | Python | 44.949579 | 122 | 0.673496 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnDelayDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Delay
This node suspends the graph for a period of time before continuing. This node, and nodes upstream of this node are locked
for the duration of the delay, which means any subsequent executions will be ignored.
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnDelayDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Delay
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.duration
inputs.execIn
Outputs:
outputs.finished
"""
# 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:duration', 'double', 0, 'Duration', 'The duration of the delay (Seconds)', {}, True, 0.0, False, ''),
('inputs:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''),
('outputs:finished', 'execution', 0, 'Finished', 'Triggered when the delay is finished', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.outputs.finished = 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 duration(self):
data_view = og.AttributeValueHelper(self._attributes.duration)
return data_view.get()
@duration.setter
def duration(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.duration)
data_view = og.AttributeValueHelper(self._attributes.duration)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
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 finished(self):
data_view = og.AttributeValueHelper(self._attributes.finished)
return data_view.get()
@finished.setter
def finished(self, value):
data_view = og.AttributeValueHelper(self._attributes.finished)
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 = OgnDelayDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnDelayDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnDelayDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,058 | Python | 44.901515 | 124 | 0.66375 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnCounterDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.Counter
This node counts the number of times it is computed since being reset
"""
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnCounterDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.Counter
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.execIn
inputs.reset
Outputs:
outputs.count
outputs.execOut
State:
state.count
"""
# 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:execIn', 'execution', 0, 'Execute In', 'The input execution', {}, True, None, False, ''),
('inputs:reset', 'execution', 0, 'Reset', 'Reset the internal counter', {}, True, None, False, ''),
('outputs:count', 'int', 0, 'Count', 'The count value', {}, True, None, False, ''),
('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''),
('state:count', 'int', 0, None, 'The counter state', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.inputs.reset = og.AttributeRole.EXECUTION
role_data.outputs.execOut = 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 execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def reset(self):
data_view = og.AttributeValueHelper(self._attributes.reset)
return data_view.get()
@reset.setter
def reset(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.reset)
data_view = og.AttributeValueHelper(self._attributes.reset)
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 count(self):
data_view = og.AttributeValueHelper(self._attributes.count)
return data_view.get()
@count.setter
def count(self, value):
data_view = og.AttributeValueHelper(self._attributes.count)
data_view.set(value)
@property
def execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
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)
@property
def count(self):
data_view = og.AttributeValueHelper(self._attributes.count)
return data_view.get()
@count.setter
def count(self, value):
data_view = og.AttributeValueHelper(self._attributes.count)
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 = OgnCounterDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnCounterDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnCounterDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 6,806 | Python | 42.356688 | 111 | 0.645901 |
omniverse-code/kit/exts/omni.graph.action/omni/graph/action/ogn/OgnSetPrimActiveDatabase.py | """Support for simplified access to data on nodes of type omni.graph.action.SetPrimActive
Set a Prim active or not in the stage.
"""
import usdrt
import omni.graph.core as og
import omni.graph.core._omni_graph_core as _og
import omni.graph.tools.ogn as ogn
class OgnSetPrimActiveDatabase(og.Database):
"""Helper class providing simplified access to data on nodes of type omni.graph.action.SetPrimActive
Class Members:
node: Node being evaluated
Attribute Value Properties:
Inputs:
inputs.active
inputs.execIn
inputs.prim
inputs.primTarget
Outputs:
outputs.execOut
"""
# 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:active', 'bool', 0, None, 'Wheter to set the prim active or not', {}, True, False, False, ''),
('inputs:execIn', 'execution', 0, None, 'Input execution', {}, True, None, False, ''),
('inputs:prim', 'path', 0, 'Prim Path', 'The prim to be (de)activated', {}, True, "", True, 'Use the primTarget input instead'),
('inputs:primTarget', 'target', 0, 'Prim', 'The prim to be (de)activated', {}, True, [], False, ''),
('outputs:execOut', 'execution', 0, 'Execute Out', 'The output execution', {}, True, None, False, ''),
])
@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.execIn = og.AttributeRole.EXECUTION
role_data.inputs.prim = og.AttributeRole.PATH
role_data.inputs.primTarget = og.AttributeRole.TARGET
role_data.outputs.execOut = 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 active(self):
data_view = og.AttributeValueHelper(self._attributes.active)
return data_view.get()
@active.setter
def active(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.active)
data_view = og.AttributeValueHelper(self._attributes.active)
data_view.set(value)
@property
def execIn(self):
data_view = og.AttributeValueHelper(self._attributes.execIn)
return data_view.get()
@execIn.setter
def execIn(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.execIn)
data_view = og.AttributeValueHelper(self._attributes.execIn)
data_view.set(value)
@property
def prim(self):
data_view = og.AttributeValueHelper(self._attributes.prim)
return data_view.get()
@prim.setter
def prim(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.prim)
data_view = og.AttributeValueHelper(self._attributes.prim)
data_view.set(value)
self.prim_size = data_view.get_array_size()
@property
def primTarget(self):
data_view = og.AttributeValueHelper(self._attributes.primTarget)
return data_view.get()
@primTarget.setter
def primTarget(self, value):
if self._setting_locked:
raise og.ReadOnlyError(self._attributes.primTarget)
data_view = og.AttributeValueHelper(self._attributes.primTarget)
data_view.set(value)
self.primTarget_size = data_view.get_array_size()
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 execOut(self):
data_view = og.AttributeValueHelper(self._attributes.execOut)
return data_view.get()
@execOut.setter
def execOut(self, value):
data_view = og.AttributeValueHelper(self._attributes.execOut)
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 = OgnSetPrimActiveDatabase.ValuesForInputs(node, self.attributes.inputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_OUTPUT)
self.outputs = OgnSetPrimActiveDatabase.ValuesForOutputs(node, self.attributes.outputs, dynamic_attributes)
dynamic_attributes = self.dynamic_attribute_data(node, og.AttributePortType.ATTRIBUTE_PORT_TYPE_STATE)
self.state = OgnSetPrimActiveDatabase.ValuesForState(node, self.attributes.state, dynamic_attributes)
| 7,275 | Python | 43.365853 | 136 | 0.647423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.