file_path
stringlengths
20
207
content
stringlengths
5
3.85M
size
int64
5
3.85M
lang
stringclasses
9 values
avg_line_length
float64
1.33
100
max_line_length
int64
4
993
alphanum_fraction
float64
0.26
0.93
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/object_info_manipulator.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. __all__ = ["ObjectInfoManipulator"] from omni.ui import color as cl from omni.ui import scene as sc import omni.ui as ui import carb LEADER_LINE_CIRCLE_RADIUS = 2 LEADER_LINE_THICKNESS = 2 LEADER_LINE_SEGMENT_LENGTH = 20 VERTICAL_MULT = 1.5 HORIZ_TEXT_OFFSET = 5 LINE1_OFFSET = 3 LINE2_OFFSET = 0 class ObjectInfoManipulator(sc.Manipulator): """Manipulator that displays the object path and material assignment with a leader line to the top of the object's bounding box. """ def on_build(self): carb.log_info("ObjectInfoManipulator - on_build") """Called when the model is changed and rebuilds the whole manipulator""" if not self.model: return for i in range(self.model.get_num_prims()): position = self.model.get_position(i) infoBlurb = str(self.model.get_name(i)).replace("/World/RGrps/", "") infoBlurb = infoBlurb.replace("/World/Subs/", "") infoBlurb = infoBlurb.replace("/World/Locs/", "") infoBlurb = infoBlurb.replace("/World/Types/", "") if infoBlurb == 'None': continue # Move everything to where the object is with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*position)): # Rotate everything to face the camera with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): # Leader lines with a small circle on the end sc.Arc(LEADER_LINE_CIRCLE_RADIUS, axis=2, color=cl.yellow) sc.Line([0, 0, 0], [0, LEADER_LINE_SEGMENT_LENGTH, 0], color=cl.yellow, thickness=LEADER_LINE_THICKNESS) sc.Line([0, LEADER_LINE_SEGMENT_LENGTH, 0], [LEADER_LINE_SEGMENT_LENGTH, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0], color=cl.yellow, thickness=LEADER_LINE_THICKNESS) # Shift text to the end of the leader line with some offset with sc.Transform(transform=sc.Matrix44.get_translation_matrix( LEADER_LINE_SEGMENT_LENGTH + HORIZ_TEXT_OFFSET, LEADER_LINE_SEGMENT_LENGTH * VERTICAL_MULT, 0)): with sc.Transform(scale_to=sc.Space.SCREEN): # Offset each Label vertically in screen space with sc.Transform(transform=sc.Matrix44.get_translation_matrix(0, LINE1_OFFSET, 0)): sc.Label(f"Resource: {infoBlurb}",alignment=ui.Alignment.LEFT_BOTTOM) def on_model_updated(self, item): # Regenerate the manipulator self.invalidate()
3,182
Python
43.830985
112
0.615651
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/group_tag.py
from .group_base import GroupBase from pxr import Gf, UsdGeom, UsdLux, Usd, Sdf from .math_utils import calcPlaneSizeForGroup from .prim_utils import cleanup_prim_path import locale import asyncio import carb import omni.client import omni.kit.app import omni.ui as ui import omni.usd import omni.kit.commands #--- SUBSCRIPTION BASED GROUPS class TagGrpView(GroupBase): def __init__(self, viewPath:str, scale:float, upAxis:str, shapeUpAxis:str, symPlanes:bool, binPack:bool): self._scale = scale self._upAxis = upAxis self._shapeUpAxis = shapeUpAxis self._view_path = viewPath self._symPlanes = symPlanes self._binPack = binPack super().__init__() def calcGroupPlaneSizes(self): self._dataStore._lcl_groups = [] self._dataStore._lcl_sizes = [] if len(self._dataStore._tag_count) == 0: self._dataManager.refresh_data() #check it again if len(self._dataStore._tag_count) == 0: return 0 #temp group list to prep for planes, adds to main aggregate gpz = self._dataStore._tag_count.copy() for grp in gpz: size = calcPlaneSizeForGroup( scaleFactor=self._scale, resourceCount=self._dataStore._tag_count.get(grp) ) #mixed plane sizes self._dataStore._lcl_sizes.append(size) #Should the planes all be the same size ? if self._dataStore._use_symmetric_planes: sorted = self._dataStore._lcl_groups.sort(key=lambda element: element['size'], reverse=True) maxPlaneSize = sorted[0]["size"] groupCount = len(sorted) #Reset plane sizes self._dataStore._lcl_sizes = [] for count in range(0,groupCount): self._dataStore._lcl_sizes.append(maxPlaneSize) self._dataStore._lcl_groups = [] grp = cleanup_prim_path(self, grp) self._dataStore._lcl_groups.append({ "group":grp, "size":size }) def calulateCosts(self): for g in self._dataStore._lcl_groups: locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) try: self._cost = str(locale.currency(self._dataStore._tag_cost[g])) except: self._cost = "" # blank not 0, blank means dont show it at all #Abstact to load resources def loadResources(self): self.view_path = Sdf.Path(self.root_path.AppendPath(self._view_path)) if (len(self._dataStore._lcl_groups)) >0 : #Cycle all the loaded groups for grp in self._dataStore._lcl_groups: carb.log_info(grp) #Cleanup the group name for a prim path group_prim_path = self.view_path.AppendPath(grp["group"]) #match the group to the resource map for key, values in self._dataStore._map_tag.items(): #Is this the group? if key == grp["group"]: asyncio.ensure_future(self.loadGroupResources(key, group_prim_path, values)) def selectGroupPrims(self): self.paths = [] stage = omni.usd.get_context().get_stage() base = Sdf.Path("/World/Tags") curr_prim = stage.GetPrimAtPath(base) for prim in Usd.PrimRange(curr_prim): # only process shapes and meshes tmp_path = str(prim.GetPath()) if '/CollisionMesh' not in tmp_path: if '/CollisionPlane' not in tmp_path: self.paths.append(tmp_path) # for grp in self._dataStore._map_subscription.keys(): # grp_path = base.AppendPath(cleanup_prim_path(self, grp)) # self.paths.append(str(grp_path)) omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=[], new_selected_paths=self.paths, expand_in_stage=True)
4,096
Python
31.007812
109
0.568359
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/prim_utils.py
__all__ = ["create_plane", "get_font_size_from_length", "get_parent_child_prim_path", "create_and_place_prim", "log_transforms", "only_select_parent_prims"] import sys from tokenize import Double import omni.usd import omni.kit.commands import shutil import carb from pathlib import Path from pxr import Sdf from pxr import Gf, UsdGeom, UsdLux from .pillow_text import draw_text_on_image_at_position CURRENT_PATH = Path(__file__).parent RES_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data\\resources") async def create_and_place_prim(self, prim_type:str, prim_name:str, grp_name:str, sub_name:str, loc_name:str, cost:str, new_prim_path:str, shapeToRender:str, scale:float, position:Gf.Vec3f ): carb.log_info("Creating new prim: " + prim_type + " @ "+ new_prim_path + " shape: " + shapeToRender) stage = omni.usd.get_context().get_stage() # Create prim to add the reference to. try: prim = stage.DefinePrim(new_prim_path) prim.GetReferences().AddReference(shapeToRender) except: carb.log_error("Invalid prim path:" + str(new_prim_path)) return my_new_prim = stage.GetPrimAtPath(new_prim_path) my_new_prim.SetCustomDataByKey('res_type', prim_type) my_new_prim.SetCustomDataByKey('res_name', prim_name) my_new_prim.SetCustomDataByKey('res_sub', sub_name) my_new_prim.SetCustomDataByKey('res_grp', grp_name) my_new_prim.SetCustomDataByKey('res_loc', loc_name) my_new_prim.SetCustomDataByKey('res_cost', cost) #Default rotation rotation = Gf.Vec3f(0,0,0) translate = Gf.Vec3d(position[0], position[1], position[2]) #Are we still set to default? Change cube size and position if shapeToRender == "omniverse://localhost/MCE/3dIcons/scene.usd": scale = 3.0 position[2] = position[2] + 30 #Buffer the cube off the z #CUSTOM SHAPE OVERRIDES if prim_name.lower() == "observation_chair": scale =0.8 rotation = Gf.Vec3f(90,0,220) translate=Gf.Vec3d(position[0]+200, position[1]+200, position[2]) if prim_name.lower() == "leather_jacket": scale =0.25 rotation = Gf.Vec3f(90,0,0) translate=Gf.Vec3d(position[0]-20, position[1], position[2]-25) if prim_name.lower() == "coat_rack": scale =0.55 rotation = Gf.Vec3f(90,0,0) translate=Gf.Vec3d(position[0]-220, position[1]+210, position[2]+10) carb.log_info("Placing prim: " + shapeToRender + " | " + str(new_prim_path) + " @ " + "scl:" + str(scale) + " x:" + str(position[0]) + "," + " y:" + str(position[1]) + "," + " z:" + str(position[2])) api = UsdGeom.XformCommonAPI(my_new_prim) try: api.SetTranslate(translate) api.SetRotate(rotation,UsdGeom.XformCommonAPI.RotationOrderXYZ) api.SetScale(Gf.Vec3f(scale,scale,scale)) except: carb.log_error("Oops!", sys.exc_info()[0], "occurred.") #log the vectors def log_transforms(self, vectors): for v in vectors: logdata = str(vectors[v][0]) + "," + str(vectors[v][1]) + "," + str(vectors[v][2]) print(logdata) def draw_image(self, output_file:str, src_file:str, textToDraw:str, costToDraw:str): font = RES_PATH.joinpath("airstrike.ttf") font_size = get_font_size_from_length(len(textToDraw)) draw_text_on_image_at_position( input_image_path=src_file, output_image_path=output_file, textToDraw=str(textToDraw), costToDraw=str(costToDraw), x=180, y=1875, fillColor="White", font=font, fontSize=font_size ) #Creates a plane of a certain size in a specific location def create_plane(self,Path:str, Name :str, Size: int, Location: Gf.Vec3f, Color:Gf.Vec3f): stage_ref = omni.usd.get_context().get_stage() omni.kit.commands.execute('AddGroundPlaneCommand', stage=stage_ref, planePath=Path, axis="Z", size=Size, position=Location, color=Color) def cleanup_prim_path(self, Name: str): #print("cleanup: " + Name) nme = Name.replace("-", "_") nme = nme.replace(" ", "_") nme = nme.replace("/", "_") nme = nme.replace(".", "_") nme = nme.replace(":", "_") nme = nme.replace(";", "_") nme = nme.replace("(", "_") nme = nme.replace(")", "_") nme = nme.replace("[", "_") nme = nme.replace("]", "_") nme = nme.replace("#", "_") #if it starts with a number add a _ if nme[0].isnumeric(): nme = "_" + nme #dont start with a - if nme[0] == "-": nme = nme[1:len(nme[0])-1] #print("cleanup res: " + nme) return nme # Concats two Sdf.Paths and truncates he result to MAX_PATH_LENGTH def get_parent_child_prim_path(self, groupPath:Sdf.Path, resName:str): resName = cleanup_prim_path(self, resName) #prim_len = len(str(groupPath)) + len(resName) #if (prim_len) > 70: # diff = prim_len - 70 # trim = len(resName) - diff # resName = resName[:trim] try: shape_prim_path = Sdf.Path(groupPath.AppendPath(resName)) return shape_prim_path except: print("Oops!", sys.exc_info()[0], "occurred.") def only_select_parent_prims(prim_paths): paths = [] for path in prim_paths: if str(path).find("Collision") != -1: continue #skip paths with Collision in them if str(path).find("Baked") != -1: continue #skip paths with Baked in them parts = path.split("/") if parts[2] == "Looks": continue if parts[1] == "Environment": continue #Select the root object only. if len(parts) == 3: parentPath = "/" + parts[1] + "/" + parts[2] if len(parts) == 4: parentPath = "/" + parts[1] + "/" + parts[2] + "/" + parts[3] if len(parts) == 5: parentPath = "/" + parts[1] + "/" + parts[2] + "/" + parts[3] + "/" + parts[4] paths.append(parentPath) return paths def get_font_size_from_length(nameLength:int): if (nameLength < 10): font_size = 160 elif (nameLength < 15): font_size = 140 elif (nameLength < 20): font_size = 120 elif (nameLength < 30): font_size = 100 elif (nameLength < 50): font_size = 80 elif (nameLength < 60): font_size = 70 elif (nameLength < 70): font_size = 60 elif (nameLength < 80): font_size = 44 return font_size
6,658
Python
30.861244
156
0.580955
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/group_group.py
from tokenize import group from .group_base import GroupBase from pxr import Gf, UsdGeom, UsdLux, Usd, Sdf from .math_utils import calcPlaneSizeForGroup from .prim_utils import cleanup_prim_path import locale import asyncio import carb import omni.client import omni.kit.app import omni.ui as ui import omni.usd import omni.kit.commands #--- RESOURCE BASED GROUPS class ResGrpView(GroupBase): def __init__(self, viewPath:str, scale:float, upAxis:str, shapeUpAxis:str, symPlanes:bool, binPack:bool): self._scale = scale self._upAxis = upAxis self._shapeUpAxis = shapeUpAxis self._view_path = viewPath self._symPlanes = symPlanes self._binPack = binPack super().__init__() #Determines the sizes of the group planes to create def calcGroupPlaneSizes(self): self._dataStore._lcl_groups = [] self._dataStore._lcl_sizes = [] if len(self._dataStore._group_count) == 0: self._dataManager.refresh_data() #check it again if len(self._dataStore._group_count) == 0: return 0 #Clone the groups gpz = self._dataStore._group_count.copy() for grp in gpz: size = calcPlaneSizeForGroup( scaleFactor=self._scale, resourceCount=self._dataStore._group_count.get(grp) ) #mixed plane sizes self._dataStore._lcl_sizes.append(size) grp = cleanup_prim_path(self, grp) self._dataStore._lcl_groups.append({ "group":grp, "size":size }) #Should the groups all be the same size ? if self._symPlanes: self._dataStore._lcl_sizes.sort(reverse=True) maxPlaneSize = self._dataStore._lcl_sizes[0] #largest plane groupCount = len(self._dataStore._lcl_sizes) #count of groups #Reset plane sizes self._dataStore._lcl_sizes = [] for count in range(0,groupCount): self._dataStore._lcl_sizes.append(maxPlaneSize) self._dataStore._lcl_groups = [] for grp in gpz: self._dataStore._lcl_groups.append({ "group":grp, "size":maxPlaneSize }) #Abstract method to calc cost def calulateCosts(self): for g in self._dataStore._lcl_groups: #Get the cost by resource group locale.setlocale( locale.LC_ALL, 'en_CA.UTF-8' ) try: self._cost = str(locale.currency(self._dataStore._group_cost[g["group"]])) except: self._cost = "" # blank not 0, blank means dont show it at all #Abstact to load resources def loadResources(self): self.view_path = Sdf.Path(self.root_path.AppendPath(self._view_path)) grpCnt = len(self._dataStore._lcl_groups) if (grpCnt) >0 : #Cycle all the loaded groups for grp in self._dataStore._lcl_groups: carb.log_info(grp["group"]) #Cleanup the group name for a prim path group_prim_path = self.view_path.AppendPath(grp["group"]) #match the group to the resource map for key, values in self._dataStore._map_group.items(): #Is this the group? if key == grp["group"]: asyncio.ensure_future(self.loadGroupResources(key, group_prim_path, values)) def selectGroupPrims(self): self.paths = [] base = Sdf.Path(self.root_path.AppendPath(self._view_path)) for grp in self._dataStore._map_group.keys(): grp_path = base.AppendPath(cleanup_prim_path(self, grp)) self.paths.append(str(grp_path)) omni.kit.commands.execute('SelectPrimsCommand', old_selected_paths=[], new_selected_paths=self.paths, expand_in_stage=True)
3,976
Python
31.867768
109
0.57998
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/constant.py
from enum import Enum, IntEnum import carb.settings FONT_OFFSET_Y = carb.settings.get_settings().get("/app/font/offset_y") or 0 class FontSize: Normal = 14 # Default (In VIEW, 18 pixels in real, configed by /app/font/size) Large = 16 # real size = round(18*16/14) = 21 XLarge = 18 # real size = round(18*18/14) = 23 XXLarge = 20 # real size = round(18*20/14) = 26 XXXLarge = 22 # real size = round(18*22/14) = 28 Small = 12 # real size = round(18*12/14) = 15 XSmall = 10 # real size = round(18*10/14) = 13 XXSmall = 8 # real size = round(18*8/14) = 10 XXXSmall = 6 # real size = round(18*6/14) = 8 class MouseKey(IntEnum): NONE = -1 LEFT = 0 RIGHT = 1 MIDDLE = 2 class COLORS: CLR_0 = 0xFF080808 CLR_1 = 0xFF181818 CLR_2 = 0xFF282828 CLR_3 = 0xFF383838 CLR_4 = 0xFF484848 CLR_5 = 0xFF585858 CLR_6 = 0xFF686868 CLR_7 = 0xFF787878 CLR_8 = 0xFF888888 CLR_9 = 0xFF989898 CLR_A = 0xFFA8A8A8 CLR_B = 0xFFB8B8B8 CLR_C = 0xFFCCCCCC CLR_D = 0xFFE0E0E0 CLR_E = 0xFFF4F4F4 LIGHRT_GARY = 0xFF808080 GRAY = 0xFF606060 DARK_GRAY = 0xFF404040 DARK_DARK = 0xFF202020 TRANSPARENT = 0x0000000 # Color for buttons selected/activated state in NvidiaLight. L_SELECTED = 0xFFCFCCBF # Color for buttons selected/activated state in NvidiaDark. D_SELECTED = 0xFF4F383F BLACK = 0xFF000000 WHITE = 0xFFFFFFFF TEXT_LIGHT = CLR_D TEXT_DISABLED_LIGHT = 0xFFA0A0A0 TEXT_DARK = CLR_C TEXT_DISABLED_DARK = 0xFF8B8A8A TEXT_SELECTED = 0xFFC5911A WIDGET_BACKGROUND_LIGHT = 0xFF535354 WIDGET_BACKGROUND_DARK = 0xFF23211F BUTTON_BACKGROUND_LIGHT = 0xFFD6D6D6 LINE_SEPARATOR = 0xFFACACAC LINE_SEPARATOR_THICK = 0xFF666666 class LightColors: Background = COLORS.WIDGET_BACKGROUND_LIGHT BackgroundSelected = COLORS.CLR_4 BackgroundHovered = COLORS.CLR_4 Text = COLORS.CLR_D TextDisabled = COLORS.TEXT_DISABLED_LIGHT TextSelected = COLORS.TEXT_SELECTED Button = COLORS.BUTTON_BACKGROUND_LIGHT ButtonHovered = COLORS.CLR_B ButtonPressed = COLORS.CLR_A ButtonSelected = 0xFFCFCCBF WindowBackground = COLORS.CLR_D class DarkColors: Background = COLORS.WIDGET_BACKGROUND_DARK BackgroundSelected = 0xFF6E6E6E BackgroundHovered = 0xFF6E6E6E Text = COLORS.CLR_C TextDisabled = COLORS.TEXT_DISABLED_DARK TextSelected = COLORS.TEXT_SELECTED Button = COLORS.WIDGET_BACKGROUND_DARK ButtonHovered = 0xFF9E9E9E ButtonPressed = 0xFF787569 ButtonSelected = 0xFF4F383F WindowBackground = 0xFF454545
2,654
Python
25.55
83
0.674077
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/azure_map_primitives.py
shape_usda_name = { "AAD": "omniverse://localhost/MCE/cube.usda", "Resource Group": "omniverse://localhost/MCE/cube.usda", "Storage account": "omniverse://localhost/MCE/cube.usda", "App Service": "omniverse://localhost/MCE/cube.usda", "Subscription": "omniverse://localhost/MCE/cube.usda", "API Connection" : "omniverse://localhost/MCE/cube.usda", "API Management service" : "omniverse://localhost/MCE/cube.usda", "App Configuration" : "omniverse://localhost/MCE/cube.usda", "App Service plan" : "omniverse://localhost/MCE/cube.usda", "App Service" : "omniverse://localhost/MCE/cube.usda", "Application Insights" : "omniverse://localhost/MCE/cube.usda", "Application gateway" : "omniverse://localhost/MCE/cube.usda", "Automation Account" : "omniverse://localhost/MCE/cube.usda", "Availability test": "omniverse://localhost/MCE/cube.usda", "Azure Cosmos DB API for MongoDB account" : "omniverse://localhost/MCE/cube.usda", "Azure Cosmos DB account" : "omniverse://localhost/MCE/cube.usda", "Azure Data Explorer Cluster" : "omniverse://localhost/MCE/cube.usda", "Azure DevOps organization" : "omniverse://localhost/MCE/cube.usda", "Azure Machine Learning" : "omniverse://localhost/MCE/cube.usda", "Azure Workbook" : "omniverse://localhost/MCE/cube.usda", "Bastion" : "omniverse://localhost/MCE/cube.usda", "Cognitive Service" : "omniverse://localhost/MCE/cube.usda", "Container registry" : "omniverse://localhost/MCE/cube.usda", "Data Lake Analytics" : "omniverse://localhost/MCE/cube.usda", "Data Lake Storage Gen1" : "omniverse://localhost/MCE/cube.usda", "Data factory (V2)" : "omniverse://localhost/MCE/cube.usda", "Disk" : "omniverse://localhost/MCE/cube.usda", "Event Grid System Topic" : "omniverse://localhost/MCE/cube.usda", "Event Hubs Namespace" : "omniverse://localhost/MCE/cube.usda", "Firewall Policy" : "omniverse://localhost/MCE/cube.usda", "Firewall" : "omniverse://localhost/MCE/cube.usda", "Function App" : "omniverse://localhost/MCE/cube.usda", "Image" : "omniverse://localhost/MCE/cube.usda", "Key vault" : "omniverse://localhost/MCE/cube.usda", "Kubernetes service" : "omniverse://localhost/MCE/cube.usda", "Language understanding" : "omniverse://localhost/MCE/cube.usda", "Load balancer" : "omniverse://localhost/MCE/cube.usda", "Log Analytics query pack" : "omniverse://localhost/MCE/cube.usda", "Log Analytics workspace" : "omniverse://localhost/MCE/cube.usda", "Logic App (Standard)" : "omniverse://localhost/MCE/cube.usda", "Logic app" : "omniverse://localhost/MCE/cube.usda", "Logic apps custom connector" : "omniverse://localhost/MCE/cube.usda", "Managed Identity" : "omniverse://localhost/MCE/cube.usda", "Network Interface" : "omniverse://localhost/MCE/cube.usda", "Network Watcher" : "omniverse://localhost/MCE/cube.usda", "Network security group" : "omniverse://localhost/MCE/cube.usda", "Power BI Embedded" : "omniverse://localhost/MCE/cube.usda", "Private DNS zone" : "omniverse://localhost/MCE/cube.usda", "Private endpoint" : "omniverse://localhost/MCE/cube.usda", "Public IP address" : "omniverse://localhost/MCE/cube.usda", "Recovery Services vault" : "omniverse://localhost/MCE/cube.usda", "Restore Point Collection" : "omniverse://localhost/MCE/cube.usda", "Runbook" : "omniverse://localhost/MCE/cube.usda", "SQL database" : "omniverse://localhost/MCE/cube.usda", "SQL elastic pool" : "omniverse://localhost/MCE/cube.usda", "SQL server" : "omniverse://localhost/MCE/cube.usda", "SQL virtual machine" : "omniverse://localhost/MCE/cube.usda", "Search service" : "omniverse://localhost/MCE/cube.usda", "Service Bus Namespace" : "omniverse://localhost/MCE/cube.usda", "Service Fabric cluster" : "omniverse://localhost/MCE/cube.usda", "Shared dashboard" : "omniverse://localhost/MCE/cube.usda", "Snapshot" : "omniverse://localhost/MCE/cube.usda", "Solution" : "omniverse://localhost/MCE/cube.usda", "Storage account" : "omniverse://localhost/MCE/cube.usda", "Traffic Manager profile" : "omniverse://localhost/MCE/cube.usda", "Virtual machine scale set" : "omniverse://localhost/MCE/cube.usda", "Virtual machine" : "omniverse://localhost/MCE/cube.usda", "Virtual network" : "omniverse://localhost/MCE/cube.usda", "Web App Bot" : "omniverse://localhost/MCE/cube.usda", }
4,482
Python
58.773333
86
0.682954
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/widget_info_model.py
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # __all__ = ["WidgetInfoModel"] from omni.ui import scene as sc from pxr import Gf from pxr import UsdGeom from pxr import Usd from pxr import UsdShade from pxr import Tf from pxr import UsdLux import omni.usd import omni.kit.commands from .prim_utils import only_select_parent_prims class WidgetInfoModel(sc.AbstractManipulatorModel): """ User part. The model tracks the position and info of the selected object. """ class PositionItem(sc.AbstractManipulatorItem): """ The Model Item represents the position. It doesn't contain anything because because we take the position directly from USD when requesting. """ def __init__(self): super().__init__() self.value = [0, 0, 0] class ValueItem(sc.AbstractManipulatorItem): """The Model Item contains a single float value about some attibute""" def __init__(self, value=0): super().__init__() self.value = [value] def __init__(self): super().__init__() self.material_name = "" self.position = WidgetInfoModel.PositionItem() # The distance from the bounding box to the position the model returns self._offset = 0 # Current selection self._prim = None self._current_path = "" self._stage_listener = None # Save the UsdContext name (we currently only work with single Context) self._usd_context_name = '' usd_context = self._get_context() # Track selection self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop( self._on_stage_event, name="Object Info Selection Update" ) def _get_context(self) -> Usd.Stage: # Get the UsdContext we are attached to return omni.usd.get_context(self._usd_context_name) def _notice_changed(self, notice, stage): """Called by Tf.Notice""" for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self._item_changed(self.position) def get_item(self, identifier): if identifier == "position": return self.position if identifier == "name": return self._current_path if identifier == "material": return self.material_name def get_custom(self, field): stage = self._get_context().get_stage() prim = stage.GetPrimAtPath(self._current_path) return prim.GetCustomDataByKey(field) def get_as_floats(self, item): if item == self.position: # Requesting position return self._get_position() if item: # Get the value directly from the item return item.value return [] def set_floats(self, item, value): if not self._current_path: return if not value or not item or item.value == value: return # Set directly to the item item.value = value # This makes the manipulator updated self._item_changed(item) def _on_stage_event(self, event): """Called by stage_event_stream""" if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._on_kit_selection_changed() def _on_kit_selection_changed(self): # selection change, reset it for now self._current_path = "" usd_context = self._get_context() stage = usd_context.get_stage() if not stage: return prim_paths = usd_context.get_selection().get_selected_prim_paths() #Selectively choose the paths prim_paths = only_select_parent_prims(prim_paths=prim_paths) if not prim_paths: self._item_changed(self.position) # Revoke the Tf.Notice listener, we don't need to update anything if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None return if len(prim_paths) > 1: return #Dont Show widget on multiselect prim = stage.GetPrimAtPath(prim_paths[0]) if prim.IsA(UsdLux.Light): print("Light") self.material_name = "I am a Light" elif prim.IsA(UsdGeom.Imageable): material, relationship = UsdShade.MaterialBindingAPI(prim).ComputeBoundMaterial() if material: self.material_name = str(material.GetPath()) else: self.material_name = "N/A" else: self._prim = None return self._prim = prim self._current_path = prim_paths[0] # Add a Tf.Notice listener to update the position if not self._stage_listener: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) (old_scale, old_rotation_euler, old_rotation_order, old_translation) = omni.usd.get_local_transform_SRT(prim) # Position is changed self._item_changed(self.position) def _get_position(self): """Returns position of currently selected object""" stage = self._get_context().get_stage() if not stage or not self._current_path: return [0, 0, 0] # Get position directly from USD prim = stage.GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range = bound.ComputeAlignedBox() bboxMin = range.GetMin() bboxMax = range.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position
6,273
Python
32.913513
117
0.616451
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/views.py
# import from omniverse from ctypes import alignment from omni.ui.workspace_utils import TOP # import from other extension py from .combo_box_model import ComboBoxModel from .style_button import button_styles from .style_meta import meta_window_style, get_gradient_color, build_gradient_image from .style_meta import cl_combobox_background, cls_temperature_gradient, cls_color_gradient, cls_tint_gradient, cls_grey_gradient, cls_button_gradient from .data_manager import DataManager from .data_store import DataStore from .button import SimpleImageButton import sys import asyncio import webbrowser #from turtle import width import omni.ext import omni.ui as ui from omni.ui import color as cl import os import carb import omni.kit.commands import omni.kit.pipapi from pxr import Sdf, Usd, Gf, UsdGeom import omni from pathlib import Path import omni.kit.notification_manager as nm from .omni_utils import get_selection from .combo_box_model import ComboBoxModel from .omni_utils import duplicate_prims from .stage_manager import StageManager from .import_fbx import convert_asset_to_usd from .prim_utils import create_plane import random LABEL_WIDTH = 120 WINDOW_NAME = "Meta Cloud Explorer" SPACING = 4 CURRENT_PATH = Path(__file__).parent DATA_PATH = CURRENT_PATH.parent.parent.parent.parent.joinpath("data\\resources") class MainView(ui.Window): """The class that represents the window""" def __init__(self, title: str = None, menu_path:str = "", delegate=None, **kwargs): super().__init__(title, width=640, height=480, **kwargs) self.__label_width = LABEL_WIDTH self._viewport_scene = None self.objModel = kwargs["objectModel"] self.widModel = kwargs["widgetModel"] self._menu_path = menu_path #Helper Class instances self._stageManager = StageManager() self._dataManager = DataManager.instance() self._dataStore = DataStore.instance() #Get notified when visibility changes self.set_visibility_changed_fn(self._on_visibility_changed) #Get notifed when the datamodel changes self._dataManager.add_model_changed_callback(self.model_changed) # Apply the style to all the widgets of this window self.frame.style = meta_window_style # Set the function that is called to build widgets when the window is visible self.frame.set_build_fn(self._build_fn) def __del__(self): self.destroy() def destroy(self): super().destroy() if self._dataManager: self._dataManager.destroy() if self._dataStore: self._dataStore = None if self._stageManager: self._stageManager = None self.objModel= None self.widModel= None if self._viewport_scene: # Empty the SceneView of any elements it may have self._viewport_scene = None # Be a good citizen, and un-register the SceneView from Viewport updates if self._viewport_window: self._viewport_window.viewport_api.remove_scene_view(self._scene_view) # Remove our references to these objects self._viewport_window = None self._scene_view = None self._menu_path = None def on_shutdown(self): self._win = None def show(self): self.visible = True self.focus() def hide(self): self.visible = False def _on_visibility_changed(self, visible): omni.kit.ui.get_editor_menu().set_value(self._menu_path, visible) @property def label_width(self): """The width of the attribute label""" return self.__label_width @label_width.setter def label_width(self, value): """The width of the attribute label""" self.__label_width = value self.frame.rebuild() #___________________________________________________________________________________________________ # Function Definitions #___________________________________________________________________________________________________ def on_docs(self): webbrowser.open_new("https://github.com/USDSync/MetaCloudExplorer/wiki") def on_code(self): webbrowser.open_new("http://metacloudexplorer.com") def on_help(self): webbrowser.open_new("https://github.com/USDSync/MetaCloudExplorer/issues") #Callback invoked when data model changes def model_changed(self): carb.log_info("Model changed!") if (hasattr(self, "_grpLbl")): self._grpLbl.text = "GROUPS: " + str(len(self._dataStore._groups)) if (hasattr(self, "_resLbl")): self._resLbl.text = "RESOURCES: " + str(len(self._dataStore._resources)) #Set defaults from quickstarts def set_defaults(self, defType:str): if defType == "tower": self.sendNotify("MCE: Tower defaults set... Select a VIEW", nm.NotificationStatus.INFO) self._dataStore._symmetric_planes_model.set_value(True) self._dataStore._packing_algo_model.set_value(False) self._dataStore._options_count_models[0].set_value(2) self._dataStore._options_count_models[1].set_value(2) self._dataStore._options_count_models[2].set_value(60) self._dataStore._options_dist_models[0].set_value(500.0) self._dataStore._options_dist_models[1].set_value(500.0) self._dataStore._options_dist_models[2].set_value(250.0) self._dataStore._options_random_models[0].set_value(1) self._dataStore._options_random_models[1].set_value(1) self._dataStore._options_random_models[2].set_value(1) if defType == "symmetric": self.sendNotify("MCE: Symmetric defaults set... Select a VIEW", nm.NotificationStatus.INFO) self._dataStore._symmetric_planes_model.set_value(True) self._dataStore._packing_algo_model.set_value(False) self._dataStore._options_count_models[0].set_value(10) self._dataStore._options_count_models[1].set_value(10) self._dataStore._options_count_models[2].set_value(40) self._dataStore._options_dist_models[0].set_value(500.0) self._dataStore._options_dist_models[1].set_value(500.0) self._dataStore._options_dist_models[2].set_value(250.0) self._dataStore._options_random_models[0].set_value(1) self._dataStore._options_random_models[1].set_value(1) self._dataStore._options_random_models[2].set_value(1) if defType == "islands": self.sendNotify("MCE: Island defaults set... Select a VIEW", nm.NotificationStatus.INFO) self._dataStore._symmetric_planes_model.set_value(False) self._dataStore._packing_algo_model.set_value(False) self._dataStore._options_count_models[0].set_value(20) self._dataStore._options_count_models[1].set_value(4) self._dataStore._options_count_models[2].set_value(4) self._dataStore._options_dist_models[0].set_value(500.0) self._dataStore._options_dist_models[1].set_value(500.0) self._dataStore._options_dist_models[2].set_value(250.0) self._dataStore._options_random_models[0].set_value(1) self._dataStore._options_random_models[1].set_value(1) self._dataStore._options_random_models[2].set_value(1) if defType == "packer": self.sendNotify("MCE: Packer algo enabled... Select a VIEW", nm.NotificationStatus.INFO) self._dataStore._symmetric_planes_model.set_value(False) self._dataStore._packing_algo_model.set_value(True) self._dataStore._options_count_models[0].set_value(4) self._dataStore._options_count_models[1].set_value(4) self._dataStore._options_count_models[2].set_value(20) self._dataStore._options_dist_models[0].set_value(500.0) self._dataStore._options_dist_models[1].set_value(500.0) self._dataStore._options_dist_models[2].set_value(250.0) self._dataStore._options_random_models[0].set_value(1) self._dataStore._options_random_models[1].set_value(1) self._dataStore._options_random_models[2].set_value(1) def show_info_objects(self): self.model.populate() #Load a fresh stage def load_stage(self, viewType: str): self._dataStore._last_view_type = viewType self._dataStore.Save_Config_Data() #Block and clear stage asyncio.ensure_future(self.clear_stage()) self._stageManager.ShowStage(viewType) #load the resource onto the stage def load_resources(self): self._stageManager.LoadResources(self._dataStore._last_view_type) #change the background shaders to reflect costs def showHideCosts(self): self._stageManager.ShowCosts() # Clear the stage async def clear_stage(self): try: stage = omni.usd.get_context().get_stage() root_prim = stage.GetPrimAtPath("/World") if (root_prim.IsValid()): stage.RemovePrim("/World") ground_prim = stage.GetPrimAtPath('/GroundPlane') if (ground_prim.IsValid()): stage.RemovePrim('/GroundPlane') ground_prim = stage.GetPrimAtPath('/RGrp') if (ground_prim.IsValid()): stage.RemovePrim('/RGrp') ground_prim = stage.GetPrimAtPath('/Loc') if (ground_prim.IsValid()): stage.RemovePrim('/Loc') ground_prim = stage.GetPrimAtPath('/AAD') if (ground_prim.IsValid()): stage.RemovePrim('/AAD') ground_prim = stage.GetPrimAtPath('/Subs') if (ground_prim.IsValid()): stage.RemovePrim('/Subs') ground_prim = stage.GetPrimAtPath('/Type') if (ground_prim.IsValid()): stage.RemovePrim('/Type') ground_prim = stage.GetPrimAtPath('/Cost') if (ground_prim.IsValid()): stage.RemovePrim('/Cost') ground_prim = stage.GetPrimAtPath('/Looks') if (ground_prim.IsValid()): stage.RemovePrim('/Looks') ground_prim = stage.GetPrimAtPath('/Tag') if (ground_prim.IsValid()): stage.RemovePrim('/Tag') if stage.GetPrimAtPath('/Environment/sky'): omni.kit.commands.execute('DeletePrimsCommand',paths=['/Environment/sky']) except: pass #ignore failure #___________________________________________________________________________________________________ # Window UI Definitions #___________________________________________________________________________________________________ def _build_fn(self): """The method that is called to build all the UI once the window is visible.""" with ui.ScrollingFrame(): with ui.VStack(height=0): self._build_new_header() self._build_image_presets() self._build_options() self._build_connection() self._build_import() self._build_help() #self.buildSliderTest() # slider = ui.FloatSlider(min=1.0, max=150.0) # slider.model.as_float = 10.0 # label = ui.Label("Omniverse", style={"color": ui.color(0), "font_size": 7.0}) #Pieces of UI Elements def _build_new_header(self): """Build the widgets of the "Source" group""" #with ui.ZStack(): #Background #ui.Image(style={'image_url': "omniverse://localhost/Resources/images/meta_cloud_explorer_800.png", 'fill_policy': ui.FillPolicy.PRESERVE_ASPECT_CROP, 'alignment': ui.Alignment.CENTER_BOTTOM, 'fill_policy':ui.FillPolicy.PRESERVE_ASPECT_CROP}) #Foreground with ui.VStack(): with ui.HStack(): with ui.VStack(): with ui.HStack(): with ui.VStack(): ui.Label("Meta Cloud Explorer", style={"color": cl("#A4B7FD"), "font_size":20}, alignment=ui.Alignment.LEFT, height=0) ui.Label("Cloud Infrastructure Scene Authoring Extension", style={"color": cl("#878683"), "font_size":16}, alignment=ui.Alignment.LEFT, height=0) with ui.VStack(): ui.Spacer(height=15) self._grpLbl = ui.Label("GROUPS: " + str(len(self._dataStore._groups)),style={"color": cl("#2069e0"), "font_size":18 }, alignment=ui.Alignment.RIGHT, height=0) self._resLbl = ui.Label("RESOURCES: " + str(len(self._dataStore._resources)), style={"color": cl("#2069e0"), "font_size":18}, alignment=ui.Alignment.RIGHT, height=0) ui.Line(style={"color": cl("#66b3ff")}, height=20) with ui.VStack(height=0, spacing=SPACING): #ui.Spacer(height=80) with ui.HStack(): ui.Button("< GROUPS >", clicked_fn=lambda: self.load_stage("ByGroup"), name="subs", height=35, style={"color": cl("#bebebe"), "font_size":20 }) ui.Button("< TYPES >", clicked_fn=lambda: self.load_stage("ByType"), name="subs",height=35, style={"color": cl("#bebebe"), "font_size":20 }) with ui.VStack(height=0, spacing=SPACING): #ui.Spacer(height=120) with ui.HStack(): ui.Button("< LOCATIONS >", clicked_fn=lambda: self.load_stage("ByLocation"), name="subs", height=35, style={"color": cl("#bebebe"), "font_size":20 }) ui.Button("< SUBSCRIPTIONS >", clicked_fn=lambda: self.load_stage("BySub"), name="subs", height=35, style={"color": cl("#bebebe"), "font_size":20 }) with ui.VStack(height=0, spacing=SPACING): #ui.Spacer(height=120) with ui.HStack(): ui.Button("Clear Stage", clicked_fn=lambda: asyncio.ensure_future(self.clear_stage()), name="clr", height=35) ui.Button("Show/Hide Costs", clicked_fn=lambda: self.showHideCosts(),name="subs", height=35) #ui.Button("Show Object Info", clicked_fn=lambda: self.show_info_objects(),name="clr", height=35) ui.Button("Select All Groups", clicked_fn=lambda: self.select_planes(),name="clr", height=35) # with ui.HStack(): # ui.Button("Network View", clicked_fn=lambda: self.load_stage("ByNetwork"), height=15) # ui.Button("Cost View", clicked_fn=lambda: self.load_stage("ByCost"), height=15) # ui.Button("Template View", clicked_fn=lambda: self.load_stage("Template"), height=15) def _build_import(self): with ui.CollapsableFrame("Import Offline Files", name="group", collapsed=True, style={"color": cl("#2069e0"), "font_size":20}): with ui.VStack(style={"color": 0xFFFFFFFF, "font_size":16}): ui.Label("Resource Groups file path:", height=10, width=120) with ui.HStack(): self._rg_data_import_field = ui.StringField(height=15) self._rg_data_import_field.enabled = True self._rg_data_import_field.model.set_value(str(self._dataStore._rg_csv_file_path)) self._dataStore._rg_csv_field_model = self._rg_data_import_field.model ui.Button("Load", width=40, clicked_fn=lambda: self._dataManager.select_file("rg")) ui.Label("All Resources file path:", height=10, width=120) with ui.HStack(): self._rs_data_import_field = ui.StringField(height=15) self._rs_data_import_field.enabled = True self._rs_data_import_field.model.set_value(str(self._dataStore._rs_csv_file_path)) self._dataStore._rs_csv_field_model = self._rs_data_import_field.model ui.Button("Load", width=40, clicked_fn=lambda: self._dataManager.select_file("res")) with ui.HStack(): ui.Button("Clear imported Data", clicked_fn=lambda: self._dataManager.wipe_data()) ui.Button("Import Selected Files", clicked_fn=lambda: self._dataManager.load_csv_files()) with ui.HStack(): ui.Button("Load Small Company", clicked_fn=lambda: self._dataManager.load_small_company()) ui.Button("Load Large Company", clicked_fn=lambda: self._dataManager.load_large_company()) ui.Button("Load Shapes Library", clicked_fn=lambda: self._dataManager.load_sample_resources()) def _build_connection(self): def _on_value_changed(field:str, value): if field == "tenant": self._dataStore._azure_tenant_id = value if field == "client": self._dataStore._azure_client_id = value if field == "subid": self._dataStore._azure_subscription_id = value if field == "secret": self._dataStore._azure_client_secret = value # def setText(label, text): # '''Sets text on the label''' # # This function exists because lambda cannot contain assignment # label.text = f"You wrote '{text}'" with ui.CollapsableFrame("Cloud API Connection", name="group", collapsed=True, style={"color": cl("#2069e0"), "font_size":20}): with ui.VStack(style={"color": 0xFFFFFFFF, "font_size":16}): # with ui.CollapsableFrame("Azure API Connection", name="group", collapsed=True): # with ui.VStack(): ui.Label("Tenant Id",width=self.label_width) self._tenant_import_field = ui.StringField(height=15) self._tenant_import_field.enabled = True self._tenant_import_field.model.set_value(str(self._dataStore._azure_tenant_id)) self._tenant_import_field.model.add_value_changed_fn(lambda m: _on_value_changed("tenant", m.get_value_as_string())) ui.Label("Client Id",width=self.label_width) self._client_import_field = ui.StringField(height=15) self._client_import_field.enabled = True self._client_import_field.model.set_value(str(self._dataStore._azure_client_id)) self._client_import_field.model.add_value_changed_fn(lambda m: _on_value_changed("client", m.get_value_as_string())) ui.Label("Subscription Id",width=self.label_width) self._subscription_id_field = ui.StringField(height=15) self._subscription_id_field.enabled = True self._subscription_id_field.model.set_value(str(self._dataStore._azure_subscription_id)) self._subscription_id_field.model.add_value_changed_fn(lambda m: _on_value_changed("subid", m.get_value_as_string())) ui.Label("Client Secret",width=self.label_width) self._client_secret_field = ui.StringField(height=15, password_mode=True) self._client_secret_field.enabled = True self._client_secret_field.model.set_value(str(self._dataStore._azure_client_secret)) self._client_secret_field.model.add_value_changed_fn(lambda m: _on_value_changed("secret", m.get_value_as_string())) ui.Button("Connect to Azure", clicked_fn=lambda: self._dataManager.load_from_api()) def _build_axis(self, axis_id, axis_name): """Build the widgets of the "X" or "Y" or "Z" group""" with ui.CollapsableFrame(axis_name, name="group", collapsed=True): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("Group Count", name="attribute_name", width=self.label_width) ui.IntDrag(model=self._dataStore._options_count_models[axis_id], min=1, max=500) with ui.HStack(): ui.Label("Distance", name="attribute_name", width=self.label_width) ui.FloatDrag(self._dataStore._options_dist_models[axis_id], min=250, max=5000) with ui.HStack(): ui.Label("Randomness", name="attribute_name", width=self.label_width) ui.FloatDrag(self._dataStore._options_random_models[axis_id], min=1.0, max=10.0) def _build_image_presets(self): def _on_clicked(self, source): self.set_defaults(source) #add selection rectangle with ui.CollapsableFrame("Quickstarts", name="group", collapsed=True, style={"color":cl("#2069e0"), "font_size":20}): with ui.VStack(style={"color": 0xFFFFFFFF}): with ui.HStack(style={}): with ui.VStack(): ui.Label("TOWER", name="attribute_name", width=self.label_width) SimpleImageButton(image="omniverse://localhost/MCE/images/tower.png", size=125, name="twr_btn", clicked_fn=lambda: _on_clicked(self, source="tower")) with ui.VStack(): ui.Label("ISLANDS", name="attribute_name", width=self.label_width) SimpleImageButton(image="omniverse://localhost/MCE/images/islands.png", size=125, name="isl_btn", clicked_fn=lambda: _on_clicked(self, source="islands")) with ui.VStack(): ui.Label("SYMMETRIC", name="attribute_name", width=self.label_width) SimpleImageButton(image="omniverse://localhost/MCE/images/Symmetric.png", size=125, name="sym_btn", clicked_fn=lambda: _on_clicked(self, source="symmetric")) with ui.VStack(): ui.Label("BIN PACKER", name="attribute_name", width=self.label_width) SimpleImageButton(image="omniverse://localhost/MCE/images/packer.png", size=125, name="row_btn",clicked_fn=lambda: _on_clicked(self, source="packer")) def _build_image_options(self): with ui.CollapsableFrame("Group Images", name="group", collapsed=True): with ui.VStack(height=0, spacing=SPACING): with ui.HStack(): ui.Label("BG Low Cost", name="attribute_name", width=self.label_width) self._bgl_data_import_field = ui.StringField(height=15) self._bgl_data_import_field.enabled = True self._bgl_data_import_field.model.set_value(str(self._dataStore._bgl_file_path)) self._dataStore._bgl_field_model = self._bgl_data_import_field.model ui.Button("Load", width=40, clicked_fn=lambda: self._dataManager.select_file("bgl")) with ui.HStack(): ui.Label("Bg Mid Cost", name="attribute_name", width=self.label_width) self._bgm_data_import_field = ui.StringField(height=15) self._bgm_data_import_field.enabled = True self._bgm_data_import_field.model.set_value(str(self._dataStore._bgm_file_path)) self._dataStore._bgm_field_model = self._bgm_data_import_field.model ui.Button("Load", width=40, clicked_fn=lambda: self._dataManager.select_file("bgm")) with ui.HStack(): ui.Label("Bg High Cost", name="attribute_name", width=self.label_width) self._bgh_data_import_field = ui.StringField(height=15) self._bgh_data_import_field.enabled = True self._bgh_data_import_field.model.set_value(str(self._dataStore._bgh_file_path)) self._dataStore._bgh_field_model = self._bgh_data_import_field.model ui.Button("Load", width=40, clicked_fn=lambda: self._dataManager.select_file("bgh")) def _build_options(self, default_value=0, min=0, max=1): def _on_value_changed_bp(model): self._dataStore._use_packing_algo = model.as_bool def _on_value_changed_sg(model): self._dataStore._use_symmetric_planes = model.as_bool def _on_value_changed_wd(model): self._dataStore._show_info_widgets = model.as_bool with ui.CollapsableFrame("Scene Composition Options", name="group", collapsed=True, style={"color": cl("#2069e0"), "font_size":20}): with ui.VStack(height=0, spacing=SPACING, style={"color": 0xFFFFFFFF, "font_size":16}): with ui.HStack(): #self._dataStore._composition_scale_model = self._build_gradient_float_slider("Scale Factor", default_value=10, min=1, max=100) ui.Label("Object Scale", name="attribute_name", width=self.label_width, min=1, max=100) ui.FloatDrag(self._dataStore._composition_scale_model, min=1, max=100) self._dataStore._composition_scale_model.set_value(self._dataStore._scale_model) with ui.HStack(): ui.Label("Use Symmetric groups?", name="attribute_name", width=self.label_width) cb1 = ui.CheckBox(self._dataStore._symmetric_planes_model) cb1.model.add_value_changed_fn(lambda model: _on_value_changed_sg(model)) with ui.HStack(): ui.Label("Use Bin Packing?", name="attribute_name", width=self.label_width) cb2 = ui.CheckBox(self._dataStore._packing_algo_model) cb2.model.add_value_changed_fn(lambda model: _on_value_changed_bp(model)) with ui.HStack(): ui.Label("Show Info UI on select?", name="attribute_name", width=self.label_width) cb3 = ui.CheckBox(self._dataStore._show_info_widgets_model) cb3.model.add_value_changed_fn(lambda model: _on_value_changed_wd(model)) self._build_image_options() self._build_axis(0, "Groups on X Axis") self._build_axis(1, "Groups on Y Axis") self._build_axis(2, "Groups on Z Axis") def _build_help(self): with ui.CollapsableFrame("About", name="group", collapsed=True, style={"color": cl("#2069e0"), "font_size":20}): with ui.VStack(height=0, spacing=SPACING, style={"color": 0xFFFFFFFF, "font_size":16}): with ui.HStack(): with ui.VStack(): with ui.HStack(): ui.Label("Meta Cloud Explorer (MCE)", clicked_fn=lambda: self.on_docs(), height=15) ui.Label("v1.0.0", clicked_fn=lambda: self.on_docs(), height=15) with ui.HStack(): with ui.VStack(): with ui.HStack(): ui.Label("The true power of the Metaverse is to gain new insights to existing problems by experiencing things in a different way, a simple change in perspective!", style={"color":0xFF000000}, elided_text=True, ) with ui.HStack(): with ui.VStack(): with ui.HStack(): ui.Line(style={"color": cl("#bebebe")}, height=20) ui.Button("Docs", clicked_fn=lambda: self.on_docs(), height=15) ui.Button("Code", clicked_fn=lambda: self.on_code(), height=15) ui.Button("Help", clicked_fn=lambda: self.on_help(), height=15) def __build_value_changed_widget(self): with ui.VStack(width=20): ui.Spacer(height=3) rect_changed = ui.Rectangle(name="attribute_changed", width=15, height=15, visible= False) ui.Spacer(height=4) with ui.HStack(): ui.Spacer(width=3) rect_default = ui.Rectangle(name="attribute_default", width=5, height=5, visible= True) return rect_changed, rect_default def _build_gradient_float_slider(self, label_name, default_value=0, min=0, max=1): def _on_value_changed(model, rect_changed, rect_defaul): if model.as_float == default_value: rect_changed.visible = False rect_defaul.visible = True else: rect_changed.visible = True rect_defaul.visible = False def _restore_default(slider): slider.model.set_value(default_value) with ui.HStack(): ui.Label(label_name, name=f"attribute_name", width=self.label_width) with ui.ZStack(): button_background_gradient = build_gradient_image(cls_button_gradient, 22, "button_background_gradient") with ui.VStack(): ui.Spacer(height=1.5) with ui.HStack(width=200): slider = ui.FloatSlider(name="float_slider", height=0, min=min, max=max) slider.model.set_value(default_value) ui.Spacer(width=1.5) ui.Spacer(width=4) rect_changed, rect_default = self.__build_value_changed_widget() # switch the visibility of the rect_changed and rect_default to indicate value changes slider.model.add_value_changed_fn(lambda model: _on_value_changed(model, rect_changed, rect_default)) # add call back to click the rect_changed to restore the default value rect_changed.set_mouse_pressed_fn(lambda x, y, b, m: _restore_default(slider)) return button_background_gradient def sendNotify(self, message:str, status:nm.NotificationStatus): # https://docs.omniverse.nvidia.com/py/kit/source/extensions/omni.kit.notification_manager/docs/index.html?highlight=omni%20kit%20notification_manager# import omni.kit.notification_manager as nm ok_button = nm.NotificationButtonInfo("OK", on_complete=self.clicked_ok) nm.post_notification( message, hide_after_timeout=True, duration=5, status=status, button_infos=[] ) def clicked_ok(self): pass def buildSliderTest(self): style = { "Button": {"stack_direction": ui.Direction.TOP_TO_BOTTOM}, "Button.Image": { "color": 0xFFFFCC99, "image_url": "resources/icons/Learn_128.png", "alignment": ui.Alignment.CENTER, }, "Button.Label": {"alignment": ui.Alignment.CENTER}, } def layout(model, button, padding, style=style): padding = "padding" if padding else "margin" style["Button"][padding] = model.get_value_as_float() button.set_style(style) def spacing(model, button): button.spacing = model.get_value_as_float() button = ui.Button("Label", style=style, width=64, height=64) with ui.HStack(width=ui.Percent(50)): ui.Label("padding", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 1)) with ui.HStack(width=ui.Percent(50)): ui.Label("margin", name="text") model = ui.FloatSlider(min=0, max=500).model model.add_value_changed_fn(lambda m, b=button: layout(m, b, 0)) with ui.HStack(width=ui.Percent(50)): ui.Label("Button.spacing", name="text") model = ui.FloatSlider(min=0, max=50).model model.add_value_changed_fn(lambda m, b=button: spacing(m, b))
32,845
Python
49.845201
254
0.565505
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/meta/cloud/explorer/azure/azure_resource_map_backup.py
shape_usda_name = { "AAD":"omniverse://localhost/MCE/3dIcons/AzureAAD_1.1.usd", "Resource_Group":"omniverse://localhost/MCE/3dIcons/Resource_Groups_2.0.usd", "Storage_account":"omniverse://localhost/MCE/3dIcons/StorageAccounts_2_8.usd", "App_Service":"omniverse://localhost/MCE/3dIcons/AppServices_1_2.usd", "Subscription":"omniverse://localhost/MCE/3dIcons/Subscriptions_1_3.usd", "API_Connection":"omniverse://localhost/MCE/3dIcons/API_Connection.usd", "API_Management_service":"omniverse://localhost/MCE/3dIcons/API-management-services.usd", "App_Configuration":"omniverse://localhost/MCE/3dIcons/App-Configuration.usd", "App_Service_plan":"omniverse://localhost/MCE/3dIcons/cube.usda", "App_Service":"omniverse://localhost/MCE/3dIcons/AppServices_1_2.usd", "Application_Insights":"omniverse://localhost/MCE/3dIcons/cube.usda", "Application_gateway":"omniverse://localhost/MCE/3dIcons/Application_Gateway.usd", "Automation_Account":"omniverse://localhost/MCE/3dIcons/automation-accounts.usd", "Availability_test":"omniverse://localhost/MCE/3dIcons/Availability_Test_1.3.usd", "Azure_Cosmos_DB_API_for_MongoDB_account":"omniverse://localhost/MCE/3dIcons/Azure_Cosmos_DB_API_MongoDB.usd", "Azure_Cosmos_DB_account":"omniverse://localhost/MCE/3dIcons/cube.usda", "Azure_Data_Explorer_Cluster":"omniverse://localhost/MCE/3dIcons/cube.usda", "Azure_DevOps_organization":"omniverse://localhost/MCE/3dIcons/azure-devops.usd", "Azure_Machine_Learning":"omniverse://localhost/MCE/3dIcons/Azure_Machine_Learning.usd", "Azure_Workbook":"omniverse://localhost/MCE/3dIcons/azure-workbook.usd", "Bastion":"omniverse://localhost/MCE/3dIcons/Bastion.usd", "Cognitive_Service":"omniverse://localhost/MCE/3dIcons/Cognitive_Services.usd", "Container_registry":"omniverse://localhost/MCE/3dIcons/container-registries.usd", "Data_Lake_Analytics":"omniverse://localhost/MCE/3dIcons/Data_Lake_Analytics_1.2.usd", "Data_Lake_Storage_Gen1":"omniverse://localhost/MCE/3dIcons/data-lake-storage-gen1.usd", "Data_factory__V2_":"omniverse://localhost/MCE/3dIcons/data-factory.usd", "Disk":"omniverse://localhost/MCE/3dIcons/Disk_1.0.usd", "DNS_Zone":"omniverse://localhost/MCE/3dIcons/cube.usda", "Event_Grid_System_Topic":"omniverse://localhost/MCE/3dIcons/event-grid-topics.usd", "Event_Hubs_Namespace":"omniverse://localhost/MCE/3dIcons/events-hub.usd", "Firewall_Policy":"omniverse://localhost/MCE/3dIcons/Firewall_Policy.usd", "Firewall":"omniverse://localhost/MCE/3dIcons/Firewall.usd", "Function_App":"omniverse://localhost/MCE/3dIcons/function-apps.usd", "Image":"omniverse://localhost/MCE/3dIcons/image.usd", "Key_vault":"omniverse://localhost/MCE/3dIcons/Key_Vaults.usd", "Kubernetes_service":"omniverse://localhost/MCE/3dIcons/kubernetess_services_cubes001_Z.usd", "Language_understanding":"omniverse://localhost/MCE/3dIcons/cube.usda", "Load_balancer":"omniverse://localhost/MCE/3dIcons/load-balancer.usd", "Log_Analytics_query_pack":"omniverse://localhost/MCE/3dIcons/cube.usda", "Log_Analytics_workspace":"omniverse://localhost/MCE/3dIcons/Log_Analytics_Workspace.usd", "Logic_App__Standard_":"omniverse://localhost/MCE/3dIcons/logic-apps.usd", "Logic_app":"omniverse://localhost/MCE/3dIcons/Logic_Apps_Std.usd", "Logic_apps_custom_connector":"omniverse://localhost/MCE/3dIcons/Logic_Apps_Custom_Connector.usd", "Managed_Identity":"omniverse://localhost/MCE/3dIcons/cube.usda", "Network_Interface":"omniverse://localhost/MCE/3dIcons/network-interface.usd", "Network_Watcher":"omniverse://localhost/MCE/3dIcons/cube.usda", "Network_security_group":"omniverse://localhost/MCE/3dIcons/network-security-groups.usd", "Power_BI_Embedded":"omniverse://localhost/MCE/3dIcons/Powe_BI_Embedded.usd", "Private_DNS_zone":"omniverse://localhost/MCE/3dIcons/cube.usda", "Private_endpoint":"omniverse://localhost/MCE/3dIcons/cube.usda", "Public_IP_address":"omniverse://localhost/MCE/3dIcons/public-ip-adresses.usd", "Recovery_Services_vault":"omniverse://localhost/MCE/3dIcons/cube.usda", "Restore_Point_Collection":"omniverse://localhost/MCE/3dIcons/Restore_Point_Collection.usd", "Runbook":"omniverse://localhost/MCE/3dIcons/Runbook.usd", "SQL_database":"omniverse://localhost/MCE/3dIcons/SQLServer_6_0.usd", "SQL_elastic_pool":"omniverse://localhost/MCE/3dIcons/SQL_Elastic_Pools.usd", "SQL_server":"omniverse://localhost/MCE/3dIcons/SQLServer.usd", "SQL_virtual_machine":"omniverse://localhost/MCE/3dIcons/sql-virtual-machine.usd", "Search_service":"omniverse://localhost/MCE/3dIcons/cube.usda", "Service_Bus_Namespace":"omniverse://localhost/MCE/3dIcons/service-bus.usd", "Service_Fabric_cluster":"omniverse://localhost/MCE/3dIcons/service-fabric-clusters.usd", "Shared_dashboard":"omniverse://localhost/MCE/3dIcons/cube.usda", "Snapshot":"omniverse://localhost/MCE/3dIcons/Snapshot.usd", "Solution":"omniverse://localhost/MCE/3dIcons/Solution_1.4.usd", "Storage_account":"omniverse://localhost/MCE/3dIcons/StorageAccounts_2.8.usd", "Traffic_Manager_profile":"omniverse://localhost/MCE/3dIcons/traffic-manager-profiles.usd", "Virtual_machine_scale_set":"omniverse://localhost/MCE/3dIcons/Virtual_Machines_Scale_Sets.usd", "Virtual_machine":"omniverse://localhost/MCE/3dIcons/Virtual_Machine.usd", "Virtual_network":"omniverse://localhost/MCE/3dIcons/Virtual_Network.usd", "Web_App_Bot":"omniverse://localhost/MCE/3dIcons/cube.usda", }
5,596
Python
73.626666
114
0.738206
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/config/extension.toml
[package] title = "Meta Cloud Explorer (Azure)" description="An Omniverse scene authoring tool to help visualize your Azure Infrastructure in your own private Metaverse!" version = "2022.1.3" category = "Browsers" authors = ["USDSync.com, MetaCloudExplorer.com - Gavin Stevens"] preview_image = "data/resources/azurescaled.png" icon = "data/resources/meta_cloud_explorer.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" changelog = "docs/CHANGELOG.md" # URL of the extension source repository. repository = "https://github.com/USDSync/MetaCloudExplorer" # Keywords for the extension keywords = ["Azure", "USD Sync", "Cloud Infrastructure", "Visualization", "Scene composition"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.ui" = {} "omni.usd" = {} "omni.kit.menu.utils" = {} "omni.kit.window.filepicker" = {} "omni.kit.window.file_importer" = {} [python.pipapi] requirements = [ "pandas", "numpy", "azure-mgmt-resource", "azure-identity", "typing-extensions" ] # Main python module this extension provides, it will be publicly available as "import meta.cloud.explorer.azure". [[python.module]] name = "meta.cloud.explorer.azure"
1,247
TOML
29.439024
122
0.718524
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/docs/CHANGELOG.md
# CHANGELOG ## [2022.3.0] - 2022-11-27 ### Added - update for 2022.3, Requires Omni.Phyx.Commands extension, python library workaround outlined on wiki. ## [2022.1.3-pre] - 2022-09-08 ### Added - updated readme, some issues with release tag pulling main instead. - merging 2022.1.3 with main ## [2022.1.3-pre] - 2022-09-08 ### Added - pre-release ## [2022.1.3.A] - 2022-09-06 ### Added - Initial checkin on this version - compatible with Omniverse Code 2022.1.2 & 2022.1.3 - requires Omni.Viewport.Utility!
513
Markdown
21.347825
103
0.692008
USDSync/MetaCloudExplorer/exts/meta.cloud.explorer.azure/docs/README.md
# USDSync.com # Meta Cloud Explorer (MCE) # NVIDIA Onmiverse Extension, a Scene Authoring Tool (In Beta Development phase) Quickly connect to your Cloud Infrastructure and visualize it in your private Omniverse!* This extension generates digital models of your Cloud Infrastructure that can be used to gain insights to drive better infrastructure, optimized resources, reduced costs, and breakthrough customer experiences. Make sure to install the Azure 3D Icon Library! https://github.com/USDSync/MetaCloudExplorer/wiki/Installing-3D-Icon-library-locally 2022.1.3 This version CANNOT CONNECT** to Azure's live Resource Management API! (live connection supported in MCE 2022.1.1) This version requires the Omni.Viewport.Utility extension be installed. This version works fine with sample data and offline data files. This version enables resource Object / Info widgets! This version will become the main branch once 2021.1.3+ supports the azure-identity library. *Compatible with Omniverse code 2022.1.2, 2022.1.3+ **This version was created to enable Object / Info widgets, but using 2022.1.2 and 2022.1.3 causes azure-identity to fail due to: https://forums.developer.nvidia.com/t/pip-library-wont-load-in-2021-1-2/222719/3
1,233
Markdown
46.461537
209
0.801298
aaravbajaj012/orbit.ReasonedExplorer/pyproject.toml
# This section defines the build system requirements [build-system] requires = ["setuptools >= 61.0"] build-backend = "setuptools.build_meta" # Project metadata [project] version = "0.1.0" name = "ext_template" # TODO description = "Extension Template for Orbit" # TODO keywords = ["extension", "template", "orbit"] # TODO readme = "README.md" requires-python = ">=3.10" license = {file = "LICENSE.txt"} classifiers = [ "Programming Language :: Python :: 3", ] authors = [ {name = "Nico Burger", email = "[email protected]"}, # TODO ] maintainers = [ {name = "Nico Burger", email = "[email protected]"}, # TODO ] # Tool dependent subtables [tool.setuptools] py-modules = [ 'orbit' ] # TODO, add modules required for your extension
767
TOML
22.999999
71
0.67927
aaravbajaj012/orbit.ReasonedExplorer/README.md
# Extension Template for Orbit [![IsaacSim](https://img.shields.io/badge/IsaacSim-2023.1.1-silver.svg)](https://docs.omniverse.nvidia.com/isaacsim/latest/overview.html) [![Orbit](https://img.shields.io/badge/Orbit-0.2.0-silver)](https://isaac-orbit.github.io/orbit/) [![Python](https://img.shields.io/badge/python-3.10-blue.svg)](https://docs.python.org/3/whatsnew/3.10.html) [![Linux platform](https://img.shields.io/badge/platform-linux--64-orange.svg)](https://releases.ubuntu.com/20.04/) [![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit&logoColor=white)](https://pre-commit.com/) ## Overview This repository serves as a template for building projects or extensions based on Orbit. It allows you to develop in an isolated environment, outside of the core Orbit repository. Furthermore, this template serves three use cases: - **Python Package** Can be installed into Isaac Sim's Python environment, making it suitable for users who want to integrate their extension to `Orbit` as a python package. - **Project Template** Ensures access to `Isaac Sim` and `Orbit` functionalities, which can be used as a project template. - **Omniverse Extension** Can be used as an Omniverse extension, ideal for projects that leverage the Omniverse platform's graphical user interface. **Key Features:** - `Isolation` Work outside the core Orbit repository, ensuring that your development efforts remain self-contained. - `Flexibility` This template is set up to allow your code to be run as an extension in Omniverse. **Keywords:** extension, template, orbit ### License The source code is released under a [BSD 3-Clause license](https://opensource.org/licenses/BSD-3-Clause). **Author: The ORBIT Project Developers<br /> Affiliation: [The AI Institute](https://theaiinstitute.com/)<br /> Maintainer: Nico Burger, [email protected]** ## Setup Depending on the use case defined [above](#overview), follow the instructions to set up your extension template. Start with the [Basic Setup](#basic-setup), which is required for either use case. ### Basic Setup #### Dependencies This template depends on Isaac Sim and Orbit. For detailed instructions on how to install these dependencies, please refer to the [installation guide](https://isaac-orbit.github.io/orbit/source/setup/installation.html). - [Isaac Sim](https://docs.omniverse.nvidia.com/isaacsim/latest/index.html) - [Orbit](https://isaac-orbit.github.io/orbit/) #### Configuration Decide on a name for your project or extension. This guide will refer to this name as `<your_extension_name>`. - Create a new repository based off this template [here](https://github.com/new?owner=isaac-orbit&template_name=orbit.ext_template&template_owner=isaac-orbit). Name your forked repository using the following convention: `"orbit.<your_extension_name>"`. - Clone your forked repository to a location **outside** the orbit repository. ```bash git clone <your_repository_url> ``` - Configure the template. Search for and replace **`TODO`**'s according to your extension's needs within the following files: - `config/extension.toml` - `pyproject.toml` - Rename your source folder. ```bash cd orbit.<your_extension_name> mv orbit/ext_template orbit/<your_extension_name> ``` - Set up a symbolic link from Orbit to this directory. This makes it convenient to index the python modules and look for extensions shipped with Isaac Sim and Orbit. ```bash ln -s <your_orbit_path> _orbit ``` #### Environment (Optional) For clarity, we will be using the `${ISAACSIM_PATH}/python.sh` command to call the Orbit specific python interpreter. However, you might be working from within a virtual environment, allowing you to use the `python` command directly, instead of `${ISAACSIM_PATH}/python.sh`. Information on setting up a virtual environment for Orbit can be found [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#setting-up-the-environment). The `ISAACSIM_PATH` should already be set from installing Orbit, see [here](https://isaac-orbit.github.io/orbit/source/setup/installation.html#configuring-the-environment-variables). #### Configure Python Interpreter In the provided configuration, we set the default Python interpreter to use the Python executable provided by Omniverse. This is specified in the `.vscode/settings.json` file: ```json "python.defaultInterpreterPath": "${env:ISAACSIM_PATH}/python.sh" ``` This setup requires you to have set up the `ISAACSIM_PATH` environment variable. If you want to use a different Python interpreter, you need to change the Python interpreter used by selecting and activating the Python interpreter of your choice in the bottom left corner of VSCode, or opening the command palette (`Ctrl+Shift+P`) and selecting `Python: Select Interpreter`. #### Set up IDE To setup the IDE, please follow these instructions: 1. Open the `orbit.<your_extension_template>` directory on Visual Studio Code IDE 2. Run VSCode Tasks, by pressing Ctrl+Shift+P, selecting Tasks: Run Task and running the setup_python_env in the drop down menu. If everything executes correctly, it should create a file .python.env in the .vscode directory. The file contains the python paths to all the extensions provided by Isaac Sim and Omniverse. This helps in indexing all the python modules for intelligent suggestions while writing code. ### Setup as Python Package / Project Template From within this repository, install your extension as a Python package to the Isaac Sim Python executable. ```bash ${ISAACSIM_PATH}/python.sh -m pip install --upgrade pip ${ISAACSIM_PATH}/python.sh -m pip install -e . ``` ### Setup as Omniverse Extension To enable your extension, follow these steps: 1. **Add the search path of your repository** to the extension manager: - Navigate to the extension manager using `Window` -> `Extensions`. - Click on the **Hamburger Icon** (☰), then go to `Settings`. - In the `Extension Search Paths`, enter the path that goes up to your repository's location without actually including the repository's own directory. For example, if your repository is located at `/home/code/orbit.ext_template`, you should add `/home/code` as the search path. - If not already present, in the `Extension Search Paths`, enter the path that leads to your local Orbit directory. For example: `/home/orbit/source/extensions` - Click on the **Hamburger Icon** (☰), then click `Refresh`. 2. **Search and enable your extension**: - Find your extension under the `Third Party` category. - Toggle it to enable your extension. ## Usage ### Python Package Import your python package within `Isaac Sim` and `Orbit` using: ```python import orbit.<your_extension_name> ``` ### Project Template We provide an example for training and playing a policy for ANYmal on flat terrain. Install [RSL_RL](https://github.com/leggedrobotics/rsl_rl) outside of the orbit repository, e.g. `home/code/rsl_rl`. ```bash git clone https://github.com/leggedrobotics/rsl_rl.git cd rsl_rl ${ISAACSIM_PATH}/python.sh -m pip install -e . ``` Train a policy. ```bash cd <path_to_your_extension> ${ISAACSIM_PATH}/python.sh scripts/rsl_rl/train.py --task Isaac-Velocity-Flat-Anymal-D-Template-v0 --num_envs 4096 --headless ``` Play the trained policy. ```bash ${ISAACSIM_PATH}/python.sh scripts/rsl_rl/play.py --task Isaac-Velocity-Flat-Anymal-D-Template-Play-v0 --num_envs 16 ``` ### Omniverse Extension We provide an example UI extension that will load upon enabling your extension defined in `orbit/ext_template/ui_extension_example.py`. For more information on UI extensions, enable and check out the source code of the `omni.isaac.ui_template` extension and refer to the introduction on [Isaac Sim Workflows 1.2.3. GUI](https://docs.omniverse.nvidia.com/isaacsim/latest/introductory_tutorials/tutorial_intro_workflows.html#gui). ## Pre-Commit Pre-committing involves using a framework to automate the process of enforcing code quality standards before code is actually committed to a version control system, like Git. This process involves setting up hooks that run automated checks, such as code formatting, linting (checking for programming errors, bugs, stylistic errors, and suspicious constructs), and running tests. If these checks pass, the commit is allowed; if not, the commit is blocked until the issues are resolved. This ensures that all code committed to the repository adheres to the defined quality standards, leading to a cleaner, more maintainable codebase. To do so, we use the [pre-commit](https://pre-commit.com/) module. Install the module using: ```bash pip install pre-commit ``` Run the pre-commit with: ```bash pre-commit run --all-files ``` ## Finalize You are all set and no longer need the template instructions - The `orbit/ext_template` and `scripts/rsl_rl` directories act as a reference template for your convenience. Delete them if no longer required. - When ready, use this `README.md` as a template and customize where appropriate. ## Docker / Cluster We are currently working on a docker and cluster setup for this template. In the meanwhile, please refer to the current setup provided in the Orbit [documentation](https://isaac-orbit.github.io/orbit/source/deployment/index.html). ## Troubleshooting ### Docker Container When running within a docker container, the following error has been encountered: `ModuleNotFoundError: No module named 'orbit'`. To mitigate, please comment out the docker specific environment definitions in `.vscode/launch.json` and run the following: ```bash echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/workspace/orbit.<your_extension_name>" >> ~/.bashrc source ~/.bashrc ``` ## Bugs & Feature Requests Please report bugs and request features using the [Issue Tracker](https://github.com/isaac-orbit/orbit.ext_template/issues).
9,898
Markdown
47.053398
724
0.761871
aaravbajaj012/orbit.ReasonedExplorer/scripts/rsl_rl/play.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to play a checkpoint if an RL agent from RSL-RL.""" from __future__ import annotations """Launch Isaac Sim Simulator first.""" import argparse from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # launch omniverse app app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app """Rest everything follows.""" import os import gymnasium as gym import omni.isaac.contrib_tasks # noqa: F401 import omni.isaac.orbit_tasks # noqa: F401 import torch from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx, ) from rsl_rl.runners import OnPolicyRunner # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> def main(): """Play with RSL-RL agent.""" # parse configuration env_cfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Loading experiment from directory: {log_root_path}") resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model ppo_runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device) ppo_runner.load(resume_path) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # obtain the trained policy for inference policy = ppo_runner.get_inference_policy(device=env.unwrapped.device) # export policy to onnx export_model_dir = os.path.join(os.path.dirname(resume_path), "exported") export_policy_as_onnx(ppo_runner.alg.actor_critic, export_model_dir, filename="policy.onnx") # reset environment obs, _ = env.get_observations() # simulate environment while simulation_app.is_running(): # run everything in inference mode with torch.inference_mode(): # agent stepping actions = policy(obs) # env stepping obs, _, _, _ = env.step(actions) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
3,566
Python
32.027777
101
0.706955
aaravbajaj012/orbit.ReasonedExplorer/scripts/rsl_rl/cli_args.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import argparse from typing import TYPE_CHECKING if TYPE_CHECKING: from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import RslRlOnPolicyRunnerCfg def add_rsl_rl_args(parser: argparse.ArgumentParser): """Add RSL-RL arguments to the parser. Args: parser: The parser to add the arguments to. """ # create a new argument group arg_group = parser.add_argument_group("rsl_rl", description="Arguments for RSL-RL agent.") # -- experiment arguments arg_group.add_argument( "--experiment_name", type=str, default=None, help="Name of the experiment folder where logs will be stored." ) arg_group.add_argument("--run_name", type=str, default=None, help="Run name suffix to the log directory.") # -- load arguments arg_group.add_argument("--resume", type=bool, default=None, help="Whether to resume from a checkpoint.") arg_group.add_argument("--load_run", type=str, default=None, help="Name of the run folder to resume from.") arg_group.add_argument("--checkpoint", type=str, default=None, help="Checkpoint file to resume from.") # -- logger arguments arg_group.add_argument( "--logger", type=str, default=None, choices={"wandb", "tensorboard", "neptune"}, help="Logger module to use." ) arg_group.add_argument( "--log_project_name", type=str, default=None, help="Name of the logging project when using wandb or neptune." ) def parse_rsl_rl_cfg(task_name: str, args_cli: argparse.Namespace) -> RslRlOnPolicyRunnerCfg: """Parse configuration for RSL-RL agent based on inputs. Args: task_name: The name of the environment. args_cli: The command line arguments. Returns: The parsed configuration for RSL-RL agent based on inputs. """ from omni.isaac.orbit_tasks.utils.parse_cfg import load_cfg_from_registry # load the default configuration rslrl_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(task_name, "rsl_rl_cfg_entry_point") # override the default configuration with CLI arguments if args_cli.seed is not None: rslrl_cfg.seed = args_cli.seed if args_cli.resume is not None: rslrl_cfg.resume = args_cli.resume if args_cli.load_run is not None: rslrl_cfg.load_run = args_cli.load_run if args_cli.checkpoint is not None: rslrl_cfg.load_checkpoint = args_cli.checkpoint if args_cli.run_name is not None: rslrl_cfg.run_name = args_cli.run_name if args_cli.logger is not None: rslrl_cfg.logger = args_cli.logger # set the project name for wandb and neptune if rslrl_cfg.logger in {"wandb", "neptune"} and args_cli.log_project_name: rslrl_cfg.wandb_project = args_cli.log_project_name rslrl_cfg.neptune_project = args_cli.log_project_name return rslrl_cfg
2,981
Python
38.759999
117
0.688695
aaravbajaj012/orbit.ReasonedExplorer/scripts/rsl_rl/train.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Script to train RL agent with RSL-RL.""" from __future__ import annotations """Launch Isaac Sim Simulator first.""" import argparse import os from omni.isaac.orbit.app import AppLauncher # local imports import cli_args # isort: skip # add argparse arguments parser = argparse.ArgumentParser(description="Train an RL agent with RSL-RL.") parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.") parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).") parser.add_argument("--cpu", action="store_true", default=False, help="Use CPU pipeline.") parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") # append RSL-RL cli arguments cli_args.add_rsl_rl_args(parser) # append AppLauncher cli args AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() # load cheaper kit config in headless if args_cli.headless: app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.gym.headless.kit" else: app_experience = f"{os.environ['EXP_PATH']}/omni.isaac.sim.python.kit" # launch omniverse app app_launcher = AppLauncher(args_cli, experience=app_experience) simulation_app = app_launcher.app """Rest everything follows.""" import os from datetime import datetime import gymnasium as gym import omni.isaac.orbit_tasks # noqa: F401 import torch from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.utils.dict import print_dict from omni.isaac.orbit.utils.io import dump_pickle, dump_yaml from omni.isaac.orbit_tasks.utils import get_checkpoint_path, parse_env_cfg from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, ) from rsl_rl.runners import OnPolicyRunner # Import extensions to set up environment tasks import orbit.ext_template.tasks # noqa: F401 TODO: import orbit.<your_extension_name> torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True torch.backends.cudnn.deterministic = False torch.backends.cudnn.benchmark = False def main(): """Train with RSL-RL agent.""" # parse configuration env_cfg: RLTaskEnvCfg = parse_env_cfg(args_cli.task, use_gpu=not args_cli.cpu, num_envs=args_cli.num_envs) agent_cfg: RslRlOnPolicyRunnerCfg = cli_args.parse_rsl_rl_cfg(args_cli.task, args_cli) # specify directory for logging experiments log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name) log_root_path = os.path.abspath(log_root_path) print(f"[INFO] Logging experiment in directory: {log_root_path}") # specify directory for logging runs: {time-stamp}_{run_name} log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S") if agent_cfg.run_name: log_dir += f"_{agent_cfg.run_name}" log_dir = os.path.join(log_root_path, log_dir) # create isaac environment env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # wrap for video recording if args_cli.video: video_kwargs = { "video_folder": os.path.join(log_dir, "videos"), "step_trigger": lambda step: step % args_cli.video_interval == 0, "video_length": args_cli.video_length, "disable_logger": True, } print("[INFO] Recording videos during training.") print_dict(video_kwargs, nesting=4) env = gym.wrappers.RecordVideo(env, **video_kwargs) # wrap around environment for rsl-rl env = RslRlVecEnvWrapper(env) # create runner from rsl-rl runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device) # write git state to logs runner.add_git_repo_to_log(__file__) # save resume path before creating a new log_dir if agent_cfg.resume: # get path to previous checkpoint resume_path = get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) print(f"[INFO]: Loading model checkpoint from: {resume_path}") # load previously trained model runner.load(resume_path) # set seed of the environment env.seed(agent_cfg.seed) # dump the configuration into log-directory dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg) dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg) dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg) dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg) # run training runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True) # close the simulator env.close() if __name__ == "__main__": # run the main execution main() # close sim app simulation_app.close()
5,231
Python
36.640288
117
0.703307
aaravbajaj012/orbit.ReasonedExplorer/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Description title = "Extension Template" # TODO: Please adapt to your title. description="Extension Template for Orbit" #TODO: Please adapt to your description. repository = "https://github.com/isaac-orbit/orbit.ext_template.git" # TODO: Please adapt to your repository. keywords = ["extension", "template", "orbit"] # TODO: Please adapt to your keywords. category = "orbit" readme = "README.md" [dependencies] "omni.kit.uiapp" = {} "omni.isaac.orbit" = {} "omni.isaac.orbit_assets" = {} "omni.isaac.orbit_tasks" = {} "omni.isaac.core" = {} "omni.isaac.gym" = {} "omni.replicator.isaac" = {} # Note: You can add additional dependencies here for your extension. # For example, if you want to use the omni.kit module, you can add it as a dependency: # "omni.kit" = {} [[python.module]] name = "orbit.ext_template" # TODO: Please adapt to your package name.
946
TOML
32.821427
110
0.700846
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """ Python module serving as a project/extension template. """ # Register Gym environments. from .tasks import * # Register UI extensions. from .ui_extension_example import *
300
Python
19.066665
56
0.743333
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/ui_extension_example.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import omni.ext import omni.ui as ui # Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)` def some_public_function(x: int): print("[orbit.ext_template] some_public_function was called with x: ", x) return x**x # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class ExampleExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[orbit.ext_template] startup") self._count = 0 self._window = ui.Window("My Window", width=300, height=300) with self._window.frame: with ui.VStack(): label = ui.Label("") def on_click(): self._count += 1 label.text = f"count: {self._count}" def on_reset(): self._count = 0 label.text = "empty" on_reset() with ui.HStack(): ui.Button("Add", clicked_fn=on_click) ui.Button("Reset", clicked_fn=on_reset) def on_shutdown(self): print("[orbit.ext_template] shutdown")
1,650
Python
33.395833
119
0.609697
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Package containing task implementations for various robotic environments.""" import os import toml # Conveniences to other module directories via relative paths ORBIT_TASKS_EXT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../")) """Path to the extension source directory.""" ORBIT_TASKS_METADATA = toml.load(os.path.join(ORBIT_TASKS_EXT_DIR, "config", "extension.toml")) """Extension metadata dictionary parsed from the extension.toml file.""" # Configure the module-level variables __version__ = ORBIT_TASKS_METADATA["package"]["version"] ## # Register Gym environments. ## from omni.isaac.orbit_tasks.utils import import_packages # The blacklist is used to prevent importing configs from sub-packages _BLACKLIST_PKGS = ["utils"] # Import all configs in this package import_packages(__name__, _BLACKLIST_PKGS)
969
Python
29.312499
95
0.744066
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Locomotion environments for legged robots.""" from .velocity import * # noqa
205
Python
21.888886
56
0.731707
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/velocity_env_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations import math from dataclasses import MISSING import omni.isaac.orbit.sim as sim_utils from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg from omni.isaac.orbit.envs import RLTaskEnvCfg from omni.isaac.orbit.managers import CurriculumTermCfg as CurrTerm from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm from omni.isaac.orbit.managers import RandomizationTermCfg as RandTerm from omni.isaac.orbit.managers import RewardTermCfg as RewTerm from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.managers import TerminationTermCfg as DoneTerm from omni.isaac.orbit.scene import InteractiveSceneCfg from omni.isaac.orbit.sensors import ContactSensorCfg, RayCasterCfg, patterns from omni.isaac.orbit.terrains import TerrainImporterCfg from omni.isaac.orbit.utils import configclass from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise import orbit.ext_template.tasks.locomotion.velocity.mdp as mdp ## # Pre-defined configs ## from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip ## # Scene definition ## @configclass class MySceneCfg(InteractiveSceneCfg): """Configuration for the terrain scene with a legged robot.""" # ground terrain terrain = TerrainImporterCfg( prim_path="/World/ground", terrain_type="generator", terrain_generator=ROUGH_TERRAINS_CFG, max_init_terrain_level=5, collision_group=-1, physics_material=sim_utils.RigidBodyMaterialCfg( friction_combine_mode="multiply", restitution_combine_mode="multiply", static_friction=1.0, dynamic_friction=1.0, ), visual_material=sim_utils.MdlFileCfg( mdl_path="{NVIDIA_NUCLEUS_DIR}/Materials/Base/Architecture/Shingles_01.mdl", project_uvw=True, ), debug_vis=False, ) # robots robot: ArticulationCfg = MISSING # sensors height_scanner = RayCasterCfg( prim_path="{ENV_REGEX_NS}/Robot/base", offset=RayCasterCfg.OffsetCfg(pos=(0.0, 0.0, 20.0)), attach_yaw_only=True, pattern_cfg=patterns.GridPatternCfg(resolution=0.1, size=[1.6, 1.0]), debug_vis=False, mesh_prim_paths=["/World/ground"], ) contact_forces = ContactSensorCfg(prim_path="{ENV_REGEX_NS}/Robot/.*", history_length=3, track_air_time=True) # lights light = AssetBaseCfg( prim_path="/World/light", spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), ) sky_light = AssetBaseCfg( prim_path="/World/skyLight", spawn=sim_utils.DomeLightCfg(color=(0.13, 0.13, 0.13), intensity=1000.0), ) ## # MDP settings ## @configclass class CommandsCfg: """Command specifications for the MDP.""" base_velocity = mdp.UniformVelocityCommandCfg( asset_name="robot", resampling_time_range=(10.0, 10.0), rel_standing_envs=0.02, rel_heading_envs=1.0, heading_command=True, heading_control_stiffness=0.5, debug_vis=True, ranges=mdp.UniformVelocityCommandCfg.Ranges( lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi) ), ) @configclass class ActionsCfg: """Action specifications for the MDP.""" joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) @configclass class ObservationsCfg: """Observation specifications for the MDP.""" @configclass class PolicyCfg(ObsGroup): """Observations for policy group.""" # observation terms (order preserved) base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) projected_gravity = ObsTerm( func=mdp.projected_gravity, noise=Unoise(n_min=-0.05, n_max=0.05), ) velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) actions = ObsTerm(func=mdp.last_action) height_scan = ObsTerm( func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("height_scanner")}, noise=Unoise(n_min=-0.1, n_max=0.1), clip=(-1.0, 1.0), ) def __post_init__(self): self.enable_corruption = True self.concatenate_terms = True # observation groups policy: PolicyCfg = PolicyCfg() @configclass class RandomizationCfg: """Configuration for randomization.""" # startup physics_material = RandTerm( func=mdp.randomize_rigid_body_material, mode="startup", params={ "asset_cfg": SceneEntityCfg("robot", body_names=".*"), "static_friction_range": (0.8, 0.8), "dynamic_friction_range": (0.6, 0.6), "restitution_range": (0.0, 0.0), "num_buckets": 64, }, ) add_base_mass = RandTerm( func=mdp.add_body_mass, mode="startup", params={"asset_cfg": SceneEntityCfg("robot", body_names="base"), "mass_range": (-5.0, 5.0)}, ) # reset base_external_force_torque = RandTerm( func=mdp.apply_external_force_torque, mode="reset", params={ "asset_cfg": SceneEntityCfg("robot", body_names="base"), "force_range": (0.0, 0.0), "torque_range": (-0.0, 0.0), }, ) reset_base = RandTerm( func=mdp.reset_root_state_uniform, mode="reset", params={ "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, "velocity_range": { "x": (-0.5, 0.5), "y": (-0.5, 0.5), "z": (-0.5, 0.5), "roll": (-0.5, 0.5), "pitch": (-0.5, 0.5), "yaw": (-0.5, 0.5), }, }, ) reset_robot_joints = RandTerm( func=mdp.reset_joints_by_scale, mode="reset", params={ "position_range": (0.5, 1.5), "velocity_range": (0.0, 0.0), }, ) # interval push_robot = RandTerm( func=mdp.push_by_setting_velocity, mode="interval", interval_range_s=(10.0, 15.0), params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, ) @configclass class RewardsCfg: """Reward terms for the MDP.""" # -- task track_lin_vel_xy_exp = RewTerm( func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) track_ang_vel_z_exp = RewTerm( func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} ) # -- penalties lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) feet_air_time = RewTerm( func=mdp.feet_air_time, weight=0.125, params={ "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), "command_name": "base_velocity", "threshold": 0.5, }, ) undesired_contacts = RewTerm( func=mdp.undesired_contacts, weight=-1.0, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, ) # -- optional penalties flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) @configclass class TerminationsCfg: """Termination terms for the MDP.""" time_out = DoneTerm(func=mdp.time_out, time_out=True) base_contact = DoneTerm( func=mdp.illegal_contact, params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, ) @configclass class CurriculumCfg: """Curriculum terms for the MDP.""" terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) ## # Environment configuration ## @configclass class LocomotionVelocityRoughEnvCfg(RLTaskEnvCfg): """Configuration for the locomotion velocity-tracking environment.""" # Scene settings scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5) # Basic settings observations: ObservationsCfg = ObservationsCfg() actions: ActionsCfg = ActionsCfg() commands: CommandsCfg = CommandsCfg() # MDP settings rewards: RewardsCfg = RewardsCfg() terminations: TerminationsCfg = TerminationsCfg() randomization: RandomizationCfg = RandomizationCfg() curriculum: CurriculumCfg = CurriculumCfg() def __post_init__(self): """Post initialization.""" # general settings self.decimation = 4 self.episode_length_s = 20.0 # simulation settings self.sim.dt = 0.005 self.sim.disable_contact_processing = True self.sim.physics_material = self.scene.terrain.physics_material # update sensor update periods # we tick all the sensors based on the smallest update period (physics update period) if self.scene.height_scanner is not None: self.scene.height_scanner.update_period = self.decimation * self.sim.dt if self.scene.contact_forces is not None: self.scene.contact_forces.update_period = self.sim.dt # check if terrain levels curriculum is enabled - if so, enable curriculum for terrain generator # this generates terrains with increasing difficulty and is useful for training if getattr(self.curriculum, "terrain_levels", None) is not None: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = True else: if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.curriculum = False
10,649
Python
32.596214
118
0.626538
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Locomotion environments with velocity-tracking commands. These environments are based on the `legged_gym` environments provided by Rudin et al. Reference: https://github.com/leggedrobotics/legged_gym """
336
Python
24.923075
86
0.764881
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/mdp/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """This sub-module contains the functions that are specific to the locomotion environments.""" from omni.isaac.orbit.envs.mdp import * # noqa: F401, F403 from .curriculums import * # noqa: F401, F403 from .rewards import * # noqa: F401, F403
370
Python
29.916664
94
0.732432
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/mdp/curriculums.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Common functions that can be used to create curriculum for the learning environment. The functions can be passed to the :class:`omni.isaac.orbit.managers.CurriculumTermCfg` object to enable the curriculum introduced by the function. """ from __future__ import annotations from collections.abc import Sequence from typing import TYPE_CHECKING import torch from omni.isaac.orbit.assets import Articulation from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.terrains import TerrainImporter if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def terrain_levels_vel( env: RLTaskEnv, env_ids: Sequence[int], asset_cfg: SceneEntityCfg = SceneEntityCfg("robot") ) -> torch.Tensor: """Curriculum based on the distance the robot walked when commanded to move at a desired velocity. This term is used to increase the difficulty of the terrain when the robot walks far enough and decrease the difficulty when the robot walks less than half of the distance required by the commanded velocity. .. note:: It is only possible to use this term with the terrain type ``generator``. For further information on different terrain types, check the :class:`omni.isaac.orbit.terrains.TerrainImporter` class. Returns: The mean terrain level for the given environment ids. """ # extract the used quantities (to enable type-hinting) asset: Articulation = env.scene[asset_cfg.name] terrain: TerrainImporter = env.scene.terrain command = env.command_manager.get_command("base_velocity") # compute the distance the robot walked distance = torch.norm(asset.data.root_pos_w[env_ids, :2] - env.scene.env_origins[env_ids, :2], dim=1) # robots that walked far enough progress to harder terrains move_up = distance > terrain.cfg.terrain_generator.size[0] / 2 # robots that walked less than half of their required distance go to simpler terrains move_down = distance < torch.norm(command[env_ids, :2], dim=1) * env.max_episode_length_s * 0.5 move_down *= ~move_up # update terrain levels terrain.update_env_origins(env_ids, move_up, move_down) # return the mean terrain level return torch.mean(terrain.terrain_levels.float())
2,376
Python
41.446428
112
0.742424
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/mdp/rewards.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from __future__ import annotations from typing import TYPE_CHECKING import torch from omni.isaac.orbit.managers import SceneEntityCfg from omni.isaac.orbit.sensors import ContactSensor if TYPE_CHECKING: from omni.isaac.orbit.envs import RLTaskEnv def feet_air_time(env: RLTaskEnv, command_name: str, sensor_cfg: SceneEntityCfg, threshold: float) -> torch.Tensor: """Reward long steps taken by the feet using L2-kernel. This function rewards the agent for taking steps that are longer than a threshold. This helps ensure that the robot lifts its feet off the ground and takes steps. The reward is computed as the sum of the time for which the feet are in the air. If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero. """ # extract the used quantities (to enable type-hinting) contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward first_contact = contact_sensor.compute_first_contact(env.step_dt)[:, sensor_cfg.body_ids] last_air_time = contact_sensor.data.last_air_time[:, sensor_cfg.body_ids] reward = torch.sum((last_air_time - threshold) * first_contact, dim=1) # no reward for zero command reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1 return reward def feet_air_time_positive_biped(env, command_name: str, threshold: float, sensor_cfg: SceneEntityCfg) -> torch.Tensor: """Reward long steps taken by the feet for bipeds. This function rewards the agent for taking steps up to a specified threshold and also keep one foot at a time in the air. If the commands are small (i.e. the agent is not supposed to take a step), then the reward is zero. """ contact_sensor: ContactSensor = env.scene.sensors[sensor_cfg.name] # compute the reward air_time = contact_sensor.data.current_air_time[:, sensor_cfg.body_ids] contact_time = contact_sensor.data.current_contact_time[:, sensor_cfg.body_ids] in_contact = contact_time > 0.0 in_mode_time = torch.where(in_contact, contact_time, air_time) single_stance = torch.sum(in_contact.int(), dim=1) == 1 reward = torch.min(torch.where(single_stance.unsqueeze(-1), in_mode_time, 0.0), dim=1)[0] reward = torch.clamp(reward, max=threshold) # no reward for zero command reward *= torch.norm(env.command_manager.get_command(command_name)[:, :2], dim=1) > 0.1 return reward
2,595
Python
43.75862
119
0.717148
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Configurations for velocity-based locomotion environments.""" # We leave this file empty since we don't want to expose any configs in this package directly. # We still need this file to import the "config" module in the parent package.
363
Python
35.399996
94
0.763085
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/rough_env_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from omni.isaac.orbit.utils import configclass from orbit.ext_template.tasks.locomotion.velocity.velocity_env_cfg import ( LocomotionVelocityRoughEnvCfg, ) ## # Pre-defined configs ## from omni.isaac.orbit_assets.anymal import ANYMAL_D_CFG # isort: skip @configclass class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # switch robot to anymal-d self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") @configclass class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # make a smaller scene for play self.scene.num_envs = 50 self.scene.env_spacing = 2.5 # spawn the robot randomly in the grid (instead of their terrain levels) self.scene.terrain.max_init_terrain_level = None # reduce the number of terrains to save memory if self.scene.terrain.terrain_generator is not None: self.scene.terrain.terrain_generator.num_rows = 5 self.scene.terrain.terrain_generator.num_cols = 5 self.scene.terrain.terrain_generator.curriculum = False # disable randomization for play self.observations.policy.enable_corruption = False # remove random pushing self.randomization.base_external_force_torque = None self.randomization.push_robot = None
1,617
Python
32.020408
81
0.683364
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/flat_env_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from omni.isaac.orbit.utils import configclass from .rough_env_cfg import AnymalDRoughEnvCfg @configclass class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg): def __post_init__(self): # post init of parent super().__post_init__() # override rewards self.rewards.flat_orientation_l2.weight = -5.0 self.rewards.dof_torques_l2.weight = -2.5e-5 self.rewards.feet_air_time.weight = 0.5 # change terrain to flat self.scene.terrain.terrain_type = "plane" self.scene.terrain.terrain_generator = None # no height scan self.scene.height_scanner = None self.observations.policy.height_scan = None # no terrain curriculum self.curriculum.terrain_levels = None class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg): def __post_init__(self) -> None: # post init of parent super().__post_init__() # make a smaller scene for play self.scene.num_envs = 50 self.scene.env_spacing = 2.5 # disable randomization for play self.observations.policy.enable_corruption = False # remove random pushing self.randomization.base_external_force_torque = None self.randomization.push_robot = None
1,382
Python
30.431817
60
0.656295
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause import gymnasium as gym from . import agents, flat_env_cfg, rough_env_cfg ## # Register Gym environments. ## gym.register( id="Isaac-Velocity-Flat-Anymal-D-Template-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg, }, ) gym.register( id="Isaac-Velocity-Flat-Anymal-D-Template-Play-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": flat_env_cfg.AnymalDFlatEnvCfg_PLAY, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDFlatPPORunnerCfg, }, ) gym.register( id="Isaac-Velocity-Rough-Anymal-D-Template-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg, }, ) gym.register( id="Isaac-Velocity-Rough-Anymal-D-Template-Play-v0", entry_point="omni.isaac.orbit.envs:RLTaskEnv", disable_env_checker=True, kwargs={ "env_cfg_entry_point": rough_env_cfg.AnymalDRoughEnvCfg_PLAY, "rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AnymalDRoughPPORunnerCfg, }, )
1,498
Python
27.283018
77
0.688251
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/rsl_rl_cfg.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from omni.isaac.orbit.utils import configclass from omni.isaac.orbit_tasks.utils.wrappers.rsl_rl import ( RslRlOnPolicyRunnerCfg, RslRlPpoActorCriticCfg, RslRlPpoAlgorithmCfg, ) @configclass class AnymalDRoughPPORunnerCfg(RslRlOnPolicyRunnerCfg): num_steps_per_env = 24 max_iterations = 1500 save_interval = 50 experiment_name = "anymal_d_rough" empirical_normalization = False policy = RslRlPpoActorCriticCfg( init_noise_std=1.0, actor_hidden_dims=[512, 256, 128], critic_hidden_dims=[512, 256, 128], activation="elu", ) algorithm = RslRlPpoAlgorithmCfg( value_loss_coef=1.0, use_clipped_value_loss=True, clip_param=0.2, entropy_coef=0.005, num_learning_epochs=5, num_mini_batches=4, learning_rate=1.0e-3, schedule="adaptive", gamma=0.99, lam=0.95, desired_kl=0.01, max_grad_norm=1.0, ) @configclass class AnymalDFlatPPORunnerCfg(AnymalDRoughPPORunnerCfg): def __post_init__(self): super().__post_init__() self.max_iterations = 300 self.experiment_name = "anymal_d_flat" self.policy.actor_hidden_dims = [128, 128, 128] self.policy.critic_hidden_dims = [128, 128, 128]
1,417
Python
26.26923
58
0.645025
aaravbajaj012/orbit.ReasonedExplorer/orbit/ext_template/tasks/locomotion/velocity/config/anymal_d/agents/__init__.py
# Copyright (c) 2022-2024, The ORBIT Project Developers. # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause from . import rsl_rl_cfg # noqa: F401, F403
168
Python
23.142854
56
0.720238
aaravbajaj012/orbit.ReasonedExplorer/docs/CHANGELOG.rst
Changelog --------- 0.1.0 (2024-01-29) ~~~~~~~~~~~~~~~~~~ Added ^^^^^ * Created an initial template for building an extension or project based on Orbit
155
reStructuredText
13.181817
81
0.593548
mati-nvidia/mc-widget-library/README.md
# Extension Project Template This project was automatically generated. - `app` - It is a folder link to the location of your *Omniverse Kit* based app. - `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path). Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better. Look for "mc.widgets" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately. Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.: ``` > app\omni.code.bat --ext-folder exts --enable omni.hello.world ``` # App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` # Sharing Your Extensions This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths. Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts` Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual. To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
2,031
Markdown
37.339622
258
0.756278
mati-nvidia/mc-widget-library/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
mati-nvidia/mc-widget-library/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
mati-nvidia/mc-widget-library/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
mati-nvidia/mc-widget-library/exts/mc.widgets/mc/widgets/demo.py
import carb import omni.ui as ui from ._widgets import CheckBoxGroup, CheckBoxGroupModel, TabGroup, BaseTab class DemoWindow(ui.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) with self.frame: with ui.VStack(): model = CheckBoxGroupModel(["Red", "Blue", "Green"]) self.cb_group = CheckBoxGroup("My CheckBox Group", model) def checkbox_changed(option_name, value): carb.log_info("This checkbox changed.") carb.log_info(f"{option_name} is {value}") def checkbox_group_changed(values): carb.log_info("The state of my CheckBoxGroup is now:") for name, value in values: carb.log_info(f"{name} is {value}") model.subscribe_value_changed_fn(checkbox_changed) model.subscribe_group_changed_fn(checkbox_group_changed) tab_group = TabGroup([MyTab1("Tab Header 1"), MyTab2("Tab Header 2"), MyTab3("Tab Header 3"),]) def destroy(self) -> None: super().destroy() self.cb_group.destroy() class MyTab1(BaseTab): def build_fn(self): with ui.VStack(style={"margin":5}): ui.Label("Hello!", alignment=ui.Alignment.CENTER, height=25) ui.Label("Check out this TabGroup Widget.", alignment=ui.Alignment.CENTER) ui.Spacer(height=40) class MyTab2(BaseTab): def build_fn(self): with ui.VStack(style={"margin":5}): with ui.HStack(spacing=2): color_model = ui.ColorWidget(0.125, 0.25, 0.5, width=0, height=0).model for item in color_model.get_item_children(): component = color_model.get_item_value_model(item) ui.FloatDrag(component) class MyTab3(BaseTab): def build_fn(self): with ui.VStack(style={"margin":5}): with ui.HStack(): ui.Label("Red: ", height=25) ui.FloatSlider() with ui.HStack(): ui.Label("Green: ", height=25) ui.FloatSlider() with ui.HStack(): ui.Label("Blue: ", height=25) ui.FloatSlider()
2,298
Python
38.63793
111
0.543516
mati-nvidia/mc-widget-library/exts/mc.widgets/mc/widgets/styles.py
import omni.ui as ui checkbox_group_style = { "HStack::checkbox_row" : { "margin_width": 18, "margin": 2 }, "Label::cb_label": { "margin_width": 10 } } tab_group_style = { "TabGroupBorder": { "background_color": ui.color.transparent, "border_color": ui.color(25), "border_width": 1 }, "Rectangle::TabGroupHeader" : { "background_color": ui.color(20), }, "ZStack::TabGroupHeader":{ "margin_width": 1 } } tab_style = { "" : { "background_color": ui.color(31), "corner_flag": ui.CornerFlag.TOP, "border_radius": 4, "color": ui.color(127) }, ":selected": { "background_color": ui.color(56), "color": ui.color(203) }, "Label": { "margin_width": 5, "margin_height": 3 } }
862
Python
19.547619
49
0.49768
mati-nvidia/mc-widget-library/exts/mc.widgets/mc/widgets/extension.py
import omni.ext from .demo import DemoWindow # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class MyExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[mc.widgets] MyExtension startup") self._window = DemoWindow("Demo Window", width=300, height=300) #settings = carb.settings.get_settings() # import fontawesome as fa # print(fa.icons['fa-python']) def on_shutdown(self): print("[mc.widgets] MyExtension shutdown") self._window.destroy() self._window = None
931
Python
43.38095
119
0.693878
mati-nvidia/mc-widget-library/exts/mc.widgets/mc/widgets/__init__.py
from .extension import * from ._widgets import CheckBoxGroup, TabGroup
70
Python
34.499983
45
0.814286
mati-nvidia/mc-widget-library/exts/mc.widgets/mc/widgets/_widgets.py
from functools import partial from typing import List import omni.ui as ui from . import styles class CheckBoxGroupModel: def __init__(self, option_names:List): self.options = [] self.bool_models = [] self.subscriptions = [] self._single_callbacks = [] self._group_callbacks = [] for option in option_names: self.add_checkbox_option(option) def add_checkbox_option(self, option_name): self.options.append(option_name) bool_model = ui.SimpleBoolModel() next_index = len(self.bool_models) self.bool_models.append(bool_model) self.subscriptions.append(bool_model.subscribe_value_changed_fn(partial(self.on_model_value_changed, next_index))) return bool_model def subscribe_value_changed_fn(self, callback_fn): self._single_callbacks.append(callback_fn) def subscribe_group_changed_fn(self, callback_fn): self._group_callbacks.append(callback_fn) def on_model_value_changed(self, index:int, model:ui.SimpleBoolModel): for callback in self._single_callbacks: option = self.options[index] callback(option, model.as_bool) for callback in self._group_callbacks: checkbox_values = [] for name, bool_model in zip(self.options, self.bool_models): checkbox_values.append((name, bool_model.as_bool)) callback(checkbox_values) def get_bool_model(self, option_name): index = self.options.index(option_name) return self.bool_models[index] def get_checkbox_options(self): return self.options def destroy(self): self.subscriptions = None self._single_callbacks = None self._group_callbacks = None class CheckBoxGroup: def __init__(self, group_name:str, model:CheckBoxGroupModel): self.group_name = group_name self.model = model self._build_widget() def _build_widget(self): with ui.VStack(width=0, height=0, style=styles.checkbox_group_style): ui.Label(f"{self.group_name}:") for option in self.model.get_checkbox_options(): with ui.HStack(name="checkbox_row", width=0, height=0): ui.CheckBox(model=self.model.get_bool_model(option)) ui.Label(option, name="cb_label") def destroy(self): self.model.destroy() class BaseTab: def __init__(self, name): self.name = name def build_fn(self): """Builds the contents for the tab. You must implement this function with the UI construction code that you want for you tab. This is set to be called by a ui.Frame so it must have only a single top-level widget. """ raise NotImplementedError("You must implement Tab.build_fn") class TabGroup: def __init__(self, tabs: List[BaseTab]): self.frame = ui.Frame(build_fn=self._build_widget) if not tabs: raise ValueError("You must provide at least one BaseTab object.") self.tabs = tabs self.tab_containers = [] self.tab_headers = [] def _build_widget(self): with ui.ZStack(style=styles.tab_group_style): ui.Rectangle(style_type_name_override="TabGroupBorder") with ui.VStack(): ui.Spacer(height=1) with ui.ZStack(height=0, name="TabGroupHeader"): ui.Rectangle(name="TabGroupHeader") with ui.VStack(): ui.Spacer(height=2) with ui.HStack(height=0, spacing=4): for x, tab in enumerate(self.tabs): tab_header = ui.ZStack(width=0, style=styles.tab_style) self.tab_headers.append(tab_header) with tab_header: rect = ui.Rectangle() rect.set_mouse_released_fn(partial(self._tab_clicked, x)) ui.Label(tab.name) with ui.ZStack(): for x, tab in enumerate(self.tabs): container_frame = ui.Frame(build_fn=tab.build_fn) self.tab_containers.append(container_frame) container_frame.visible = False # Initialize first tab self.select_tab(0) def select_tab(self, index: int): for x in range(len(self.tabs)): if x == index: self.tab_containers[x].visible = True self.tab_headers[x].selected = True else: self.tab_containers[x].visible = False self.tab_headers[x].selected = False def _tab_clicked(self, index, x, y, button, modifier): if button == 0: self.select_tab(index) def append_tab(self, tab: BaseTab): pass def destroy(self): self.frame.destroy()
5,092
Python
35.905797
122
0.5652
mati-nvidia/mc-widget-library/exts/mc.widgets/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Simple UI Extension Template" description="The simplest python extension example. Use it as a starting point for your extensions." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "mc.widgets" [python.pipapi] # List of additional directories with pip achives to be passed into pip using ``--find-links`` arg. # Relative paths are relative to extension root. Tokens can be used. # archiveDirs = ["path/to/pip_archive"] # Commands passed to pip install before extension gets enabled. Can also contain flags, like `--upgrade`, `--no--index`, etc. # Refer to: https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format requirements = [ "fontawesome" ] # Allow going to online index if package can't be found locally (not recommended) use_online_index = true # Use this to specify a list of additional repositories if your pip package is hosted somewhere other # than the default repo(s) configured in pip. Will pass these to pip with "--extra-index-url" argument # repositories = ["https://my.additional.pip_repo.com/"]
1,642
TOML
34.717391
125
0.743605
mati-nvidia/omni-code-with-me/README.md
# Code With Me This repository contains NVIDIA Omniverse extensions and projects created during [my live coding sessions on YouTube](https://www.youtube.com/@mati-codes). The goal of these projects and live coding sessions is to teach Omniverse development by example and to show developer workflows for creating Omniverse extensions, connectors and applications. I have created a tag for every past live coding session to record the state of the project at the end of the session. If you want to go back in time and see the exact code from a livestream, use the tags. Feel free to use any examples from these projects and reach out to me if you have any questions. ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
787
Markdown
70.636357
242
0.80305
mati-nvidia/omni-code-with-me/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
mati-nvidia/omni-code-with-me/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
mati-nvidia/omni-code-with-me/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/README.md
# Tutorial Framework [maticodes.tutorial.framework.core] A framework for creating in-app tutorials for NVIDIA Omniverse.
122
Markdown
29.749993
63
0.819672
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/maticodes/tutorial/framework/core/extension.py
# SPDX-License-Identifier: Apache-2.0 import omni.ext import omni.ui as ui from .window import TutorialWindow # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class TutorialFrameworkExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[maticodes.tutorial.framework.core] maticodes tutorial framework core startup") self._window = TutorialWindow() def on_shutdown(self): print("[maticodes.tutorial.framework.core] maticodes tutorial framework core shutdown") self._window.destroy() self._window = None
949
Python
36.999999
119
0.734457
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/maticodes/tutorial/framework/core/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
64
Python
15.249996
37
0.75
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/maticodes/tutorial/framework/core/window.py
# SPDX-License-Identifier: Apache-2.0 import omni.ui as ui class TutorialWindow(ui.Window): def __init__(self): super().__init__("Tutorial", width=300, height=300) self.frame.set_build_fn(self._build_window) step1 = Step(50, "Step 1", "This is step 1") step2 = Step(60, "Step 2", "This is step 2") step3 = Step(70, "Step 3", "This is step 3") self.steps = [step1, step2, step3] self.step_index = 0 def _build_window(self): with ui.VStack(): self.step_frame = ui.Frame() self.step_frame.set_build_fn(self._build_step_frame) with ui.HStack(height=20): ui.Button("Reset", width=0) ui.Spacer() ui.Button("Validate", width=0) with ui.HStack(height=0): def prev_func(): self.step_index -= 1 self.step_frame.rebuild() ui.Button("Previous", clicked_fn=prev_func) ui.Spacer() def next_func(): self.step_index += 1 self.step_frame.rebuild() ui.Button("Next", clicked_fn=next_func) def _build_step_frame(self): step = self.steps[self.step_index] step.build() class Step(): def __init__(self, num_lines=10, title="Step", text="Hello World"): self.num_lines = num_lines self.text = text self.title = title def build_title(self): ui.Label(self.title, height=0, alignment=ui.Alignment.CENTER) def build_content(self): with ui.VStack(): for x in range(self.num_lines): ui.Label(self.text) def build(self): with ui.VStack(): self.build_title() with ui.ScrollingFrame(): self.build_content()
1,878
Python
29.803278
71
0.518104
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "0.1.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["Matias Codesal"] # The title and description fields are primarily for displaying extension info in UI title = "Tutorial Framework" description="A framework for creating in-app tutorials for NVIDIA Omniverse." # Path (relative to the root) or content of readme markdown file for UI. readme = "README.md" # URL of the extension source repository. repository = "https://github.com/mati-nvidia/omni-code-with-me" # One of categories for UI. category = "Tutorial" # Keywords for the extension keywords = ["kit", "tutorial"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} # Main python module this extension provides, it will be publicly available as "import maticodes.tutorial.framework.core". [[python.module]] name = "maticodes.tutorial.framework.core" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,645
TOML
33.291666
122
0.75076
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [0.1.0] - 2023-05-09 - Pre-release version. Still WIP.
155
Markdown
16.333332
80
0.670968
mati-nvidia/omni-code-with-me/exts/maticodes.tutorial.framework.core/docs/index.rst
maticodes.tutorial.framework.core ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"maticodes.tutorial.framework.core" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
367
reStructuredText
16.523809
50
0.643052
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/README.md
# Save Reminder [maticodes.notify.reminder] A simple extension that reminds you to save your work on a timer. ![](data/notification.png) ## Preferences There are a few preferences that you can set to customize the functionality. You can access the preferences by clicking on Edit->Preferences. ![](data/settings.png)
320
Markdown
31.099997
141
0.775
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/maticodes/notify/reminder/preferences.py
# SPDX-License-Identifier: Apache-2.0 from omni.kit.window.preferences import PreferenceBuilder from omni.kit.widget.settings.settings_widget import SettingType import omni.ui as ui from . import constants as c class SaveReminderPreferences(PreferenceBuilder): def __init__(self): super().__init__("Reminders") def build(self): with ui.VStack(height=0, spacing=5): with self.add_frame("Save Reminder"): with ui.VStack(): # TODO: Is "min" a valid kwarg? self.create_setting_widget( "Enable Save Reminder", c.SAVE_ENABLED_SETTING, SettingType.BOOL, min=0 ) self.create_setting_widget( "Save Reminder Interval (seconds)", c.SAVE_INTERVAL_SETTING, SettingType.INT, min=0 ) self.create_setting_widget( "Save Reminder Message", c.SAVE_MESSAGE_SETTING, SettingType.STRING, min=0 )
1,041
Python
39.076922
107
0.572526
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/maticodes/notify/reminder/constants.py
# SPDX-License-Identifier: Apache-2.0 import carb SAVE_REMINDER_FIRED = carb.events.type_from_string("maticodes.notify.reminder.SAVE_REMINDER_FIRED") SAVE_INTERVAL_SETTING = "/persistent/exts/maticodes.notify.reminder/save/interval" SAVE_ENABLED_SETTING = "/persistent/exts/maticodes.notify.reminder/save/enabled" SAVE_MESSAGE_SETTING = "/persistent/exts/maticodes.notify.reminder/save/message" DEFAULT_SAVE_INTERVAL = 600 DEFAULT_SAVE_MESSAGE = "Hey! Don't forget to save!"
478
Python
38.916663
99
0.792887
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/maticodes/notify/reminder/extension.py
# SPDX-License-Identifier: Apache-2.0 import asyncio import carb import carb.settings import omni.ext import omni.kit.app import omni.kit.notification_manager as nm import omni.kit.window.preferences import omni.usd from . import constants as c from .preferences import SaveReminderPreferences class MaticodesNotifyReminderExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[maticodes.notify.reminder] maticodes notify reminder startup") self.settings = carb.settings.get_settings() self.settings.set_default(c.SAVE_ENABLED_SETTING, True) self.settings.set_default(c.SAVE_INTERVAL_SETTING, c.DEFAULT_SAVE_INTERVAL) self.settings.set_default(c.SAVE_MESSAGE_SETTING, c.DEFAULT_SAVE_MESSAGE) self._preferences_page = omni.kit.window.preferences.register_page(SaveReminderPreferences()) self.bus = omni.kit.app.get_app().get_message_bus_event_stream() self.save_fired_sub = self.bus.create_subscription_to_push_by_type(c.SAVE_REMINDER_FIRED, self.on_save_reminder) asyncio.ensure_future(self.reminder_timer()) def on_save_reminder(self, e: carb.events.IEvent): if self.settings.get_as_bool(c.SAVE_ENABLED_SETTING): message = self.settings.get(c.SAVE_MESSAGE_SETTING) ok_button = nm.NotificationButtonInfo("SAVE", on_complete=self.do_save) cancel_button = nm.NotificationButtonInfo("CANCEL", on_complete=None) notification = nm.post_notification( message, hide_after_timeout=False, duration=0, status=nm.NotificationStatus.WARNING, button_infos=[ok_button, cancel_button]) asyncio.ensure_future(self.reminder_timer()) def do_save(self): def save_finished(arg1, arg2, saved_files): if not saved_files: carb.log_error("No files saved! Are you working in an untitled stage?") else: carb.log_info(f"Saved the files: {saved_files}") omni.usd.get_context().save_stage_with_callback(save_finished) async def reminder_timer(self): await asyncio.sleep(self.settings.get(c.SAVE_INTERVAL_SETTING)) if hasattr(self, "bus"): self.bus.push(c.SAVE_REMINDER_FIRED) def on_shutdown(self): print("[maticodes.notify.reminder] maticodes notify reminder shutdown") self.save_fired_sub = None omni.kit.window.preferences.unregister_page(self._preferences_page) self._preferences_page = None
2,676
Python
44.372881
120
0.692078
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/maticodes/notify/reminder/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
64
Python
15.249996
37
0.75
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # Lists people or organizations that are considered the "authors" of the package. authors = ["Matias Codesal"] # The title and description fields are primarily for displaying extension info in UI title = "Save Reminder" description="A simple extension that reminds you to save your work on a timer." # Path (relative to the root) or content of readme markdown file for UI. readme = "README.md" # URL of the extension source repository. repository = "https://github.com/mati-nvidia/omni-code-with-me" # One of categories for UI. category = "Productivity" # Keywords for the extension keywords = ["kit", "save", "reminder", "timer"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/notification.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.window.preferences" = {} "omni.kit.widget.settings" = {} "omni.usd" = {} "omni.kit.notification_manager" = {} # Main python module this extension provides, it will be publicly available as "import maticodes.notify.reminder". [[python.module]] name = "maticodes.notify.reminder" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,772
TOML
33.096153
118
0.739842
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2023-05-09 - Initial version. - Users notified with a viewport notification. - Users preferences in the Reminder page to customize the functionality. - Notification includes a Save button that minimally saves the Stage.
329
Markdown
28.999997
80
0.753799
mati-nvidia/omni-code-with-me/exts/maticodes.notify.reminder/docs/index.rst
maticodes.notify.reminder ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"maticodes.notify.reminder" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
351
reStructuredText
15.761904
43
0.632479
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/widgets.py
# SPDX-License-Identifier: Apache-2.0 import asyncio import copy from functools import partial import carb import omni.kit.app import omni.kit.uiaudio from omni import ui from .config import ConfigManager, Settings from .constants import ( DEFAULT_BUTTON_COLOR, EDIT_BAR_HEIGHT, GUTTER_WIDTH, REORDER_EVENT, SOUNDS_CHANGED_EVENT, USER_CONFIG_PATH, ) from .style import get_button_style, slot_style class ButtonSlot: def __init__(self, sound_name, sound, width, height) -> None: self._settings = carb.settings.get_settings() self.edit_sub = self._settings.subscribe_to_node_change_events(Settings.EDIT_MODE, self._on_mode_changed) self.color_sub = None self.sound_name = sound_name self.sound = sound self.width = width self.height = height self._audio_iface = omni.kit.uiaudio.get_ui_audio_interface() self.msg_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.color_model = None self.frame = ui.Frame(width=self.width, height=self.height) self.frame.set_build_fn(self._build_frame) self.button_frame = None def _build_frame(self): with ui.HStack(style=slot_style): if self._settings.get(Settings.EDIT_MODE): with ui.ZStack(width=0, height=0): ui.Rectangle(width=GUTTER_WIDTH, height=EDIT_BAR_HEIGHT, name="edit_bar") with ui.VStack(): def drag(sound_name): return sound_name img = ui.Image( carb.tokens.get_tokens_interface().resolve("${glyphs}/toolbar_move_global.svg"), width=GUTTER_WIDTH, height=GUTTER_WIDTH, ) img.set_drag_fn(lambda: drag(self.sound_name)) with ui.HStack(): ui.Spacer() color = ConfigManager.resolved_config()["sounds_repo"][self.sound_name].get( "color", DEFAULT_BUTTON_COLOR ) self.color_model = ui.ColorWidget(*color, width=0, height=0).model self.color_sub = self.color_model.subscribe_end_edit_fn(self._on_color_changed) ui.Spacer() ui.Button( "", width=GUTTER_WIDTH, height=GUTTER_WIDTH, clicked_fn=self._rename_button, image_url=carb.tokens.get_tokens_interface().resolve("${glyphs}/pencil.svg"), ) ui.Button( "", width=GUTTER_WIDTH, height=GUTTER_WIDTH, clicked_fn=self._remove_button, image_url=carb.tokens.get_tokens_interface().resolve("${glyphs}/trash.svg"), ) self.button_frame = ui.Frame(width=self.width, height=self.height) self.button_frame.set_build_fn(self._build_button) def _rename_button(self): RenameWindow(self.sound_name) def _remove_button(self): active_sounds = copy.deepcopy(ConfigManager.resolved_config()["active_sounds"]) active_sounds.remove(self.sound_name) ConfigManager.user_config["active_sounds"] = active_sounds ConfigManager.save_user_config(USER_CONFIG_PATH) self.msg_bus.push(carb.events.type_from_string(REORDER_EVENT)) def _on_color_changed(self, model, item): sound_data = ConfigManager.resolved_config()["sounds_repo"][self.sound_name] color = [] for child in model.get_item_children(): component = model.get_item_value_model(child) color.append(component.as_float) sound_data["color"] = color[:3] ConfigManager.user_config["sounds_repo"][self.sound_name] = sound_data ConfigManager.save_user_config(USER_CONFIG_PATH) self.button_frame.rebuild() def _build_button(self): color = ConfigManager.resolved_config()["sounds_repo"][self.sound_name].get("color", DEFAULT_BUTTON_COLOR) button_style = get_button_style(color) def on_click(): self._audio_iface.play_sound(self.sound) if self._settings.get(Settings.EDIT_MODE): button = ui.Button( self.sound_name, height=self.height, width=self.width, clicked_fn=on_click, style=button_style ) button.set_accept_drop_fn(self._can_drop) button.set_drop_fn(partial(self._on_drop, button, self.sound_name)) else: ui.Button(self.sound_name, height=self.height, width=self.width, clicked_fn=on_click, style=button_style) def _can_drop(self, path: str) -> bool: return True def _on_drop(self, button, sound_name, e): if sound_name == e.mime_data: return active_sounds = copy.deepcopy(ConfigManager.resolved_config()["active_sounds"]) moved_id = active_sounds.index(e.mime_data) active_sounds.pop(moved_id) insert_index = active_sounds.index(sound_name) button_width = button.computed_width button_pos_x = button.screen_position_x button_center = button_pos_x + button_width / 2 if e.x > button_center: insert_index += 1 active_sounds.insert(insert_index, e.mime_data) ConfigManager.user_config["active_sounds"] = active_sounds self.msg_bus.push(carb.events.type_from_string(REORDER_EVENT)) def _on_mode_changed(self, value, event_type): self.frame.rebuild() class RenameWindow(ui.Window): title = "Rename Sound" def __init__(self, sound_name, **kwargs) -> None: super().__init__(self.title, flags=ui.WINDOW_FLAGS_MODAL, width=200, height=100, **kwargs) self.sound_name = sound_name self.name_model = None self.msg_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.frame.set_build_fn(self._build_frame) def _build_frame(self): with ui.VStack(): self.name_model = ui.StringField(height=0).model self.name_model.set_value(self.sound_name) ui.Spacer(height=10) with ui.HStack(): ui.Button("Ok", height=0, clicked_fn=self._rename_button) ui.Button("Cancel", height=0, clicked_fn=self._close_window) def _close_window(self): async def close_async(): self.destroy() asyncio.ensure_future(close_async()) def _rename_button(self): sounds_repo = copy.deepcopy(ConfigManager.resolved_config()["sounds_repo"]) new_name = self.name_model.as_string if new_name in sounds_repo: return active_sounds = copy.deepcopy(ConfigManager.resolved_config()["active_sounds"]) index = active_sounds.index(self.sound_name) active_sounds.remove(self.sound_name) active_sounds.insert(index, new_name) data = sounds_repo[self.sound_name] user_sounds_repo = copy.deepcopy(ConfigManager.user_config["sounds_repo"]) if self.sound_name in user_sounds_repo: del user_sounds_repo[self.sound_name] ConfigManager.user_config["active_sounds"] = active_sounds user_sounds_repo[new_name] = data ConfigManager.user_config["sounds_repo"] = user_sounds_repo ConfigManager.save_user_config(USER_CONFIG_PATH) self.msg_bus.push(carb.events.type_from_string(SOUNDS_CHANGED_EVENT)) self._close_window() class PaletteSlot: def __init__(self, sound_name, sound, width, height) -> None: self._settings = carb.settings.get_settings() self.sound_name = sound_name self.sound = sound self.width = width self.height = height self._audio_iface = omni.kit.uiaudio.get_ui_audio_interface() self.msg_bus = omni.kit.app.get_app().get_message_bus_event_stream() self.frame = ui.Frame(width=self.width, height=self.height) self.frame.set_build_fn(self._build_frame) def _build_frame(self): color = ConfigManager.resolved_config()["sounds_repo"][self.sound_name].get("color", DEFAULT_BUTTON_COLOR) style = {"background_color": ui.color(*color), "border_radius": 3} with ui.ZStack(): ui.Rectangle(style=style) with ui.HStack(style=slot_style, width=0): ui.Label(self.sound_name, alignment=ui.Alignment.CENTER) with ui.VStack(): ui.Spacer(height=1) with ui.HStack(): def on_play(): self._audio_iface.play_sound(self.sound) ui.Button( "", width=24, height=24, clicked_fn=on_play, image_url=carb.tokens.get_tokens_interface().resolve("${glyphs}/timeline_play.svg"), ) ui.Button( "", width=24, height=24, clicked_fn=self._add_active_sound, image_url=carb.tokens.get_tokens_interface().resolve("${glyphs}/plus.svg"), ) def _add_active_sound(self): active_sounds = copy.deepcopy(ConfigManager.resolved_config()["active_sounds"]) if self.sound_name not in active_sounds: active_sounds.append(self.sound_name) ConfigManager.user_config["active_sounds"] = active_sounds ConfigManager.save_user_config(USER_CONFIG_PATH) self.msg_bus.push(carb.events.type_from_string(SOUNDS_CHANGED_EVENT))
10,065
Python
41.652542
117
0.567213
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/config.py
# SPDX-License-Identifier: Apache-2.0 import copy import json import os from pathlib import Path import carb.settings import carb.tokens import omni.kit.app class ConfigManager: default_config = {} user_config = {} default_config_path = "data/default_config.json" @classmethod def _read_json(cls, filepath): with open(filepath, "r") as f: data = json.load(f) return data @classmethod def load_default_config(cls, ext_id): manager = omni.kit.app.get_app().get_extension_manager() ext_root_path = Path(manager.get_extension_path(ext_id)) filepath = ext_root_path / cls.default_config_path data = cls._read_json(filepath) for sound_name in data["sounds_repo"]: abs_path = Path(ext_root_path) / data["sounds_repo"][sound_name]["uri"] data["sounds_repo"][sound_name]["uri"] = str(abs_path) cls.default_config = data @classmethod def load_user_config(cls, filepath: Path): filepath = cls._resolve_path(filepath) if not os.path.exists(filepath): os.makedirs(os.path.dirname(filepath), exist_ok=True) else: data = cls._read_json(filepath) cls.user_config = data if not cls.user_config: cls.user_config = {"sounds_repo": {}} @classmethod def save_user_config(cls, filepath: Path): filepath = cls._resolve_path(filepath) with open(filepath, "w") as f: json.dump(cls.user_config, f, indent=4) @classmethod def _resolve_path(cls, filepath): return carb.tokens.get_tokens_interface().resolve(str(filepath)) @classmethod def resolved_config(cls): resolved_config = {} resolved_config.update(cls.default_config) resolved_config.update(cls.user_config) sounds_repo = copy.deepcopy(cls.default_config["sounds_repo"]) sounds_repo.update(cls.user_config["sounds_repo"]) resolved_config["sounds_repo"] = sounds_repo return resolved_config class TransientSettings: EDIT_MODE = "/exts/maticodes.soundboard.window/edit_mode" class PersistentSettings: BUTTON_WIDTH = "/exts/maticodes.soundboard.window/button_width" @classmethod def get_persistent_keys(cls): attrs = [attr for attr in dir(cls) if not callable(getattr(cls, attr)) and not attr.startswith("__")] return [getattr(cls, attr) for attr in attrs] class Settings(PersistentSettings, TransientSettings): pass class SettingsManager: PERSISTENT = "/persistent" def __init__(self): self._settings = carb.settings.get_settings() self._load_settings() def _load_settings(self): for key in PersistentSettings.get_persistent_keys(): value = self._settings.get(self.PERSISTENT + key) if value is not None: self._settings.set(key, value) def save_settings(self): for key in PersistentSettings.get_persistent_keys(): value = self._settings.get(key) self._settings.set(self.PERSISTENT + key, value) @property def settings(self): return self._settings
3,203
Python
28.943925
109
0.632532
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/style.py
# SPDX-License-Identifier: Apache-2.0 import omni.ui as ui slot_style = { "ColorWidget": { "margin_height": 5 }, "Rectangle::edit_bar": { "background_color": ui.color(.04), "border_radius": 7 } } def get_button_style(color): return { "": { "background_color": ui.color(*[c * 0.5 for c in color]), "background_gradient_color": ui.color(*color) }, ":hovered": { "background_color": ui.color(*[c * 0.75 for c in color]), "background_gradient_color": ui.color(*[c * 1.1 for c in color]), }, }
619
Python
23.799999
77
0.513732
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/constants.py
# SPDX-License-Identifier: Apache-2.0 from pathlib import Path import carb REORDER_EVENT = "maticodes.soundboard.window.BUTTONS_REORDERED" SOUNDS_CHANGED_EVENT = "maticodes.soundboard.window.SOUNDS_CHANGED" DATA_DIR = Path("${omni_data}/exts/maticodes.soundboard.window") USER_CONFIG_PATH = DATA_DIR / "user.config" GUTTER_WIDTH = 24 EDIT_BAR_HEIGHT = 110 DEFAULT_BUTTON_COLOR = (0.15, 0.15, 0.15)
403
Python
24.249998
67
0.754342
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/extension.py
# SPDX-License-Identifier: Apache-2.0 from .config import SettingsManager import omni.ext import omni.kit.app from .window import Soundboard # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class SoundboardWindowExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. MENU_PATH = "Window/Soundboard" def on_startup(self, ext_id): self.ext_id = ext_id self.settings_mgr = SettingsManager() editor_menu = omni.kit.ui.get_editor_menu() self._window = None self._menu = editor_menu.add_item(SoundboardWindowExtension.MENU_PATH, self._on_menu_click, toggle=True, value=True) self.show_window(True) def _on_menu_click(self, menu, toggled): self.show_window(toggled) def show_window(self, toggled): if toggled: if self._window is None: self._window = Soundboard("Soundboard", self.ext_id, width=800, height=500) self._window.set_visibility_changed_fn(self._visibility_changed_fn) else: self._window.show() else: if self._window is not None: self._window.hide() def _visibility_changed_fn(self, visible: bool): """Toggles window visibility and Window menu item checked state. Args: visible (bool): Whether the window is visible or not """ if self._menu: omni.kit.ui.get_editor_menu().set_value(SoundboardWindowExtension.MENU_PATH, visible) self.show_window(visible) def on_shutdown(self): if self._menu: omni.kit.ui.get_editor_menu().remove_item(self._menu) self.settings_mgr.save_settings() if self._window is not None: self._window.destroy() self._window = None
2,157
Python
35.576271
119
0.639777
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/__init__.py
# SPDX-License-Identifier: Apache-2.0 from .extension import *
64
Python
15.249996
37
0.75
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/window.py
# SPDX-License-Identifier: Apache-2.0 import copy import shutil from functools import partial from pathlib import Path from typing import List import carb.tokens import omni.kit.app import omni.kit.uiaudio import omni.ui as ui from omni.kit.window.drop_support import ExternalDragDrop from .config import ConfigManager, Settings from .constants import DATA_DIR, REORDER_EVENT, SOUNDS_CHANGED_EVENT, USER_CONFIG_PATH, GUTTER_WIDTH from .widgets import ButtonSlot, PaletteSlot class Soundboard(ui.Window): def __init__(self, title, ext_id, **kwargs): super().__init__(title, **kwargs) self.ext_id = ext_id self._sounds = {} self._buttons_frame = None self._slider_sub = None ConfigManager.load_default_config(self.ext_id) ConfigManager.load_user_config(USER_CONFIG_PATH) self._audio_iface = omni.kit.uiaudio.get_ui_audio_interface() self._load_sounds() self._settings = carb.settings.get_settings() self._settings_sub = self._settings.subscribe_to_node_change_events( Settings.BUTTON_WIDTH, self._on_settings_changed ) self._edit_sub = self._settings.subscribe_to_node_change_events(Settings.EDIT_MODE, self._on_edit_changed) self._external_drag_and_drop = None bus = omni.kit.app.get_app().get_message_bus_event_stream() reorder_event_type = carb.events.type_from_string(REORDER_EVENT) self._reorder_sub = bus.create_subscription_to_push_by_type(reorder_event_type, self._on_reorder) self._sounds_changed_sub = bus.create_subscription_to_push_by_type( carb.events.type_from_string(SOUNDS_CHANGED_EVENT), self._on_sounds_changed ) self.frame.set_build_fn(self._build_window) def _on_reorder(self, e): self._buttons_frame.rebuild() def _on_sounds_changed(self, e): self._load_sounds() self._buttons_frame.rebuild() def _on_edit_changed(self, item, event_type): self.frame.rebuild() def _build_window(self): edit_mode = self._settings.get(Settings.EDIT_MODE) with ui.VStack(): with ui.HStack(height=0): if edit_mode: ui.Label("Button Width: ", width=0) def slider_changed(model): self._settings.set(Settings.BUTTON_WIDTH, model.as_float) model = ui.SimpleFloatModel(self._settings.get(Settings.BUTTON_WIDTH)) self._slider_sub = model.subscribe_value_changed_fn(slider_changed) ui.FloatSlider(model, min=50, max=400, step=1) ui.Spacer() def set_edit_mode(button): button.checked = not button.checked if not button.checked: ConfigManager.save_user_config(USER_CONFIG_PATH) self._settings.set(Settings.EDIT_MODE, button.checked) button = ui.Button(text="Edit", height=0, width=0, checked=edit_mode) button.set_clicked_fn(partial(set_edit_mode, button)) self._buttons_frame = ui.Frame() self._buttons_frame.set_build_fn(self._build_buttons_frame) def _build_buttons_frame(self): button_width = self._settings.get(Settings.BUTTON_WIDTH) edit_mode = self._settings.get(Settings.EDIT_MODE) gutter_offset = GUTTER_WIDTH if edit_mode else 0 with ui.VStack(): with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, ): with ui.VGrid(column_width=button_width + gutter_offset): for sound_name in ConfigManager.resolved_config()["active_sounds"]: ButtonSlot(sound_name, self._sounds[sound_name], width=button_width, height=button_width) if edit_mode: with ui.ScrollingFrame( horizontal_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_ON, vertical_scrollbar_policy=ui.ScrollBarPolicy.SCROLLBAR_ALWAYS_OFF, height=75, ): with ui.ZStack(): ui.Rectangle(style={"background_color": ui.color.black}) with ui.VStack(): # ui.Spacer(height=5) with ui.HStack(style={"margin": 2}): for sound_name, sound_data in ConfigManager.resolved_config()[ "sounds_repo" ].items(): sound = self._load_sound(sound_data["uri"]) PaletteSlot(sound_name, sound, width=button_width, height=50) if self._external_drag_and_drop: self._external_drag_and_drop.destroy() self._external_drag_and_drop = None self._external_drag_and_drop = ExternalDragDrop( window_name=self.title, drag_drop_fn=self._on_ext_drag_drop ) elif self._external_drag_and_drop: self._external_drag_and_drop.destroy() self._external_drag_and_drop = None def _load_sounds(self): self._sounds = {} for sound_name in ConfigManager.resolved_config()["active_sounds"]: sound_data = ConfigManager.resolved_config()["sounds_repo"][sound_name] sound = self._load_sound(sound_data["uri"]) self._sounds[sound_name] = sound def _load_sound(self, filepath): return self._audio_iface.create_sound(filepath) def _on_settings_changed(self, item, event_type): if self._buttons_frame: self._buttons_frame.rebuild() def _on_ext_drag_drop(self, edd: ExternalDragDrop, payload: List[str]): paths = edd.expand_payload(payload) if paths: for p in paths: filepath = Path(p) if filepath.suffix in [".mp3", ".wav"]: dest = DATA_DIR / filepath.name dest = carb.tokens.get_tokens_interface().resolve(str(dest)) shutil.copy(filepath, dest) self._sounds[filepath.stem] = self._load_sound(dest) self._add_sound_to_config(filepath.stem, dest) ConfigManager.save_user_config(USER_CONFIG_PATH) self.frame.rebuild() def _add_sound_to_config(self, sound_name, file_path): active_sounds = copy.deepcopy(ConfigManager.resolved_config()["active_sounds"]) active_sounds.append(sound_name) ConfigManager.user_config["active_sounds"] = active_sounds if not ConfigManager.user_config.get("sounds_repo"): ConfigManager.user_config["sounds_repo"] = {} ConfigManager.user_config["sounds_repo"][sound_name] = {"uri": file_path} def show(self): self.visible = True def hide(self): self.visible = False def destroy(self) -> None: self._slider_sub = None if self._settings_sub: self._settings.unsubscribe_to_change_events(self._settings_sub) self._settings_sub = None if self._edit_sub: self._settings.unsubscribe_to_change_events(self._edit_sub) self._edit_sub = None if self._reorder_sub: self._reorder_sub.unsubscribe() self._reorder_sub = None if self._sounds_changed_sub: self._sounds_changed_sub.unsubscribe() self._sounds_changed_sub = None if self._external_drag_and_drop: self._external_drag_and_drop.destroy() self._external_drag_and_drop = None if self._buttons_frame: self._buttons_frame.destroy() self._buttons_frame = None super().destroy()
8,034
Python
41.739361
114
0.582898
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/maticodes/soundboard/window/scripts/create_default_config.py
# SPDX-License-Identifier: Apache-2.0 import json from pathlib import Path config_path = Path(__file__).parent.parent.parent.parent / "data" / "default_config.json" sounds = { "Applause": { "uri": "data/sounds/applause.wav" }, "Door Bell": { "uri": "data/sounds/door_bell.wav" }, "Door Bell": { "uri": "data/sounds/door_bell.wav" }, "Crowd Laughing": { "uri": "data/sounds/laugh_crowd.mp3" }, "Crowd Sarcastic Laughing": { "uri": "data/sounds/laugh_crowd_sarcastic.wav" }, "Level Complete": { "uri": "data/sounds/level_complete.wav" }, "Ooooh Yeah": { "uri": "data/sounds/oh_yeah.wav" }, "Pew Pew": { "uri": "data/sounds/pew_pew.wav" }, "Phone Ringing 1": { "uri": "data/sounds/phone_ring_analog.wav" }, "Phone Ringing 2": { "uri": "data/sounds/phone_ringing_digital.wav" }, "Rooster Crowing": { "uri": "data/sounds/rooster_crowing.wav" }, "Thank you": { "uri": "data/sounds/thank_you.wav" }, "Timer": { "uri": "data/sounds/timer.wav" }, "Woohoo": { "uri": "data/sounds/woohoo.wav" }, "Yes Scream": { "uri": "data/sounds/yes_scream.wav" }, } config = { "active_sounds": [key for key in sounds], "sounds_repo": sounds } with open(config_path, "w") as f: json.dump(config, f, indent=4)
1,441
Python
21.888889
89
0.536433
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Soundboard Window" description="A sound effects soundboard. Just for fun and for learning." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://github.com/mati-nvidia/omni-code-with-me" # One of categories for UI. category = "Audio" # Keywords for the extension keywords = ["kit", "sound", "example", "audio"] # Icon to show in the extension manager icon = "data/icon.png" # Preview to show in the extension manager preview_image = "data/soundboard_preview.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.uiaudio" = {} "omni.kit.window.drop_support" = {} # Main python module this extension provides, it will be publicly available as "import maticodes.soundboard.window". [[python.module]] name = "maticodes.soundboard.window" [settings] exts."maticodes.soundboard.window".button_width = 300 exts."maticodes.soundboard.window".edit_mode = false [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,301
TOML
27.304347
116
0.737125
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
mati-nvidia/omni-code-with-me/exts/maticodes.soundboard.window/docs/README.md
# Soundboard Window This is a simple sound effects soundboard extension. Have some fun with it and use it for learning Kit. Sound of the concepts that you can learn from the Code With Me recordings and this repository: - Drag and Drop - External Drag and Drop - Modal Window - Using persistent and transient carb.settings - Using carb.tokens - Custom events ## Performance Mode ![](../data/soundboard_preview.png) This mode is just a window with a grid of buttons to have a simple UX for playing sounds. Click on a button to play its sound. You can click on the "Edit" button to switch to "Edit" mode. ## Edit Mode ![](../data/edit_mode.png) In this mode, you can: - Resize the buttons - Drag and drop from the move handle to reorder the buttons. - Assign custom colors to the buttons - Rename buttons - Remove buttons - Preview sounds from the Sounds Palette at the bottom of the window - Add buttons from the Sounds Palette - Add a new sound to the active sounds and Sounds Palette by dragging a sound file into the window. ## Included Sound Files The included sound files in this extension are CC0 from [freesound.org](https://freesound.org).
1,151
Markdown
38.724137
187
0.762815
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/maticodes/layers/mute/extension.py
import carb import omni.ext from .window import LayerMuteWindow class LayersVisibilityExtension(omni.ext.IExt): def on_startup(self, ext_id): self._window = LayerMuteWindow("Layers Mute Window", width=300, height=300) def on_shutdown(self): self._window.destroy()
292
Python
21.53846
83
0.712329
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/maticodes/layers/mute/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/maticodes/layers/mute/window.py
from functools import partial import carb import omni.kit.commands import omni.kit.usd.layers as usd_layers import omni.ui as ui import omni.usd class LayerMuteWindow(ui.Window): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Using ui.Frame.set_build_fn() provides a function to be called with ui.Frame.rebuild() self.frame.set_build_fn(self.build_frame) # Using the same interfaces as Layers window self.layers: usd_layers.Layers = usd_layers.get_layers() self.layers_state: usd_layers.LayersState = self.layers.get_layers_state() self._event_subs = [] events_stream = omni.usd.get_context().get_stage_event_stream() self._event_subs.append( events_stream.create_subscription_to_pop_by_type( omni.usd.StageEventType.OPENED, self._on_stage_opened ) ) self._event_subs.append( self.layers.get_event_stream().create_subscription_to_pop(self._on_layers_changed) ) def build_frame(self): with ui.ScrollingFrame(): with ui.VStack(): layer_ids = self.layers_state.get_local_layer_identifiers() if len(layer_ids) < 2: ui.Label("There are currently no sublayers in this Stage.", alignment=ui.Alignment.CENTER) for layer_id in layer_ids: layer_name = self.layers_state.get_layer_name(layer_id) # Skip the root layer since it can't be muted. if layer_name != "Root Layer": is_muted = self.layers_state.is_layer_locally_muted(layer_id) button = ui.Button(layer_name, height=25, checked=not is_muted) button.set_clicked_fn(partial(self._on_clicked, layer_id, button)) def _on_clicked(self, layer_id, button): button.checked = not button.checked # Using the Kit command allows users to undo the change with Ctrl+Z omni.kit.commands.execute("SetLayerMuteness", layer_identifier=layer_id, muted=not button.checked) def _on_stage_opened(self, event: carb.events.IEvent): # If user changes stages, rebuild the window with a new list of layers. self.frame.rebuild() def _on_layers_changed(self, event: carb.events.IEvent): # If layers are added, removed or layer muteness changed. self.frame.rebuild() def destroy(self) -> None: for sub in self._event_subs: sub.unsubscribe() return super().destroy()
2,596
Python
40.887096
110
0.616333
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/maticodes/layers/mute/tests/__init__.py
from .test_hello_world import *
31
Python
30.999969
31
0.774194
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/maticodes/layers/mute/tests/test_hello_world.py
# NOTE: # omni.kit.test - std python's unittest module with additional wrapping to add suport for async/await tests # For most things refer to unittest docs: https://docs.python.org/3/library/unittest.html import omni.kit.test # Extnsion for writing UI tests (simulate UI interaction) import omni.kit.ui_test as ui_test # Import extension python module we are testing with absolute import path, as if we are external user (other extension) import maticodes.layers.visibility # Having a test class dervived from omni.kit.test.AsyncTestCase declared on the root of module will make it auto-discoverable by omni.kit.test class Test(omni.kit.test.AsyncTestCase): # Before running each test async def setUp(self): pass # After running each test async def tearDown(self): pass # Actual test, notice it is "async" function, so "await" can be used if needed async def test_hello_public_function(self): result = maticodes.layers.visibility.some_public_function(4) self.assertEqual(result, 256) async def test_window_button(self): # Find a label in our window label = ui_test.find("My Window//Frame/**/Label[*]") # Find buttons in our window add_button = ui_test.find("My Window//Frame/**/Button[*].text=='Add'") reset_button = ui_test.find("My Window//Frame/**/Button[*].text=='Reset'") # Click reset button await reset_button.click() self.assertEqual(label.widget.text, "empty") await add_button.click() self.assertEqual(label.widget.text, "count: 1") await add_button.click() self.assertEqual(label.widget.text, "count: 2")
1,690
Python
34.978723
142
0.685207
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/config/extension.toml
[package] # Semantic Versioning is used: https://semver.org/ version = "1.0.0" # The title and description fields are primarily for displaying extension info in UI title = "Layers Mute Window" description="A simple extension showing how to create a UI to replicate the mute functionality of the Layers Window." # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Location of change log file in target (final) folder of extension, relative to the root. # More info on writing changelog: https://keepachangelog.com/en/1.0.0/ changelog="docs/CHANGELOG.md" # Preview image and icon. Folder named "data" automatically goes in git lfs (see .gitattributes file). # Preview image is shown in "Overview" of Extensions window. Screenshot of an extension might be a good preview image. preview_image = "data/preview.png" # Icon is shown in Extensions window, it is recommended to be square, of size 256x256. icon = "data/icon.png" # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.kit.usd.layers" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import maticodes.layers.visibility". [[python.module]] name = "maticodes.layers.mute" [[test]] # Extra dependencies only to be used during test run dependencies = [ "omni.kit.ui_test" # UI testing extension ]
1,553
TOML
32.063829
118
0.74179
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/docs/CHANGELOG.md
# Changelog The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [1.0.0] - 2021-04-26 - Initial version of extension UI template with a window
178
Markdown
18.888887
80
0.702247
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/docs/README.md
# Layers Mute Window [maticodes.layers.mute] A simple extension showing how to create a UI to replicate the mute functionality of the Layers Window.
150
Markdown
36.749991
103
0.8
mati-nvidia/omni-code-with-me/exts/maticodes.layers.mute/docs/index.rst
maticodes.layers.visibility ############################# Example of Python only extension .. toctree:: :maxdepth: 1 README CHANGELOG .. automodule::"maticodes.layers.visibility" :platform: Windows-x86_64, Linux-x86_64 :members: :undoc-members: :show-inheritance: :imported-members: :exclude-members: contextmanager
355
reStructuredText
15.95238
44
0.63662
mati-nvidia/omni-code-with-me/scripts/create_blenshapes.py
# SPDX-License-Identifier: Apache-2.0 import math from pxr import Usd, UsdGeom, UsdSkel, Gf, Vt stage = Usd.Stage.CreateNew("blendshapes.usda") xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(xform.GetPrim()) stage.SetStartTimeCode(1.0) stage.SetEndTimeCode(17.0) UsdGeom.SetStageMetersPerUnit(stage, 0.01) UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) eq_tri_height = math.sqrt(3) * 1/2 skel_root = UsdSkel.Root.Define(stage, "/World/MorphingTri") extents_anim = { 1: [(-0.5, 0, 0), (0.5, eq_tri_height, 0)], 5: [(-0.5, 0, 0), (0.5, 2* eq_tri_height, 0)], 9: [(-0.5, 0, 0), (0.5, eq_tri_height, 0)], 13: [(-0.5, 0, 0), (0.5, eq_tri_height + (1-eq_tri_height), 0)], 17: [(-0.5, 0, 0), (0.5, 2*eq_tri_height + (1-eq_tri_height), 0)], } extents_attr = skel_root.CreateExtentAttr() for timesample, value in extents_anim.items(): extents_attr.Set(value, timesample) # Skeleton is required even if it's empty skel = UsdSkel.Skeleton.Define(stage, skel_root.GetPath().AppendChild("Skel")) mesh = UsdGeom.Mesh.Define(stage, "/World/MorphingTri/Mesh") mesh_binding = UsdSkel.BindingAPI.Apply(mesh.GetPrim()) # This binding could go on SkelRoot too. It will inherit down to the mesh. mesh_binding.CreateSkeletonRel().SetTargets([skel.GetPath()]) points = Vt.Vec3fArray([ (0.5, 0, 0), (0, eq_tri_height, 0), (-0.5, 0, 0) ]) face_vert_indices = [ 0, 1, 2 ] face_vert_counts = [3] mesh.CreatePointsAttr(points) mesh.CreateFaceVertexIndicesAttr(face_vert_indices) mesh.CreateFaceVertexCountsAttr(face_vert_counts) iso = UsdSkel.BlendShape.Define(stage, mesh.GetPath().AppendChild("iso")) iso.CreateOffsetsAttr().Set([(0, eq_tri_height, 0)]) iso.CreatePointIndicesAttr().Set([1]) right = UsdSkel.BlendShape.Define(stage, mesh.GetPath().AppendChild("right")) right.CreateOffsetsAttr().Set([(-0.5, 1-eq_tri_height, 0)]) right.CreatePointIndicesAttr().Set([1]) mesh_binding = UsdSkel.BindingAPI.Apply(mesh.GetPrim()) mesh_binding.CreateBlendShapesAttr().Set(["iso", "right"]) mesh_binding.CreateBlendShapeTargetsRel().SetTargets([iso.GetPath(), right.GetPath()]) # anim = UsdSkel.Animation.Define(stage, skel_root.GetPath().AppendChild("Anim")) # anim.CreateBlendShapesAttr().Set(["right", "iso"]) # anim.CreateBlendShapeWeightsAttr().Set([1.0, 2.0]) anim = UsdSkel.Animation.Define(stage, skel_root.GetPath().AppendChild("Anim")) anim.CreateBlendShapesAttr().Set(["right", "iso"]) # Frame 1 anim.CreateBlendShapeWeightsAttr().Set([0.0, 0.0], 1.0) # Frame 5 anim.CreateBlendShapeWeightsAttr().Set([0.0, 1.0], 5.0) # Frame 9 anim.CreateBlendShapeWeightsAttr().Set([0.0, 0.0], 9.0) # Frame 13 anim.CreateBlendShapeWeightsAttr().Set([1.0, 0.0], 13.0) # Frame 17 anim.CreateBlendShapeWeightsAttr().Set([1.0, 1.0], 17.0) root_binding = UsdSkel.BindingAPI.Apply(skel_root.GetPrim()) root_binding.CreateAnimationSourceRel().AddTarget(anim.GetPath()) stage.Save()
2,929
Python
32.295454
86
0.707067
mati-nvidia/omni-code-with-me/scripts/basic_skel.py
# SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom, UsdSkel, Gf, Vt stage = Usd.Stage.CreateNew("test_arm.usda") xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(xform.GetPrim()) stage.SetStartTimeCode(1.0) stage.SetEndTimeCode(10.0) UsdGeom.SetStageMetersPerUnit(stage, 0.01) UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) skel_root = UsdSkel.Root.Define(stage, "/World/Arm") # Create Mesh mesh = UsdGeom.Mesh.Define(stage, "/World/Arm/Mesh") points = Vt.Vec3fArray([ # Hand (0.5, -0.5, 4), (-0.5, -0.5, 4), (0.5, 0.5, 4), (-0.5, 0.5, 4), # Shoulder (-0.5, -0.5, 0), (0.5, -0.5, 0), (-0.5, 0.5, 0), (0.5, 0.5, 0), # Elbow (-0.5, 0.5, 2), (0.5, 0.5, 2), (0.5, -0.5, 2), (-0.5, -0.5, 2) ]) face_vert_indices = [ 2, 3, 1, 0, 6, 7, 5, 4, 8, 9, 7, 6, 3, 2, 9, 8, 10, 11, 4, 5, 0, 1, 11, 10, 7, 9, 10, 5, 9, 2, 0, 10, 3, 8, 11, 1, 8, 6, 4, 11 ] face_vert_counts = [4] * 10 mesh.CreatePointsAttr(points) mesh.CreateFaceVertexIndicesAttr(face_vert_indices) mesh.CreateFaceVertexCountsAttr(face_vert_counts) skeleton = UsdSkel.Skeleton.Define(stage, "/World/Arm/Rig") joints = ["Shoulder", "Shoulder/Elbow", "Shoulder/Elbow/Hand"] skeleton.CreateJointsAttr(joints) # World space xforms. Who cares about my parents? bind_xforms = Vt.Matrix4dArray([ Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)), Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,2,1)), Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,4,1)) ]) skeleton.CreateBindTransformsAttr(bind_xforms) # Local space xforms. What's my offset from my parent joint? rest_xforms = Vt.Matrix4dArray([ Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,0,1)), Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,2,1)), Gf.Matrix4d((1,0,0,0),(0,1,0,0),(0,0,1,0),(0,0,2,1)) ]) skeleton.CreateRestTransformsAttr(rest_xforms) # TODO: Do I need to apply BindingAPI to skel root? binding_root = UsdSkel.BindingAPI.Apply(skel_root.GetPrim()) binding_mesh = UsdSkel.BindingAPI.Apply(mesh.GetPrim()) binding_skel = UsdSkel.BindingAPI.Apply(skeleton.GetPrim()) binding_mesh.CreateSkeletonRel().SetTargets([skeleton.GetPath()]) # This is index in joints property for each vertex. joint_indices = binding_mesh.CreateJointIndicesPrimvar(False, 1) joint_indices.Set([2,2,2,2, 0,0,0,0, 1,1,1,1]) joint_weights = binding_mesh.CreateJointWeightsPrimvar(False, 1) joint_weights.Set([1,1,1,1, 1,1,1,1, 1,1,1,1]) identity = Gf.Matrix4d().SetIdentity() binding_mesh.CreateGeomBindTransformAttr(identity) skel_anim = UsdSkel.Animation.Define(stage, skeleton.GetPath().AppendPath("Anim")) binding_skel.CreateAnimationSourceRel().SetTargets([skel_anim.GetPath()]) skel_anim.CreateJointsAttr().Set(["Shoulder/Elbow"]) skel_anim.CreateTranslationsAttr().Set(Vt.Vec3fArray([(0.0, 0.0, 2.0)])) skel_anim.CreateScalesAttr().Set(Vt.Vec3hArray([(1.0, 1.0, 1.0)])) rot_attr = skel_anim.CreateRotationsAttr() rot_anim = { 1: [(1.0,0.0,0.0,0.0)], 10: [(0.7071, 0.7071, 0.0, 0.0)] } for key in rot_anim: values = rot_anim[key] quats = [] for value in values: quats.append(Gf.Quatf(*value)) rot_attr.Set(Vt.QuatfArray(quats), key) stage.Save()
3,222
Python
33.655914
82
0.655183
mati-nvidia/omni-code-with-me/scripts/create_prvw_surf.py
# SPDX-License-Identifier: Apache-2.0 import omni.usd from pxr import UsdShade, UsdGeom, Sdf stage = omni.usd.get_context().get_stage() UsdGeom.SetStageUpAxis(stage, UsdGeom.Tokens.y) billboard = UsdGeom.Mesh.Define(stage, "/World/billboard") billboard.CreatePointsAttr([(-100, -100, 0), (100, -100, 0), (100, 100, 0), (-100, 100,0)]) billboard.CreateFaceVertexCountsAttr([4]) billboard.CreateFaceVertexIndicesAttr([0, 1, 2, 3]) billboard.CreateExtentAttr([(-100, -100, 0), (100, 100, 0)]) tex_coords = UsdGeom.PrimvarsAPI(billboard).CreatePrimvar("st", Sdf.ValueTypeNames.TexCoord2fArray, UsdGeom.Tokens.varying) tex_coords.Set([(0, 0), (1, 0), (1, 1), (0, 1)]) material = UsdShade.Material.Define(stage, "/World/PreviewMtl") pbr_shader = UsdShade.Shader.Define(stage, "/World/PreviewMtl/PBRShader") pbr_shader.CreateIdAttr("UsdPreviewSurface") pbr_shader.CreateInput("roughness", Sdf.ValueTypeNames.Float).Set(0.4) pbr_shader.CreateInput("occlusion", Sdf.ValueTypeNames.Float) pbr_shader.CreateInput("displacement", Sdf.ValueTypeNames.Float) pbr_shader.CreateInput("normal", Sdf.ValueTypeNames.Normal3f) pbr_shader.CreateInput("metallic", Sdf.ValueTypeNames.Float).Set(0.0) pbr_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((1.0, 0.0, 0.0)) material.CreateSurfaceOutput().ConnectToSource(pbr_shader.ConnectableAPI(), "surface") material.CreateDisplacementOutput().ConnectToSource(pbr_shader.ConnectableAPI(), "displacement") st_reader = UsdShade.Shader.Define(stage, '/World/PreviewMtl/st_reader') st_reader.CreateIdAttr('UsdPrimvarReader_float2') transform2d = UsdShade.Shader.Define(stage, '/World/PreviewMtl/transform2d') transform2d.CreateIdAttr("UsdTransform2d") transform2d.CreateInput("in", Sdf.ValueTypeNames.Float2).ConnectToSource(st_reader.ConnectableAPI(), 'result') transform2d.CreateInput("rotation", Sdf.ValueTypeNames.Float) transform2d.CreateInput("scale", Sdf.ValueTypeNames.Float2).Set((1.0, 1.0)) transform2d.CreateInput("translation", Sdf.ValueTypeNames.Float2) # Diffuse diffuseTextureSampler = UsdShade.Shader.Define(stage,'/World/PreviewMtl/diffuseTexture') diffuseTextureSampler.CreateIdAttr('UsdUVTexture') diffuseTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/Users/mcodesal/Downloads/Ground062S_1K-PNG/Ground062S_1K_Color.png") diffuseTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(transform2d.ConnectableAPI(), 'result') diffuseTextureSampler.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") diffuseTextureSampler.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") diffuseTextureSampler.CreateOutput('rgb', Sdf.ValueTypeNames.Float3) pbr_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).ConnectToSource(diffuseTextureSampler.ConnectableAPI(), 'rgb') # Roughness roughTextureSampler = UsdShade.Shader.Define(stage,'/World/PreviewMtl/roughnessTexture') roughTextureSampler.CreateIdAttr('UsdUVTexture') roughTextureSampler.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/Users/mcodesal/Downloads/Ground062S_1K-PNG/Ground062S_1K_Roughness.png") roughTextureSampler.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(transform2d.ConnectableAPI(), 'result') roughTextureSampler.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") roughTextureSampler.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") roughTextureSampler.CreateOutput('r', Sdf.ValueTypeNames.Float) pbr_shader.CreateInput("roughness", Sdf.ValueTypeNames.Color3f).ConnectToSource(roughTextureSampler.ConnectableAPI(), 'r') # AO ao = UsdShade.Shader.Define(stage,'/World/PreviewMtl/aoTexture') ao.CreateIdAttr('UsdUVTexture') ao.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/Users/mcodesal/Downloads/Ground062S_1K-PNG/Ground062S_1K_AmbientOcclusion.png") ao.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(transform2d.ConnectableAPI(), 'result') ao.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") ao.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") ao.CreateOutput('r', Sdf.ValueTypeNames.Float) pbr_shader.CreateInput("occlusion", Sdf.ValueTypeNames.Color3f).ConnectToSource(ao.ConnectableAPI(), 'r') # Displacement displace = UsdShade.Shader.Define(stage,'/World/PreviewMtl/displaceTexture') displace.CreateIdAttr('UsdUVTexture') displace.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/Users/mcodesal/Downloads/Ground062S_1K-PNG/Ground062S_1K_Displacement.png") displace.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(transform2d.ConnectableAPI(), 'result') displace.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") displace.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") displace.CreateOutput('r', Sdf.ValueTypeNames.Float) pbr_shader.CreateInput("displacement", Sdf.ValueTypeNames.Color3f).ConnectToSource(displace.ConnectableAPI(), 'r') # Normal normal = UsdShade.Shader.Define(stage,'/World/PreviewMtl/normalTexture') normal.CreateIdAttr('UsdUVTexture') normal.CreateInput('file', Sdf.ValueTypeNames.Asset).Set("C:/Users/mcodesal/Downloads/Ground062S_1K-PNG/Ground062S_1K_NormalGL.png") normal.CreateInput("st", Sdf.ValueTypeNames.Float2).ConnectToSource(transform2d.ConnectableAPI(), 'result') normal.CreateInput("wrapS", Sdf.ValueTypeNames.Token).Set("repeat") normal.CreateInput("wrapT", Sdf.ValueTypeNames.Token).Set("repeat") normal.CreateInput("bias", Sdf.ValueTypeNames.Float4).Set((-1, -1, -1, 0)) normal.CreateInput("scale", Sdf.ValueTypeNames.Float4).Set((2.0, 2.0, 2.0, 1.0)) normal.CreateInput("sourceColorSpace", Sdf.ValueTypeNames.Token).Set("raw") normal.CreateOutput('rgb', Sdf.ValueTypeNames.Float3) pbr_shader.CreateInput("normal", Sdf.ValueTypeNames.Color3f).ConnectToSource(normal.ConnectableAPI(), 'rgb') st_input = material.CreateInput('frame:stPrimvarName', Sdf.ValueTypeNames.Token) st_input.Set('st') st_reader.CreateInput('varname',Sdf.ValueTypeNames.Token).ConnectToSource(st_input) billboard.GetPrim().ApplyAPI(UsdShade.MaterialBindingAPI) UsdShade.MaterialBindingAPI(billboard).Bind(material)
6,068
Python
60.30303
146
0.798451
mati-nvidia/omni-code-with-me/scripts/mesh_example.py
# SPDX-License-Identifier: Apache-2.0 from pxr import Usd, UsdGeom, UsdSkel, Gf, Vt stage = Usd.Stage.CreateNew("test_mesh.usda") xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, "/World") stage.SetDefaultPrim(xform.GetPrim()) # Create Mesh mesh = UsdGeom.Mesh.Define(stage, "/World/Mesh") points = Vt.Vec3fArray([ # Top, Right, Bottom, Left (0.0, 1.0, 0.0), (1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, 1.0, 1.0), (1.0, 0.0, 1.0), (0.0, -1.0, 1.0), (-1.0, 0.0, 1.0), ]) face_vert_indices = [ 0, 1, 2, 3, 0, 4, 5, 1, 1, 5, 6, 2, 6, 7, 3, 2, 7, 4, 0, 3, 7, 6, 5, 4 ] face_vert_counts = [4] * int(len(face_vert_indices) / 4.0) #[4] * 2 mesh.CreatePointsAttr(points) mesh.CreateFaceVertexIndicesAttr(face_vert_indices) mesh.CreateFaceVertexCountsAttr(face_vert_counts) #mesh.CreateSubdivisionSchemeAttr("none") stage.Save()
880
Python
24.911764
73
0.614773
mati-nvidia/omni-code-with-me/scripts/variant_set_basics.py
# SPDX-License-Identifier: Apache-2.0 import omni.usd from pxr import UsdGeom stage = omni.usd.get_context().get_stage() xform: UsdGeom.Xform = UsdGeom.Xform.Define(stage, "/World/MyPlane") plane: UsdGeom.Mesh = UsdGeom.Mesh.Define(stage, "/World/MyPlane/Plane") # plane.CreatePointsAttr().Set([(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50)]) # plane.CreateFaceVertexCountsAttr().Set([4]) # plane.CreateFaceVertexIndicesAttr().Set([0, 2, 3, 1]) # plane.CreateExtentAttr().Set([(-50, 0, -50), (50, 0, 50)]) xform_prim = xform.GetPrim() plane_prim = plane.GetPrim() # prim.GetAttribute("primvars:displayColor").Set([(1.0, 1.0, 0.0)]) ################# # Shading Variant ################# variants = { "default": (1.0, 1.0, 0.0), "red": (1.0, 0.0, 0.0), "blue": (0.0, 0.0, 1.0), "green": (0.0, 1.0, 0.0) } shading_varset = xform_prim.GetVariantSets().AddVariantSet("shading") for variant_name in variants: shading_varset.AddVariant(variant_name) # Author opinions in for each variant. You could do this in the previous for loop too. for variant_name in variants: # You must select a variant to author opinion for it. shading_varset.SetVariantSelection(variant_name) with shading_varset.GetVariantEditContext(): # Specs authored within this context are authored just for the variant. plane_prim.GetAttribute("primvars:displayColor").Set([variants[variant_name]]) # Remember to set the variant you want selected once you're done authoring. shading_varset.SetVariantSelection(list(variants.keys())[0]) ################## # Geometry Variant ################## variants = { "default": { "points": [(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50)], "indices": [0, 2, 3, 1], "counts": [4] }, "sloped": { "points": [(-50, 0, -50), (50, 0, -50), (-50, 20, 50), (50, 20, 50)], "indices": [0, 2, 3, 1], "counts": [4] }, "stacked": { "points": [(-50, 0, -50), (50, 0, -50), (-50, 0, 50), (50, 0, 50), (-50, 10, -50), (-50, 10, 50), (50, 10, 50)], "indices": [0, 2, 3, 1, 4, 5, 6], "counts": [4, 3] } } shading_varset = xform_prim.GetVariantSets().AddVariantSet("geometry") for variant_name in variants: shading_varset.AddVariant(variant_name) # Author opinions in for each variant. You could do this in the previous for loop too. for variant_name in variants: # You must select a variant to author opinion for it. shading_varset.SetVariantSelection(variant_name) with shading_varset.GetVariantEditContext(): # Specs authored within this context are authored just for the variant. plane.CreatePointsAttr().Set(variants[variant_name]["points"]) plane.CreateFaceVertexCountsAttr().Set(variants[variant_name]["counts"]) plane.CreateFaceVertexIndicesAttr().Set(variants[variant_name]["indices"]) # Remember to set the variant you want selected once you're done authoring. shading_varset.SetVariantSelection(list(variants.keys())[0]) ################## # Add Spheres Variant ################## variants = { "default": 1, "two": 2, "three": 3 } shading_varset = xform_prim.GetVariantSets().AddVariantSet("spheres") for variant_name in variants: shading_varset.AddVariant(variant_name) # Author opinions in for each variant. You could do this in the previous for loop too. for variant_name in variants: # You must select a variant to author opinion for it. shading_varset.SetVariantSelection(variant_name) with shading_varset.GetVariantEditContext(): # Specs authored within this context are authored just for the variant. for x in range(variants[variant_name]): UsdGeom.Sphere.Define(stage, xform_prim.GetPath().AppendPath(f"Sphere_{x}")) # Remember to set the variant you want selected once you're done authoring. shading_varset.SetVariantSelection(list(variants.keys())[0])
3,934
Python
36.122641
120
0.647687
mati-nvidia/omni-code-with-me/scripts/multi_render_ctx_mtl.py
# SPDX-License-Identifier: Apache-2.0 from pxr import Sdf, UsdShade, Gf import omni.usd stage = omni.usd.get_context().get_stage() mtl_path = Sdf.Path("/World/Looks/OmniSurface") mtl = UsdShade.Material.Define(stage, mtl_path) shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("Shader")) shader.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset) # MDL shaders should use "mdl" sourceType shader.SetSourceAsset("OmniSurface.mdl", "mdl") shader.SetSourceAssetSubIdentifier("OmniSurface", "mdl") shader.CreateInput("diffuse_reflection_color", Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(1.0, 0.0, 0.0)) # MDL materials should use "mdl" renderContext mtl.CreateSurfaceOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out") mtl.CreateDisplacementOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out") mtl.CreateVolumeOutput("mdl").ConnectToSource(shader.ConnectableAPI(), "out") prvw_shader = UsdShade.Shader.Define(stage, mtl_path.AppendPath("prvw_shader")) prvw_shader.CreateIdAttr("UsdPreviewSurface") prvw_shader.CreateInput("diffuseColor", Sdf.ValueTypeNames.Color3f).Set((0.0, 0.0, 1.0)) # Render Context specific to Storm # mtl.CreateSurfaceOutput("glslfx").ConnectToSource(prvw_shader.ConnectableAPI(), "out") # mtl.CreateDisplacementOutput("glslfx").ConnectToSource(prvw_shader.ConnectableAPI(), "out") # mtl.CreateVolumeOutput("glslfx").ConnectToSource(prvw_shader.ConnectableAPI(), "out") # Universal outputs mtl.CreateSurfaceOutput().ConnectToSource(prvw_shader.ConnectableAPI(), "out") mtl.CreateDisplacementOutput().ConnectToSource(prvw_shader.ConnectableAPI(), "out") mtl.CreateVolumeOutput().ConnectToSource(prvw_shader.ConnectableAPI(), "out")
1,690
Python
50.242423
103
0.787574
mati-nvidia/scene-api-sample/README.md
# Scene API Sample Extension ![Scene API Sample Preview](exts/maticodes.scene.sample/data/preview.png) ## Adding This Extension To add a this extension to your Omniverse app: 1. Go into: Extension Manager -> Gear Icon -> Extension Search Path 2. Add this as a search path: `git://github.com/matiascodesal/scene-api-sample.git?branch=main&dir=exts`
349
Markdown
42.749995
104
0.767908
mati-nvidia/scene-api-sample/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389
mati-nvidia/scene-api-sample/tools/packman/config.packman.xml
<config remotes="cloudfront"> <remote2 name="cloudfront"> <transport actions="download" protocol="https" packageLocation="d4i3qtqj3r0z5.cloudfront.net/${name}@${version}" /> </remote2> </config>
211
XML
34.333328
123
0.691943
mati-nvidia/scene-api-sample/tools/packman/bootstrap/install_package.py
# Copyright 2019 NVIDIA CORPORATION # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import zipfile import tempfile import sys import shutil __author__ = "hfannar" logging.basicConfig(level=logging.WARNING, format="%(message)s") logger = logging.getLogger("install_package") class TemporaryDirectory: def __init__(self): self.path = None def __enter__(self): self.path = tempfile.mkdtemp() return self.path def __exit__(self, type, value, traceback): # Remove temporary data created shutil.rmtree(self.path) def install_package(package_src_path, package_dst_path): with zipfile.ZipFile( package_src_path, allowZip64=True ) as zip_file, TemporaryDirectory() as temp_dir: zip_file.extractall(temp_dir) # Recursively copy (temp_dir will be automatically cleaned up on exit) try: # Recursive copy is needed because both package name and version folder could be missing in # target directory: shutil.copytree(temp_dir, package_dst_path) except OSError as exc: logger.warning( "Directory %s already present, packaged installation aborted" % package_dst_path ) else: logger.info("Package successfully installed to %s" % package_dst_path) install_package(sys.argv[1], sys.argv[2])
1,888
Python
31.568965
103
0.68697
mati-nvidia/scene-api-sample/exts/maticodes.scene.sample/maticodes/scene/sample/manipulators.py
from omni.ui import color as cl from omni.ui import scene as sc class SelectionMarker(sc.Manipulator): """A manipulator that adds a circle with crosshairs above the selected prim.""" def __init__(self, **kwargs): super().__init__(**kwargs) self._radius = 5 self._thickness = 2 self._half_line_length = 10 def on_build(self): if not self.model: return if not self.model.has_selection(): return with sc.Transform(transform=sc.Matrix44.get_translation_matrix(*self.model.position.value)): with sc.Transform(look_at=sc.Transform.LookAt.CAMERA): sc.Arc(self._radius, axis=2, color=cl.yellow) sc.Line([0, -self._half_line_length, 0], [0, self._half_line_length, 0], color=cl.yellow, thickness=self._thickness) sc.Line([-self._half_line_length, 0, 0], [self._half_line_length, 0, 0], color=cl.yellow, thickness=self._thickness) def on_model_updated(self, item): self.invalidate()
1,091
Python
35.399999
100
0.587534
mati-nvidia/scene-api-sample/exts/maticodes.scene.sample/maticodes/scene/sample/extension.py
import omni.ext import omni.kit.commands import omni.ui as ui from omni.ui import scene as sc import omni.usd from .models import CameraModel, SelectionModel from .manipulators import SelectionMarker # Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be # instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled # on_shutdown() is called. class SceneAPISampleExtension(omni.ext.IExt): # ext_id is current extension id. It can be used with extension manager to query additional information, like where # this extension is located on filesystem. def on_startup(self, ext_id): print("[maticodes.scene.sample] SceneAPISampleExtension startup") self._window = SampleWindow() def on_shutdown(self): print("[maticodes.scene.sample] SceneAPISampleExtension shutdown") self._window.destroy() self._window = None class SampleWindow(ui.Window): def __init__(self, title: str = None, **kwargs): if title is None: title = "Viewport" if "width" not in kwargs: kwargs["width"] = 1200 if "height" not in kwargs: kwargs["height"] = 480 kwargs["flags"] = ui.WINDOW_FLAGS_NO_SCROLL_WITH_MOUSE | ui.WINDOW_FLAGS_NO_SCROLLBAR super().__init__(title, **kwargs) self.frame.set_build_fn(self.__build_window) def __build_window(self): scene_view = sc.SceneView(model=CameraModel(), aspect_ratio_policy=sc.AspectRatioPolicy.PRESERVE_ASPECT_HORIZONTAL, scene_aspect_ratio=1280 / 720) with scene_view.scene: SelectionMarker(model=SelectionModel())
1,802
Python
36.562499
119
0.660932
mati-nvidia/scene-api-sample/exts/maticodes.scene.sample/maticodes/scene/sample/__init__.py
from .extension import *
25
Python
11.999994
24
0.76
mati-nvidia/scene-api-sample/exts/maticodes.scene.sample/maticodes/scene/sample/models.py
from typing import List import carb import omni.kit.viewport_legacy as vp from omni.ui import scene as sc import omni.usd from pxr import Gf, Sdf, Tf, Usd, UsdGeom class SelectionModel(sc.AbstractManipulatorModel): """A data model storing the current selected object. Tracks selection changes using omni.usd.StageEventType.SELECTION_CHANGED and position changes for the selected prim using Tf.Notice. """ class PositionItem(sc.AbstractManipulatorItem): def __init__(self): super().__init__() self.value = [0, 0, 0] def __init__(self): super().__init__() self.position = SelectionModel.PositionItem() self._offset = 5 self._current_path = "" usd_context = omni.usd.get_context() self._stage: Usd.Stage = usd_context.get_stage() if self._stage: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, self._stage) self._selection = usd_context.get_selection() self._events = usd_context.get_stage_event_stream() self._stage_event_sub = self._events.create_subscription_to_pop(self._on_stage_event, name="Selection Update") def _notice_changed(self, notice, stage): """Update model with the selected prim's latest position.""" for p in notice.GetChangedInfoOnlyPaths(): if self._current_path in str(p.GetPrimPath()): self.position.value = self._get_position() self._item_changed(self.position) def _on_stage_event(self, event): """Update model with the latest selected prim and its position. Only tracks the first selected prim. Not multi-selct. """ if event.type == int(omni.usd.StageEventType.SELECTION_CHANGED): self._current_path = "" if not self._stage: return prim_paths = self._selection.get_selected_prim_paths() if not prim_paths: self.position.value = [0, 0, 0] self._item_changed(self.position) return prim = self._stage.GetPrimAtPath(prim_paths[0]) if not prim.IsA(UsdGeom.Imageable): self._prim = None return self._prim = prim self._current_path = prim_paths[0] self.position.value = self._get_position() self._item_changed(self.position) def _get_position(self): if not self._current_path: return [0, 0, 0] prim = self._stage.GetPrimAtPath(self._current_path) box_cache = UsdGeom.BBoxCache(Usd.TimeCode.Default(), includedPurposes=[UsdGeom.Tokens.default_]) bound = box_cache.ComputeWorldBound(prim) range_ = bound.ComputeAlignedBox() bboxMin = range_.GetMin() bboxMax = range_.GetMax() position = [(bboxMin[0] + bboxMax[0]) * 0.5, bboxMax[1] + self._offset, (bboxMin[2] + bboxMax[2]) * 0.5] return position def has_selection(self): return self._current_path != "" class CameraModel(sc.AbstractManipulatorModel): def __init__(self): super().__init__() self._camera_prim = None self._camera_path = None self._stage_listener = None def on_usd_context_event(event: carb.events.IEvent): """Register/Re-register Tf.Notice callbacks on UsdContext changes.""" event_type = event.type if event_type == int(omni.usd.StageEventType.OPENED) or event_type == int(omni.usd.StageEventType.CLOSING): if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._camera_prim = None self._camera_path = None if event_type == int(omni.usd.StageEventType.OPENED): stage = omni.usd.get_context().get_stage() self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectChanged, self._notice_changed, stage) self._get_camera() usd_ctx = omni.usd.get_context() self._stage_event_sub = usd_ctx.get_stage_event_stream().create_subscription_to_pop(on_usd_context_event, name="CameraModel stage event") stage = usd_ctx.get_stage() if stage: self._stage_listener = Tf.Notice.Register(Usd.Notice.ObjectsChanged, self._notice_changed, stage) def destroy(self): self._stage_event_sub = None if self._stage_listener: self._stage_listener.Revoke() self._stage_listener = None self._camera_prim = None self._camera_path = None super().destroy() def get_as_floats(self, item): if item == self.get_item("projection"): return self._get_projection() if item == self.get_item("view"): return self._get_view() def _notice_changed(self, notice, stage): for p in notice.GetChangedInfoOnlyPaths(): if p.GetPrimPath() == self._camera_path: self._item_changed(None) @staticmethod def _flatten(transform): """Need to convert Gf.Matrix4d into a list for Scene API. This is the fastest way.""" return [ transform[0][0], transform[0][1], transform[0][2], transform[0][3], transform[1][0], transform[1][1], transform[1][2], transform[1][3], transform[2][0], transform[2][1], transform[2][2], transform[2][3], transform[3][0], transform[3][1], transform[3][2], transform[3][3], ] def _get_camera(self): if not self._camera_prim: viewport_window = vp.get_default_viewport_window() stage = omni.usd.get_context(viewport_window.get_usd_context_name()).get_stage() if stage: self._camera_path = Sdf.Path(viewport_window.get_active_camera()) self._camera_prim = stage.GetPrimAtPath(self._camera_path) if self._camera_prim: return UsdGeom.Camera(self._camera_prim).GetCamera().frustum def _get_view(self) -> List[float]: frustum = self._get_camera() if frustum: view = frustum.ComputeViewMatrix() else: view = Gf.Matrix4d(1.0) return self._flatten(view) def _get_projection(self) -> List[float]: frustum = self._get_camera() if frustum: projection = frustum.ComputeProjectionMatrix() else: projection = Gf.Matrix4d(1.0) return self._flatten(projection)
6,588
Python
37.086705
145
0.592289
mati-nvidia/scene-api-sample/exts/maticodes.scene.sample/config/extension.toml
[package] # Semantic Versionning is used: https://semver.org/ version = "1.1.0" # The title and description fields are primarily for displaying extension info in UI title = "Scene API Sample" description="A sample of how to mark an selected object using the omni.ui.scene API." authors=["Matias Codesal <[email protected]>"] preview_image = "data/preview.png" # Path (relative to the root) or content of readme markdown file for UI. readme = "docs/README.md" # URL of the extension source repository. repository = "https://github.com/mati-nvidia/scene-api-sample" # One of categories for UI. category = "Example" # Keywords for the extension keywords = ["kit", "example"] # Use omni.ui to build simple UI [dependencies] "omni.kit.uiapp" = {} "omni.ui.scene" = {} "omni.usd" = {} # Main python module this extension provides, it will be publicly available as "import omni.hello.world". [[python.module]] name = "maticodes.scene.sample"
945
TOML
28.562499
105
0.731217
mati-nvidia/omni-bookshelf-generator/README.md
# Bookshelf Generator This NVIDIA Omniverse Kit Extension procedurally creates bookshelves with variable height and width and it fills the shelves with books. It is part of a series of live coding sessions that I worked on. This is a great project to study if you are interested in learning more about USD, PointInstancers and Kit Extensions. Watch the recordings of the [full Bookshelf Generator live coding series](https://www.youtube.com/playlist?list=PL3jK4xNnlCVcDS_DgtTSAljdC2KUliU1F). ![Bookshelf Generator](exts/maticodes.generator.bookshelf/data/clip.gif) ## Usage See the extension's README for [usage instructions](exts/maticodes.generator.bookshelf/docs/README.md). ## App Link Setup If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included. Run: ``` > link_app.bat ``` If successful you should see `app` folder link in the root of this repo. If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app: ``` > link_app.bat --app create ``` You can also just pass a path to create link to: ``` > link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4" ``` ## Attribution Icon made by [Freepik](https://www.flaticon.com/authors/freepik) from [www.flaticon.com](www.flaticon.com) ## Contributing The source code for this repository is provided as-is and we are not accepting outside contributions.
1,589
Markdown
39.76923
469
0.773442
mati-nvidia/omni-bookshelf-generator/tools/scripts/link_app.py
import os import argparse import sys import json import packmanapi import urllib3 def find_omniverse_apps(): http = urllib3.PoolManager() try: r = http.request("GET", "http://127.0.0.1:33480/components") except Exception as e: print(f"Failed retrieving apps from an Omniverse Launcher, maybe it is not installed?\nError: {e}") sys.exit(1) apps = {} for x in json.loads(r.data.decode("utf-8")): latest = x.get("installedVersions", {}).get("latest", "") if latest: for s in x.get("settings", []): if s.get("version", "") == latest: root = s.get("launch", {}).get("root", "") apps[x["slug"]] = (x["name"], root) break return apps def create_link(src, dst): print(f"Creating a link '{src}' -> '{dst}'") packmanapi.link(src, dst) APP_PRIORITIES = ["code", "create", "view"] if __name__ == "__main__": parser = argparse.ArgumentParser(description="Create folder link to Kit App installed from Omniverse Launcher") parser.add_argument( "--path", help="Path to Kit App installed from Omniverse Launcher, e.g.: 'C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4'", required=False, ) parser.add_argument( "--app", help="Name of Kit App installed from Omniverse Launcher, e.g.: 'code', 'create'", required=False ) args = parser.parse_args() path = args.path if not path: print("Path is not specified, looking for Omniverse Apps...") apps = find_omniverse_apps() if len(apps) == 0: print( "Can't find any Omniverse Apps. Use Omniverse Launcher to install one. 'Code' is the recommended app for developers." ) sys.exit(0) print("\nFound following Omniverse Apps:") for i, slug in enumerate(apps): name, root = apps[slug] print(f"{i}: {name} ({slug}) at: '{root}'") if args.app: selected_app = args.app.lower() if selected_app not in apps: choices = ", ".join(apps.keys()) print(f"Passed app: '{selected_app}' is not found. Specify one of the following found Apps: {choices}") sys.exit(0) else: selected_app = next((x for x in APP_PRIORITIES if x in apps), None) if not selected_app: selected_app = next(iter(apps)) print(f"\nSelected app: {selected_app}") _, path = apps[selected_app] if not os.path.exists(path): print(f"Provided path doesn't exist: {path}") else: SCRIPT_ROOT = os.path.dirname(os.path.realpath(__file__)) create_link(f"{SCRIPT_ROOT}/../../app", path) print("Success!")
2,813
Python
32.5
133
0.562389