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
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIcable/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/franka_follow_target.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample import numpy as np from omni.isaac.core.prims.geometry_prim import GeometryPrim # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController from omni.isaac.franka import Franka from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root import carb import omni import rclpy import asyncio from .ros2_twist_sub import QuestROS2Sub def addObjectsGeom(scene, name, scale, ini_pos, collision=None, mass=None, orientation=None): scene.add(GeometryPrim(prim_path=f"/World/{name}", name=f"{name}_ref_geom", collision=True)) geom = scene.get_object(f"{name}_ref_geom") if orientation is None: # Usually - (x, y, z, w) # But in Isaac Sim - (w, x, y, z) orientation = np.array([1.0, 0.0, 0.0, 0.0]) geom.set_local_scale(scale) geom.set_world_pose(position=ini_pos) geom.set_default_state(position=ini_pos, orientation=orientation) geom.set_collision_enabled(False) if collision is not None: geom.set_collision_enabled(True) geom.set_collision_approximation(collision) if mass is not None: massAPI = UsdPhysics.MassAPI.Apply(geom.prim.GetPrim()) massAPI.CreateMassAttr().Set(mass) return geom class FrankaFollowTarget(BaseSample): def __init__(self) -> None: super().__init__() self._isaac_assets_path = get_assets_root_path() self.CUBE_URL = self._isaac_assets_path + "/Isaac/Props/Blocks/nvidia_cube.usd" self._quest_ros2_sub_node = None self._controller = None self._articulation_controller = None return def __del__(self): if self._quest_ros2_sub_node is not None: self._quest_ros2_sub_node.destroy_node() rclpy.shutdown() return async def ros_loop(self): while rclpy.ok(): rclpy.spin_once(self._quest_ros2_sub_node, timeout_sec=0) await asyncio.sleep(1e-4) def add_light(self): sphereLight1 = UsdLux.SphereLight.Define(self._stage, Sdf.Path("/World/SphereLight")) sphereLight1.CreateIntensityAttr(10000) sphereLight1.CreateRadiusAttr(0.1) sphereLight1.AddTranslateOp().Set(Gf.Vec3f(1.0, 0.0, 1.0)) def add_cube(self): add_reference_to_stage(usd_path=self.CUBE_URL, prim_path=f"/World/NVIDIA_Cube") self._cube_geom = addObjectsGeom( self._world.scene, "NVIDIA_Cube", scale=np.array([1.0, 1.0, 1.0]), ini_pos=np.array([0.5, 0.3, 0.1]), collision="sdf", mass=0.1, orientation=None ) def add_franka(self): self._franka = self._world.scene.add( Franka( prim_path="/World/Fancy_Franka", name="fancy_franka" ) ) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self._world.scene.add_default_ground_plane() self.add_franka() self.add_light() self.add_cube() return async def setup_post_load(self): self._world = self.get_world() self._my_franka = self._world.scene.get_object("fancy_franka") self._my_gripper = self._my_franka.gripper # RMPFlow controller self._controller = RMPFlowController( name="target_follower_controller", robot_articulation=self._my_franka ) # ROS 2 init rclpy.init(args=None) self._quest_ros2_sub_node = QuestROS2Sub() self._articulation_controller = self._my_franka.get_articulation_controller() self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) await self.ros_loop() return def physics_callback(self, step_size): ee_position, ee_orientation = self._quest_ros2_sub_node.get_pose( z_offset=0.30, # z -180 > 0, 0, -1, 0 q_offset=np.array([0.0, 0.0, -1.0, 0.0]) ) gripper_command = self._quest_ros2_sub_node.get_right_btn() if np.array_equal( ee_position, np.array([0.0, 0.0, 0.0]) ): ee_position = np.array([0.4, 0, 0.5]) if gripper_command: self._my_gripper.close() else: self._my_gripper.open() # RMPFlow controller actions = self._controller.forward( target_end_effector_position=ee_position, target_end_effector_orientation=ee_orientation, # w x y z => x y z w # 0 0 1 0 => 0 1 0 0 # 0 0 1 0 => 0 1 0 0 # target_end_effector_orientation=np.array([0, 0, 1, 0]), ) self._articulation_controller.apply_action(actions) return async def setup_pre_reset(self): world = self.get_world() if world.physics_callback_exists("sim_step"): world.remove_physics_callback("sim_step") self._controller.reset() return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def world_cleanup(self): self._world.pause() self._controller = None return
5,982
Python
32.424581
116
0.622033
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/ros2_twist_sub.py
import numpy as np # ROS2 imports import rclpy from rclpy.node import Node from std_msgs.msg import Float32 from geometry_msgs.msg import Twist, PoseStamped def quaternion_multiply(q1, q2): w1, x1, y1, z1 = q1 w2, x2, y2, z2 = q2 w = w1*w2 - x1*x2 - y1*y2 - z1*z2 x = w1*x2 + x1*w2 + y1*z2 - z1*y2 y = w1*y2 - x1*z2 + y1*w2 + z1*x2 z = w1*z2 + x1*y2 - y1*x2 + z1*w2 return np.array([w, x, y, z]) class QuestROS2Sub(Node): def __init__(self): super().__init__('questros2_subscriber') queue_size = 10 # Queue Size self._rh_twist_sub = self.create_subscription( Twist, 'q2r_right_hand_twist', self.twist_sub_callback, queue_size ) self._rh_pose_sub = self.create_subscription( PoseStamped, 'q2r_right_hand_pose', self.pose_sub_callback, queue_size ) self._rh_index_btn_sub = self.create_subscription( Float32, 'right_press_index', self.btn_sub_callback, queue_size ) self._cur_twist = Twist() self._cur_pose = PoseStamped() self._btn_press = False def twist_sub_callback(self, msg): # self.get_logger().info(f""" # x : {msg.linear.x:.3f} / y : {msg.linear.y:.3f} / z : {msg.linear.z:.3f} # r : {msg.angular.x:.3f} / p : {msg.angular.y:.3f} / y : {msg.angular.z:.3f} # """) self._cur_twist = msg def pose_sub_callback(self, msg): # self.get_logger().info(f""" # x : {msg.pose.position.x:.3f} / y : {msg.pose.position.y:.3f} / z : {msg.pose.position.z:.3f} # x : {msg.pose.orientation.x:.3f} / y : {msg.pose.orientation.y:.3f} / z : {msg.pose.orientation.z:.3f} / w : {msg.pose.orientation.w:.3f} # """) self._cur_pose = msg def btn_sub_callback(self, msg): if msg.data == 1.0: self._btn_press = True else: self._btn_press = False # print(f"msg.data: {msg.data} / self._btn_press: {self._btn_press}") def get_twist(self): # return self._cur_twist lin_x, lin_y, lin_z = self._cur_twist.linear.x, self._cur_twist.linear.y, self._cur_twist.linear.z ang_x, ang_y, ang_z = self._cur_twist.angular.x, self._cur_twist.angular.y, self._cur_twist.angular.z lin_x *= 5 lin_y *= 2 lin_z *= 2 return [ lin_x, lin_y, lin_z, 0.0, 0.0, 0.0] def get_pose(self, z_offset, q_offset): position = np.array([ self._cur_pose.pose.position.x, self._cur_pose.pose.position.y, self._cur_pose.pose.position.z + z_offset ]) orientation = np.array([ self._cur_pose.pose.orientation.x, self._cur_pose.pose.orientation.y, self._cur_pose.pose.orientation.z, self._cur_pose.pose.orientation.w ]) orientation = quaternion_multiply(q_offset, orientation) isaac_orientation = np.array([ orientation[3], orientation[0], orientation[1], orientation[2], ]) return position, isaac_orientation def get_right_btn(self): return self._btn_press def main(args=None): """Do enter into this main function first.""" rclpy.init(args=args) quest_ros2_sub = QuestROS2Sub() rclpy.spin(quest_ros2_sub) quest_ros2_sub.destroy_node() rclpy.shutdown() if __name__ == '__main__': """main function""" main()
3,502
Python
28.191666
151
0.55197
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_follow_target import FrankaFollowTarget """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ROS2 Examples", name="FrankaFollowTarget", title="FrankaFollowTarget", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaFollowTarget(), ) return def on_shutdown(self): print(f"Shutting down {self._sample.__class__.__name__}") self._extra_frames = [] if self._sample._world is not None: self._sample._world_cleanup() if self._menu_items is not None: self._sample_window_cleanup() if self._buttons is not None: self._buttons["Load World"].enabled = True self._enable_all_buttons(False) self.shutdown_cleanup() return
2,565
Python
41.065573
135
0.709162
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaFollowTarget/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .hello_multi_robot import HelloMultiRobot """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="", name="HelloMultiRobot", title="HelloMultiRobot", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=HelloMultiRobot(), ) return
2,058
Python
41.895832
135
0.741011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/hello_multi_robot.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.franka.tasks import PickPlace from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.nucleus import get_assets_root_path from omni.isaac.wheeled_robots.controllers import WheelBasePoseController from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.wheeled_robots.controllers.differential_controller import DifferentialController from omni.isaac.core.tasks import BaseTask from omni.isaac.core.utils.types import ArticulationAction import numpy as np class RobotsPlaying(BaseTask): def __init__( self, name ): super().__init__(name=name, offset=None) self._jetbot_goal_position = np.array([1.3, 0.3, 0]) self._task_event = 0 self._pick_place_task = PickPlace(cube_initial_position=np.array([0.1, 0.3, 0.05]), target_position=np.array([0.7, -0.3, 0.0515 / 2.0])) return def set_up_scene(self, scene): super().set_up_scene(scene) self._pick_place_task.set_up_scene(scene) assets_root_path = get_assets_root_path() jetbot_asset_path = assets_root_path + "/Isaac/Robots/Jetbot/jetbot.usd" self._jetbot = scene.add( WheeledRobot( prim_path="/World/Fancy_Jetbot", name="fancy_jetbot", wheel_dof_names=["left_wheel_joint", "right_wheel_joint"], create_robot=True, usd_path=jetbot_asset_path, position=np.array([0, 0.3, 0]), ) ) pick_place_params = self._pick_place_task.get_params() self._franka = scene.get_object(pick_place_params["robot_name"]["value"]) self._franka.set_world_pose(position=np.array([1.0, 0, 0])) self._franka.set_default_state(position=np.array([1.0, 0, 0])) return def get_observations(self): current_jetbot_position, current_jetbot_orientation = self._jetbot.get_world_pose() observations= { "task_event": self._task_event, self._jetbot.name: { "position": current_jetbot_position, "orientation": current_jetbot_orientation, "goal_position": self._jetbot_goal_position } } # add the subtask's observations as well observations.update(self._pick_place_task.get_observations()) return observations def get_params(self): pick_place_params = self._pick_place_task.get_params() params_representation = pick_place_params params_representation["jetbot_name"] = {"value": self._jetbot.name, "modifiable": False} params_representation["franka_name"] = pick_place_params["robot_name"] return params_representation def pre_step(self, control_index, simulation_time): if self._task_event == 0: current_jetbot_position, _ = self._jetbot.get_world_pose() if np.mean(np.abs(current_jetbot_position[:2] - self._jetbot_goal_position[:2])) < 0.04: self._task_event += 1 self._cube_arrive_step_index = control_index elif self._task_event == 1: if control_index - self._cube_arrive_step_index == 200: self._task_event += 1 return def post_reset(self): self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) self._task_event = 0 return class HelloMultiRobot(BaseSample): def __init__(self) -> None: super().__init__() return def setup_scene(self): world = self.get_world() world.add_task(RobotsPlaying(name="awesome_task")) return async def setup_post_load(self): self._world = self.get_world() task_params = self._world.get_task("awesome_task").get_params() # We need franka later to apply to it actions self._franka = self._world.scene.get_object(task_params["franka_name"]["value"]) self._jetbot = self._world.scene.get_object(task_params["jetbot_name"]["value"]) # We need the cube later on for the pick place controller self._cube_name = task_params["cube_name"]["value"] # Add Franka Controller self._franka_controller = PickPlaceController(name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka) self._jetbot_controller = WheelBasePoseController(name="cool_controller", open_loop_wheel_controller= DifferentialController(name="simple_control", wheel_radius=0.03, wheel_base=0.1125)) self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) await self._world.play_async() return async def setup_post_reset(self): self._franka_controller.reset() self._jetbot_controller.reset() await self._world.play_async() return def physics_step(self, step_size): current_observations = self._world.get_observations() if current_observations["task_event"] == 0: self._jetbot.apply_wheel_actions( self._jetbot_controller.forward( start_position=current_observations[self._jetbot.name]["position"], start_orientation=current_observations[self._jetbot.name]["orientation"], goal_position=current_observations[self._jetbot.name]["goal_position"])) elif current_observations["task_event"] == 1: self._jetbot.apply_wheel_actions(ArticulationAction(joint_velocities=[-8, -8])) elif current_observations["task_event"] == 2: self._jetbot.apply_wheel_actions(ArticulationAction(joint_velocities=[0.0, 0.0])) # Pick up the block actions = self._franka_controller.forward( picking_position=current_observations[self._cube_name]["position"], placing_position=current_observations[self._cube_name]["target_position"], current_joint_positions=current_observations[self._franka.name]["joint_positions"]) self._franka.apply_action(actions) # Pause once the controller is done if self._franka_controller.is_done(): self._world.pause() return
7,063
Python
46.093333
118
0.612771
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloMultiRobot/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/ur10_basic.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.tasks import BaseTask from omni.isaac.franka import Franka from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.prims.geometry_prim import GeometryPrim from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.franka import Franka from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.rotations import euler_angles_to_quat from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from omni.isaac.core import SimulationContext from omni.physx.scripts import utils from pxr import PhysxSchema import numpy as np import carb from omni.isaac.universal_robots import UR10 from omni.isaac.universal_robots.controllers.rmpflow_controller import RMPFlowController class UR10Basic(BaseSample): def __init__(self) -> None: super().__init__() # Nucleus Path Configuration carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) return def setup_scene(self): self._world = self.get_world() self._world.scene.add_default_ground_plane() # Add UR10 robot self._ur10 = self._world.scene.add( UR10( prim_path="/World/UR10", name="UR10", attach_gripper=False, ) ) self.simulation_context = SimulationContext() return async def setup_post_load(self): self._my_ur10 = self._world.scene.get_object("UR10") # RMPFlow controller self._controller = RMPFlowController( name="target_follower_controller", robot_articulation=self._my_ur10 ) self._articulation_controller = self._my_ur10.get_articulation_controller() self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) return def physics_step(self, step_size): # RMPFlow controller actions = self._controller.forward( target_end_effector_position=np.array([0.4, 0, 0.5]), # target_end_effector_orientation=ee_orientation, # w x y z => x y z w # 0 0 1 0 => 0 1 0 0 # 0 0 1 0 => 0 1 0 0 target_end_effector_orientation=np.array([1, 0, 0, 0]), ) self._articulation_controller.apply_action(actions) return async def setup_pre_reset(self): self._save_count = 0 self._event = 0 return async def setup_post_reset(self): await self._world.play_async() return def world_cleanup(self): return
3,429
Python
31.666666
101
0.673666
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .ur10_basic import UR10Basic """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIReal", name="UR10Basic", title="UR10Basic", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=UR10Basic(), ) return
2,035
Python
41.416666
135
0.738575
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ETRIUR10/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .limo_ackermann import LimoAckermann """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WheeledRobots", name="LimoAckermann_ROS2_Twist", title="LimoAckermann_ROS2_Twist", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=LimoAckermann(), ) return
2,082
Python
42.395832
135
0.742555
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/limo_ackermann.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController import omni.graph.core as og import numpy as np import usdrt.Sdf import carb class LimoAckermann(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_ackermann.usd" self._domain_id = 30 self._maxWheelRotation = 1e6 self._maxWheelVelocity = 1e6 self._trackWidth = 0.13 self._turningWheelRadius = 0.045 self._wheelBase = 0.2 self._targetPrim = "/World/Limo/base_link" self._robotPath = "/World/Limo/base_link" return def og_setup(self): try: og.Controller.edit( {"graph_path": "/ROS2Ackermann", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("subscribeTwist", "omni.isaac.ros2_bridge.ROS2SubscribeTwist"), ("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"), ("angVelBreak", "omni.graph.nodes.BreakVector3"), ("linVelBreak", "omni.graph.nodes.BreakVector3"), ("wheelbase", "omni.graph.nodes.ConstantDouble"), ("multiply", "omni.graph.nodes.Multiply"), ("atan2", "omni.graph.nodes.ATan2"), ("toRad", "omni.graph.nodes.ToRad"), ("ackermannCtrl", "omni.isaac.wheeled_robots.AckermannSteering"), ("wheelJointNames", "omni.graph.nodes.ConstructArray"), ("wheelRotationVel", "omni.graph.nodes.ConstructArray"), ("hingeJointNames", "omni.graph.nodes.ConstructArray"), ("hingePosVel", "omni.graph.nodes.ConstructArray"), ("articulationRotation", "omni.isaac.core_nodes.IsaacArticulationController"), ("articulationPosition", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("subscribeTwist.inputs:topicName", "cmd_vel"), ("wheelbase.inputs:value", self._wheelBase), ("ackermannCtrl.inputs:maxWheelRotation", self._maxWheelRotation), ("ackermannCtrl.inputs:maxWheelVelocity", self._maxWheelVelocity), ("ackermannCtrl.inputs:trackWidth", self._trackWidth), ("ackermannCtrl.inputs:turningWheelRadius", self._turningWheelRadius), ("ackermannCtrl.inputs:useAcceleration", False), ("wheelJointNames.inputs:arraySize", 4), ("wheelJointNames.inputs:arrayType", "token[]"), ("wheelJointNames.inputs:input0", "rear_left_wheel"), ("wheelJointNames.inputs:input1", "rear_right_wheel"), ("wheelJointNames.inputs:input2", "front_left_wheel"), ("wheelJointNames.inputs:input3", "front_right_wheel"), ("hingeJointNames.inputs:arraySize", 2), ("hingeJointNames.inputs:arrayType", "token[]"), ("hingeJointNames.inputs:input0", "left_steering_hinge_wheel"), ("hingeJointNames.inputs:input1", "right_steering_hinge_wheel"), ("wheelRotationVel.inputs:arraySize", 4), ("wheelRotationVel.inputs:arrayType", "double[]"), ("hingePosVel.inputs:arraySize", 2), ("hingePosVel.inputs:arrayType", "double[]"), ("articulationRotation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationRotation.inputs:robotPath", self._targetPrim), ("articulationRotation.inputs:usePath", False), ("articulationPosition.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationPosition.inputs:robotPath", self._targetPrim), ("articulationPosition.inputs:usePath", False), ], og.Controller.Keys.CREATE_ATTRIBUTES: [ ("wheelJointNames.inputs:input1", "token"), ("wheelJointNames.inputs:input2", "token"), ("wheelJointNames.inputs:input3", "token"), ("hingeJointNames.inputs:input1", "token"), ("wheelRotationVel.inputs:input1", "double"), ("wheelRotationVel.inputs:input2", "double"), ("wheelRotationVel.inputs:input3", "double"), ("hingePosVel.inputs:input1", "double"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "subscribeTwist.inputs:execIn"), ("context.outputs:context", "subscribeTwist.inputs:context"), ("subscribeTwist.outputs:linearVelocity", "scaleToFromStage.inputs:value"), ("scaleToFromStage.outputs:result", "linVelBreak.inputs:tuple"), ("subscribeTwist.outputs:angularVelocity", "angVelBreak.inputs:tuple"), ("subscribeTwist.outputs:execOut", "ackermannCtrl.inputs:execIn"), ("angVelBreak.outputs:z", "multiply.inputs:a"), ("linVelBreak.outputs:x", "ackermannCtrl.inputs:speed"), ("wheelbase.inputs:value", "multiply.inputs:b"), ("wheelbase.inputs:value", "ackermannCtrl.inputs:wheelBase"), ("multiply.outputs:product", "atan2.inputs:a"), ("linVelBreak.outputs:x", "atan2.inputs:b"), ("atan2.outputs:result", "toRad.inputs:degrees"), ("toRad.outputs:radians", "ackermannCtrl.inputs:steeringAngle"), ("ackermannCtrl.outputs:leftWheelAngle", "hingePosVel.inputs:input0"), ("ackermannCtrl.outputs:rightWheelAngle", "hingePosVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input0"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input2"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input3"), ("ackermannCtrl.outputs:execOut", "articulationRotation.inputs:execIn"), ("wheelJointNames.outputs:array", "articulationRotation.inputs:jointNames"), ("wheelRotationVel.outputs:array", "articulationRotation.inputs:velocityCommand"), ("ackermannCtrl.outputs:execOut", "articulationPosition.inputs:execIn"), ("hingeJointNames.outputs:array", "articulationPosition.inputs:jointNames"), ("hingePosVel.outputs:array", "articulationPosition.inputs:positionCommand"), ], }, ) og.Controller.edit( {"graph_path": "/ROS2Odom", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("readSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"), ("computeOdom", "omni.isaac.core_nodes.IsaacComputeOdometry"), ("publishOdom", "omni.isaac.ros2_bridge.ROS2PublishOdometry"), ("publishRawTF", "omni.isaac.ros2_bridge.ROS2PublishRawTransformTree"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("computeOdom.inputs:chassisPrim", [usdrt.Sdf.Path(self._targetPrim)]), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "computeOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishOdom.inputs:execIn"), ("onPlaybackTick.outputs:tick", "publishRawTF.inputs:execIn"), ("readSimTime.outputs:simulationTime", "publishOdom.inputs:timeStamp"), ("readSimTime.outputs:simulationTime", "publishRawTF.inputs:timeStamp"), ("context.outputs:context", "publishOdom.inputs:context"), ("context.outputs:context", "publishRawTF.inputs:context"), ("computeOdom.outputs:angularVelocity", "publishOdom.inputs:angularVelocity"), ("computeOdom.outputs:linearVelocity", "publishOdom.inputs:linearVelocity"), ("computeOdom.outputs:orientation", "publishOdom.inputs:orientation"), ("computeOdom.outputs:position", "publishOdom.inputs:position"), ("computeOdom.outputs:orientation", "publishRawTF.inputs:rotation"), ("computeOdom.outputs:position", "publishRawTF.inputs:translation"), ], }, ) except Exception as e: print(e) def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo") self._save_count = 0 self.og_setup() return async def setup_post_load(self): self._world = self.get_world() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._save_count += 1 return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): self._summit_controller.reset() await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
12,071
Python
56.21327
106
0.567724
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannTwistROS2/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .hello_camera import HelloCamera """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="", name="HelloCamera", title="HelloCamera", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=HelloCamera(), ) return
2,037
Python
41.458332
135
0.738832
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/hello_camera.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from datetime import datetime import numpy as np # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from omni.isaac.core.objects import DynamicCuboid from omni.isaac.sensor import Camera from omni.isaac.core import World import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from PIL import Image import carb import h5py import omni import cv2 class HelloCamera(BaseSample): def __init__(self) -> None: super().__init__() self._save_count = 0 self._f = None self._time_list = [] self._img_list = [] return def setup_camera(self): self._camera = Camera( prim_path="/World/camera", position=np.array([0.0, 0.0, 25.0]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats(np.array([0, 90, 0]), degrees=True), ) self._camera.initialize() self._camera.add_motion_vectors_to_frame() def setup_cube(self, prim_path, name, position, scale, color): self._fancy_cube = self._world.scene.add( DynamicCuboid( prim_path=prim_path, name=name, position=position, scale=scale, color=color, )) def setup_dataset(self): now = datetime.now() # current date and time date_time_str = now.strftime("%m_%d_%Y_%H_%M_%S") file_name = f'hello_cam_{date_time_str}.hdf5' print(file_name) self._f = h5py.File(file_name,'w') self._group = self._f.create_group("isaac_save_data") def setup_scene(self): print("setup_scene") world = self.get_world() world.scene.add_default_ground_plane() self.setup_camera() self.setup_cube( prim_path="/World/random_cube", name="fancy_cube", position=np.array([0, 0, 1.0]), scale=np.array([0.5015, 0.5015, 0.5015]), color=np.array([0, 0, 1.0]), ) self.setup_dataset() self.simulation_context = SimulationContext() async def setup_post_load(self): print("setup_post_load") world = self.get_world() self._camera.add_motion_vectors_to_frame() self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) #callback names have to be unique return def physics_callback(self, step_size): self._camera.get_current_frame() if self._save_count % 100 == 0: current_time = self.simulation_context.current_time self._time_list.append(current_time) self._img_list.append(self._camera.get_rgba()[:, :, :3]) print("Data Collected") self._save_count += 1 if self._save_count == 500: self.world_cleanup() async def setup_pre_reset(self): if self._f is not None: self._f.close() self._f = None elif self._f is None: print("Create new file for new data collection...") self.setup_dataset() self._save_count = 0 return # async def setup_post_reset(self): # return def world_cleanup(self): if self._f is not None: self._group.create_dataset(f"sim_time", data=self._time_list, compression='gzip', compression_opts=9) self._group.create_dataset(f"image", data=self._img_list, compression='gzip', compression_opts=9) self._f.close() print("Data saved") elif self._f is None: print("Invalid Operation Data not saved") self._f = None self._save_count = 0 world = self.get_world() world.pause() return
4,415
Python
27.490322
121
0.593431
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/HelloCamera/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .gripper_control import GripperControl """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="AddingNewManip2", name="GripperControl", title="GripperControl", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=GripperControl(), ) return
2,067
Python
42.083332
135
0.742622
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/gripper_control.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.manipulators.grippers.surface_gripper import SurfaceGripper from omni.isaac.manipulators import SingleManipulator import numpy as np import carb class GripperControl(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._robot_path = self._server_root + "/Projects/RBROS2/mirobot_ros2/mirobot_description/urdf/mirobot_urdf_2/mirobot_urdf_2.usd" self._joints_default_positions = np.zeros(6) # simulation step counter self._sim_step = 0 return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() # add robot to the scene add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/mirobot") self._gripper = SurfaceGripper( end_effector_prim_path="/World/mirobot/Link6", translate=0.1611, direction="x" ) #define the manipulator self._my_mirobot = self._world.scene.add( SingleManipulator( prim_path="/World/mirobot", name="mirobot", end_effector_prim_name="Link6", gripper=self._gripper, )) # default joint states self._my_mirobot.set_joints_default_state( positions=self._joints_default_positions ) return async def setup_post_load(self): self._world = self.get_world() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._sim_step += 1 return
2,611
Python
33.826666
137
0.661815
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/MirobotGripperControl/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .foot_env import FootEnv """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="", name="FootEnv", title="FootEnv", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FootEnv(), ) return
2,017
Python
41.041666
135
0.736242
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FootEnv/foot_env.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample import numpy as np # Note: checkout the required tutorials at https://docs.omniverse.nvidia.com/app_isaacsim/app_isaacsim/overview.html from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.objects import DynamicCuboid from omni.isaac.sensor import Camera from omni.isaac.core import World import omni.graph.core as og import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core import SimulationContext from omni.physx.scripts import deformableUtils, physicsUtils from pxr import UsdGeom, Gf, UsdPhysics, Sdf, Gf, Tf, UsdLux from PIL import Image import carb import h5py import omni import cv2 class FootEnv(BaseSample): def __init__(self) -> None: super().__init__() self._save_count = 0 self._rotate_count = 0 carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._time_list = [] self._img_list = [] return def og_setup(self): camprim1 = "/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_ir_left/camera_left/Stream_depth" camprim2 = "/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_rgb/camera_rgb/Stream_rgb" try: og.Controller.edit( {"graph_path": "/ActionGraph", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("OnPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("RenderProduct1", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RenderProduct2", "omni.isaac.core_nodes.IsaacCreateRenderProduct"), ("RGBPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("DepthPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ("CameraInfoPublish", "omni.isaac.ros2_bridge.ROS2CameraHelper"), ], og.Controller.Keys.SET_VALUES: [ ("RenderProduct1.inputs:cameraPrim", camprim1), ("RenderProduct2.inputs:cameraPrim", camprim2), ("RGBPublish.inputs:topicName", "rgb"), ("RGBPublish.inputs:type", "rgb"), ("RGBPublish.inputs:resetSimulationTimeOnStop", True), ("DepthPublish.inputs:topicName", "depth"), ("DepthPublish.inputs:type", "depth"), ("DepthPublish.inputs:resetSimulationTimeOnStop", True), ("CameraInfoPublish.inputs:topicName", "depth_camera_info"), ("CameraInfoPublish.inputs:type", "camera_info"), ("CameraInfoPublish.inputs:resetSimulationTimeOnStop", True), ], og.Controller.Keys.CONNECT: [ ("OnPlaybackTick.outputs:tick", "RenderProduct1.inputs:execIn"), ("OnPlaybackTick.outputs:tick", "RenderProduct2.inputs:execIn"), ("RenderProduct1.outputs:execOut", "DepthPublish.inputs:execIn"), ("RenderProduct1.outputs:execOut", "CameraInfoPublish.inputs:execIn"), ("RenderProduct2.outputs:execOut", "RGBPublish.inputs:execIn"), ("RenderProduct1.outputs:renderProductPath", "DepthPublish.inputs:renderProductPath"), ("RenderProduct1.outputs:renderProductPath", "CameraInfoPublish.inputs:renderProductPath"), ("RenderProduct2.outputs:renderProductPath", "RGBPublish.inputs:renderProductPath"), ], }, ) except Exception as e: print(e) def camera_setup(self): gemini_usd_path = self._server_root + "/NVIDIA/Assets/Isaac/2023.1.1/Isaac/Sensors/Orbbec/Gemini 2/orbbec_gemini2_V1.0.usd" # TODO : check foot availability add_reference_to_stage( usd_path=gemini_usd_path, prim_path=f"/World/Orbbec_Gemini2", ) self._gemini_mesh = UsdGeom.Mesh.Get(self._stage, "/World/Orbbec_Gemini2") physicsUtils.set_or_add_translate_op(self._gemini_mesh, translate=Gf.Vec3f(0.05, 0.5, 0.5)) # x: -3.1415927, y: 0, z: -1.5707963 rot = rot_utils.euler_angles_to_quats(np.array([ 90, 0, 0 ]), degrees=True) physicsUtils.set_or_add_orient_op(self._gemini_mesh, orient=Gf.Quatf(*rot)) # physicsUtils.set_or_add_scale_op(gemini_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) ldm_light = self._stage.GetPrimAtPath("/World/Orbbec_Gemini2/Orbbec_Gemini2/camera_ldm/camera_ldm/RectLight") ldm_light_intensity = ldm_light.GetAttribute("intensity") ldm_light_intensity.Set(0) def add_female_foot(self): foot_usd_path = self._server_root + "/Projects/DInsight/Female_Foot.usd" add_reference_to_stage( usd_path=foot_usd_path, prim_path=f"/World/foot", ) foot_mesh = UsdGeom.Mesh.Get(self._stage, "/World/foot") physicsUtils.set_or_add_translate_op(foot_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.6)) physicsUtils.set_or_add_orient_op(foot_mesh, orient=Gf.Quatf(-0.5, -0.5, -0.5, -0.5)) physicsUtils.set_or_add_scale_op(foot_mesh, scale=Gf.Vec3f(0.001, 0.001, 0.001)) def add_male_foot(self): foot_usd_path = self._server_root + "/Projects/DInsight/foot1.usd" add_reference_to_stage( usd_path=foot_usd_path, prim_path=f"/World/foot", ) foot_mesh = UsdGeom.Mesh.Get(self._stage, "/World/foot") physicsUtils.set_or_add_translate_op(foot_mesh, translate=Gf.Vec3f(0.0, 0.0, 0.45)) physicsUtils.set_or_add_orient_op(foot_mesh, orient=Gf.Quatf(-0.5, -0.5, -0.5, -0.5)) physicsUtils.set_or_add_scale_op(foot_mesh, scale=Gf.Vec3f(0.25, 0.25, 0.25)) def add_soft_foot(self): foot_usd_path = self._server_root + "/Projects/DInsight/foot2.usd" add_reference_to_stage( usd_path=foot_usd_path, prim_path=f"/World/foot", ) foot_mesh = UsdGeom.Mesh.Get(self._stage, "/World/foot") physicsUtils.set_or_add_translate_op(foot_mesh, translate=Gf.Vec3f(0.2, 0.08, 0.33)) physicsUtils.set_or_add_orient_op(foot_mesh, orient=Gf.Quatf(0.6918005, 0.3113917, 0, 0.6514961)) physicsUtils.set_or_add_scale_op(foot_mesh, scale=Gf.Vec3f(1.0, 1.0, 1.0)) def add_leg_foot(self): foot_usd_path = self._server_root + "/Projects/DInsight/foot3.usd" add_reference_to_stage( usd_path=foot_usd_path, prim_path=f"/World/foot", ) foot_mesh = UsdGeom.Mesh.Get(self._stage, "/World/foot") physicsUtils.set_or_add_translate_op(foot_mesh, translate=Gf.Vec3f(0.0, 0.08, 0.30)) # physicsUtils.set_or_add_orient_op(foot_mesh, orient=Gf.Quatf(-0.5207212, -0.3471475, 0, -0.7799603)) physicsUtils.set_or_add_orient_op(foot_mesh, orient=Gf.Quatf(0.6513039, 0.4342026, 0.3618355, 0.5063066 )) physicsUtils.set_or_add_scale_op(foot_mesh, scale=Gf.Vec3f(0.005, 0.005, 0.005)) def add_light(self): sphereLight = UsdLux.SphereLight.Define(self._stage, Sdf.Path("/World/bottomSphereLight")) sphereLight.CreateIntensityAttr(3000) sphereLight.CreateRadiusAttr(0.05) def setup_scene(self): self._world = self.get_world() self._stage = omni.usd.get_context().get_stage() self._world.scene.add_default_ground_plane() self.simulation_context = SimulationContext() self.add_light() self.camera_setup() # self.add_female_foot() # self.add_male_foot() # self.add_soft_foot() self.add_leg_foot() self.og_setup() # self._f = h5py.File('hello_cam.hdf5','w') # self._group = self._f.create_group("isaac_save_data") return async def setup_post_load(self): self._world.add_physics_callback("sim_step", callback_fn=self.physics_callback) #callback names have to be unique return def physics_callback(self, step_size): # self._camera.get_current_frame() if self._save_count % 11 == 0: current_time = self.simulation_context.current_time omega = 2 * np.pi * self._rotate_count / 100 x_offset, y_offset = 0.5 * np.cos(omega), 0.5 * np.sin(omega) physicsUtils.set_or_add_translate_op(self._gemini_mesh, translate=Gf.Vec3f( 0.05, x_offset, 0.5 + y_offset)) rot = rot_utils.euler_angles_to_quats( np.array([ 90 + 360 / 100 * self._rotate_count, 0, 0 ]), degrees=True) print(f"rot: {rot}") physicsUtils.set_or_add_orient_op(self._gemini_mesh, orient=Gf.Quatf(*rot)) self._time_list.append(current_time) # self._img_list.append(self._camera.get_rgba()[:, :, :3]) print("Data Collected") self._rotate_count += 1 self._save_count += 1 if self._save_count > 1100: self.world_cleanup() # async def setup_pre_reset(self): # return # async def setup_post_reset(self): # return def world_cleanup(self): # self._group.create_dataset(f"sim_time", data=self._time_list, compression='gzip', compression_opts=9) # self._group.create_dataset(f"image", data=self._img_list, compression='gzip', compression_opts=9) # self._f.close() # print("Data saved") self._save_count = 0 self._world.pause() return
10,651
Python
39.501901
131
0.596564
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .replicator_basic import BinwithStuffs """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="Replicator", name="BinwithStuffs", title="BinwithStuffs", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=BinwithStuffs(), ) return
2,059
Python
41.916666
135
0.741622
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/replicator_basic.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.core.utils.stage import add_reference_to_stage, get_stage_units from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.physics_context.physics_context import PhysicsContext from semantics.schema.editor import remove_prim_semantics from omni.isaac.core.utils.prims import get_prim_at_path from omni.isaac.examples.base_sample import BaseSample import omni.replicator.core as rep import carb.settings import numpy as np from omni.isaac.core.prims.geometry_prim import GeometryPrim from os.path import expanduser import datetime now = datetime.datetime.now() PROPS = { 'spam' : "/Isaac/Props/YCB/Axis_Aligned/010_potted_meat_can.usd", 'jelly' : "/Isaac/Props/YCB/Axis_Aligned/009_gelatin_box.usd", 'tuna' : "/Isaac/Props/YCB/Axis_Aligned/007_tuna_fish_can.usd", 'cleanser' : "/Isaac/Props/YCB/Axis_Aligned/021_bleach_cleanser.usd", 'tomato_soup' : "/Isaac/Props/YCB/Axis_Aligned/005_tomato_soup_can.usd" } class BinwithStuffs(BaseSample): def __init__(self) -> None: super().__init__() # Nucleus Path Configuration self._isaac_assets_path = get_assets_root_path() self._nucleus_server_path = "omniverse://localhost/NVIDIA/" self.CRATE = self._nucleus_server_path + "Samples/Marbles/assets/standalone/SM_room_crate_3/SM_room_crate_3.usd" self.BIN_URL = self._isaac_assets_path + "/Isaac/Props/KLT_Bin/small_KLT_visual.usd" # Enable scripts carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True) # Disable capture on play and async rendering carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False) carb.settings.get_settings().set("/omni/replicator/asyncRendering", False) carb.settings.get_settings().set("/app/asyncRendering", False) # Replicator Writerdir now_str = now.strftime("%Y-%m-%d_%H:%M:%S") self._out_dir = str(expanduser("~") + "/Documents/grocery_data_" + now_str) # bin geometry property self._bin_scale = np.array([2.0, 2.0, 0.5]) self._bin_position = np.array([0.0, 0.0, 0.3]) self._plane_scale = np.array([0.24, 0.4, 1.0]) self._plane_position = np.array([0.0, 0.0, 0.4]) self._plane_rotation = np.array([0.0, 0.0, 0.0]) self._sim_step = 0 return def random_props(self, file_name, class_name, max_number=3, one_in_n_chance=4): file_name = self._isaac_assets_path + file_name instances = rep.randomizer.instantiate(file_name, size=max_number, mode='scene_instance') with instances: rep.physics.collider() rep.modify.semantics([('class', class_name)]) rep.randomizer.scatter_2d(self.plane, check_for_collisions=True) rep.modify.pose( rotation=rep.distribution.uniform((-180,-180, -180), (180, 180, 180)), ) visibility_dist = [True] + [False]*(one_in_n_chance) rep.modify.visibility(rep.distribution.choice(visibility_dist)) def random_sphere_lights(self): with self.rp_light: rep.modify.pose( position=rep.distribution.uniform((-0.5, -0.5, 1.0), (0.5, 0.5, 1.0)), ) def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() add_reference_to_stage(usd_path=self.BIN_URL, prim_path="/World/bin") world.scene.add(GeometryPrim(prim_path="/World/bin", name=f"bin_ref_geom", collision=True)) self._bin_ref_geom = world.scene.get_object(f"bin_ref_geom") self._bin_ref_geom.set_local_scale(np.array([self._bin_scale])) self._bin_ref_geom.set_world_pose(position=self._bin_position) self._bin_ref_geom.set_default_state(position=self._bin_position) self.cam = rep.create.camera(position=(0, 0, 2), look_at=(0, 0, 0)) self.rp = rep.create.render_product(self.cam, resolution=(1024, 1024)) self.plane = rep.create.plane( scale=self._plane_scale, position=self._plane_position, rotation=self._plane_rotation, visible=False ) rep.randomizer.register(self.random_props) # rep.randomizer.register(self.random_sphere_lights) return async def setup_post_load(self): # interval : Number of frames to capture before switching. # When generating large datasets, increasing this interval will reduce time taken. # A good value to set is 10. with rep.trigger.on_frame(num_frames=50, interval=2): for n, f in PROPS.items(): self.random_props(f, n) # Create a writer and apply the augmentations to its corresponding annotators self._writer = rep.WriterRegistry.get("BasicWriter") print(f"Writing data to: {self._out_dir}") self._writer.initialize( output_dir=self._out_dir, rgb=True, bounding_box_2d_tight=True, ) # Attach render product to writer self._writer.attach([self.rp]) return
5,609
Python
40.25
120
0.648244
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/inference/model_info.py
import tritonclient.grpc as grpcclient inference_server_url = "localhost:8003" triton_client = grpcclient.InferenceServerClient(url=inference_server_url) # find out info about model model_name = "our_new_model" config_info = triton_client.get_model_config(model_name) print(config_info)
290
Python
25.454543
74
0.793103
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/inference/inference.py
from tritonclient.utils import triton_to_np_dtype import tritonclient.grpc as grpcclient import cv2 import numpy as np from matplotlib import pyplot as plt inference_server_url = "localhost:8003" triton_client = grpcclient.InferenceServerClient(url=inference_server_url) model_name = "our_new_model" # load image data target_width, target_height = 1024, 1024 image_bgr = cv2.imread("sample_image3.png") image_bgr = cv2.resize(image_bgr, (target_width, target_height)) image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) image = np.float32(image_rgb) # preprocessing image = image/255 image = np.moveaxis(image, -1, 0) # HWC to CHW image = image[np.newaxis, :] # add batch dimension image = np.float32(image) plt.imshow(image_rgb) # create input input_name = "input" inputs = [grpcclient.InferInput(input_name, image.shape, "FP32")] inputs[0].set_data_from_numpy(image) output_names = ["boxes", "labels", "scores"] outputs = [grpcclient.InferRequestedOutput(n) for n in output_names] results = triton_client.infer(model_name, inputs, outputs=outputs) boxes, labels, scores = [results.as_numpy(o) for o in output_names] # annotate annotated_image = image_bgr.copy() props_dict = { 0: 'klt_bin', 1: 'tomato_soup', 2: 'tuna', 3: 'spam', 4: 'jelly', 5: 'cleanser', } if boxes.size > 0: # ensure something is found for box, lab, scr in zip(boxes, labels, scores): if scr > 0.4: box_top_left = int(box[0]), int(box[1]) box_bottom_right = int(box[2]), int(box[3]) text_origin = int(box[0]), int(box[3]) border_color = list(np.random.random(size=3) * 256) text_color = (255, 255, 255) font_scale = 0.9 thickness = 1 # bounding box2 img = cv2.rectangle( annotated_image, box_top_left, box_bottom_right, border_color, thickness=5, lineType=cv2.LINE_8 ) print(f"index: {lab}, label: {props_dict[lab]}, score: {scr:.2f}") # For the text background # Finds space required by the text so that we can put a background with that amount of width. (w, h), _ = cv2.getTextSize( props_dict[lab], cv2.FONT_HERSHEY_SIMPLEX, 0.6, 1 ) # Prints the text. img = cv2.rectangle( img, (box_top_left[0], box_top_left[1] - 20), (box_top_left[0] + w, box_top_left[1]), border_color, -1 ) img = cv2.putText( img, props_dict[lab], box_top_left, cv2.FONT_HERSHEY_SIMPLEX, 0.6, text_color, 1 ) plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)) plt.show()
2,869
Python
28.587629
105
0.581039
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/export/model_export.py
import os import torch import torchvision import warnings warnings.filterwarnings("ignore") device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') # load the PyTorch model. pytorch_dir = "/home/kimsooyoung/Documents/model.pth" model = torch.load(pytorch_dir).cuda() # Export Model dummy_input = torch.rand(1, 3, 1024, 1024).cuda() torch.onnx.export( model, dummy_input, "model.onnx", opset_version=11, input_names=["input"], output_names=["boxes", "labels", "scores"] )
527
Python
20.999999
83
0.698292
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/viz/data_visualize.py
import os import json import hashlib from PIL import Image import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches # # Desktop # data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-21_18:52:00" # Laptop data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-21_10:13:03" out_dir = "/home/kimsooyoung/Documents" number = "0025" # Write Visualization Functions # data_to_colour # takes in our data from a specific label ID and maps it to the proper color for the bounding box. def data_to_colour(data): if isinstance(data, str): data = bytes(data, "utf-8") else: data = bytes(data) m = hashlib.sha256() m.update(data) key = int(m.hexdigest()[:8], 16) r = ((((key >> 0) & 0xFF) + 1) * 33) % 255 g = ((((key >> 8) & 0xFF) + 1) * 33) % 255 b = ((((key >> 16) & 0xFF) + 1) * 33) % 255 inv_norm_i = 128 * (3.0 / (r + g + b)) return (int(r * inv_norm_i) / 255, int(g * inv_norm_i) / 255, int(b * inv_norm_i) / 255) # colorize_bbox_2d # takes in the path to the RGB image for the background, # the bounding box data, the labels, and the path to store the visualization. # It outputs a colorized bounding box. def colorize_bbox_2d(rgb_path, data, id_to_labels, file_path): rgb_img = Image.open(rgb_path) colors = [data_to_colour(bbox["semanticId"]) for bbox in data] fig, ax = plt.subplots(figsize=(10, 10)) ax.imshow(rgb_img) for bbox_2d, color, index in zip(data, colors, id_to_labels.keys()): labels = id_to_labels[str(index)] rect = patches.Rectangle( xy=(bbox_2d["x_min"], bbox_2d["y_min"]), width=bbox_2d["x_max"] - bbox_2d["x_min"], height=bbox_2d["y_max"] - bbox_2d["y_min"], edgecolor=color, linewidth=2, label=labels, fill=False, ) ax.add_patch(rect) plt.legend(loc="upper left") plt.savefig(file_path) # Load Synthetic Data and Visualize rgb_path = data_dir rgb = "rgb_"+number+".png" rgb_path = os.path.join(rgb_path, rgb) import os print(os.path.abspath(".")) # load the bounding box data. npy_path = data_dir bbox2d_tight_file_name = "bounding_box_2d_tight_"+number+".npy" data = np.load(os.path.join(npy_path, bbox2d_tight_file_name)) # load the labels corresponding to the image. json_path = data_dir bbox2d_tight_labels_file_name = "bounding_box_2d_tight_labels_"+number+".json" bbox2d_tight_id_to_labels = None with open(os.path.join(json_path, bbox2d_tight_labels_file_name), "r") as json_data: bbox2d_tight_id_to_labels = json.load(json_data) # Finally, we can call our function and see the labeled image! colorize_bbox_2d(rgb_path, data, bbox2d_tight_id_to_labels, os.path.join(out_dir, "bbox2d_tight.png"))
2,790
Python
31.453488
102
0.642294
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorBinwithStuffs/train/fast_rcnn_train.py
from PIL import Image import os import numpy as np import torch import torch.utils.data import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor from torchvision import transforms as T import json import shutil epochs = 15 num_classes = 6 data_dir = "/home/kimsooyoung/Documents/grocery_data_2024-05-21_18:52:00" output_file = "/home/kimsooyoung/Documents/model.pth" device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu') print(f"Using device: {device}") class GroceryDataset(torch.utils.data.Dataset): # This function is run once when instantiating the Dataset object def __init__(self, root, transforms): self.root = root self.transforms = transforms # In the first portion of this code we are taking our single dataset folder # and splitting it into three folders based on the file types. # This is just a preprocessing step. list_ = os.listdir(root) for file_ in list_: name, ext = os.path.splitext(file_) ext = ext[1:] if ext == '': continue if os.path.exists(root+ '/' + ext): shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_) else: os.makedirs(root+'/'+ext) shutil.move(root+'/'+file_, root+'/'+ext+'/'+file_) self.imgs = list(sorted(os.listdir(os.path.join(root, "png")))) self.label = list(sorted(os.listdir(os.path.join(root, "json")))) self.box = list(sorted(os.listdir(os.path.join(root, "npy")))) # We have our three attributes with the img, label, and box data # Loads and returns a sample from the dataset at the given index idx def __getitem__(self, idx): img_path = os.path.join(self.root, "png", self.imgs[idx]) img = Image.open(img_path).convert("RGB") label_path = os.path.join(self.root, "json", self.label[idx]) with open(os.path.join('root', label_path), "r") as json_data: json_labels = json.load(json_data) box_path = os.path.join(self.root, "npy", self.box[idx]) dat = np.load(str(box_path)) boxes = [] labels = [] for i in dat: obj_val = i[0] xmin = torch.as_tensor(np.min(i[1]), dtype=torch.float32) xmax = torch.as_tensor(np.max(i[3]), dtype=torch.float32) ymin = torch.as_tensor(np.min(i[2]), dtype=torch.float32) ymax = torch.as_tensor(np.max(i[4]), dtype=torch.float32) if (ymax > ymin) & (xmax > xmin): boxes.append([xmin, ymin, xmax, ymax]) area = (xmax - xmin) * (ymax - ymin) labels += [json_labels.get(str(obj_val)).get('class')] label_dict = {} # Labels for the dataset static_labels = { 'klt_bin' : 0, 'tomato_soup' : 1, 'tuna' : 2, 'spam' : 3, 'jelly' : 4, 'cleanser' : 5 } labels_out = [] # Transforming the input labels into a static label dictionary to use for i in range(len(labels)): label_dict[i] = labels[i] for i in label_dict: fruit = label_dict[i] final_fruit_label = static_labels[fruit] labels_out += [final_fruit_label] target = {} target["boxes"] = torch.as_tensor(boxes, dtype=torch.float32) target["labels"] = torch.as_tensor(labels_out, dtype=torch.int64) target["image_id"] = torch.tensor([idx]) target["area"] = area if self.transforms is not None: img= self.transforms(img) return img, target # Finally we have a function for the number of samples in our dataset def __len__(self): return len(self.imgs) # Create Helper Functions # converting to `Tensor` objects and also converting the `dtypes`. def get_transform(train): transforms = [] transforms.append(T.PILToTensor()) transforms.append(T.ConvertImageDtype(torch.float)) return T.Compose(transforms) # Create a function to collate our samples. def collate_fn(batch): return tuple(zip(*batch)) # Create Model and Train # We are starting with the pretrained (default weights) object detection # fasterrcnn_resnet50 model from Torchvision. def create_model(num_classes): model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights='DEFAULT') in_features = model.roi_heads.box_predictor.cls_score.in_features model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) return model # create our dataset by using our custom GroceryDataset class # This is then passed into our DataLoader. dataset = GroceryDataset(data_dir, get_transform(train=True)) data_loader = torch.utils.data.DataLoader( dataset, # batch_size=16, batch_size=8, shuffle=True, collate_fn=collate_fn ) # create our model with the N classes # And then transfer it to the GPU for training. model = create_model(num_classes) model.to(device) params = [p for p in model.parameters() if p.requires_grad] optimizer = torch.optim.SGD(params, lr=0.001) len_dataloader = len(data_loader) # Now we can actually train our model. # Keep track of our loss and print it out as we train. model.train() ep = 0 for epoch in range(epochs): optimizer.zero_grad() ep += 1 i = 0 for imgs, annotations in data_loader: i += 1 imgs = list(img.to(device) for img in imgs) annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations] loss_dict = model(imgs, annotations) losses = sum(loss for loss in loss_dict.values()) losses.backward() optimizer.step() print(f'Epoch: {ep} Iteration: {i}/{len_dataloader}, Loss: {losses}') torch.save(model, output_file)
5,909
Python
33.360465
84
0.616856
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "RoadBalanceEdu" EXTENSION_DESCRIPTION = ""
495
Python
37.153843
76
0.80404
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .replicator_basic import BasicCubeRandomRotation """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="Replicator", name="BasicCubeRandomRotation", title="BasicCubeRandomRotation", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=BasicCubeRandomRotation(), ) return
2,099
Python
42.749999
135
0.746546
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/replicator_basic.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.stage import open_stage import omni.replicator.core as rep import carb.settings import numpy as np from os.path import expanduser import datetime now = datetime.datetime.now() class BasicCubeRandomRotation(BaseSample): def __init__(self) -> None: super().__init__() self.assets_root_path = get_assets_root_path() self._nucleus_server_path = "omniverse://localhost/NVIDIA/" # Enable scripts carb.settings.get_settings().set_bool("/app/omni.graph.scriptnode/opt_in", True) # Disable capture on play and async rendering carb.settings.get_settings().set("/omni/replicator/captureOnPlay", False) carb.settings.get_settings().set("/omni/replicator/asyncRendering", False) carb.settings.get_settings().set("/app/asyncRendering", False) now_str = now.strftime("%Y-%m-%d_%H:%M:%S") self._out_dir = str(expanduser("~") + "/Documents/cube_data_" + now_str) self._sim_step = 0 return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() # Create a red cube and a render product from a camera looking at the cube from the top red_mat = rep.create.material_omnipbr(diffuse=(1, 0, 0)) self.red_cube = rep.create.cube(position=(0, 0, 0.71), material=red_mat) self.cam = rep.create.camera(position=(0, 0, 5), look_at=(0, 0, 0)) self.rp = rep.create.render_product(self.cam, resolution=(1024, 1024)) return async def setup_post_load(self): with rep.trigger.on_frame(num_frames=20): with self.red_cube: rep.randomizer.rotation() # Create a writer and apply the augmentations to its corresponding annotators writer = rep.WriterRegistry.get("BasicWriter") print(f"Writing data to: {self._out_dir}") writer.initialize( output_dir=self._out_dir, rgb=True, bounding_box_2d_tight=True, distance_to_camera=True ) # Attach render product to writer writer.attach([self.rp]) return
2,733
Python
34.506493
95
0.663739
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ReplicatorCubeRandomRotation/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .franka_deformable import FrankaDeformable """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIDemo", name="FrankaDeformable", title="FrankaDeformable", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FrankaDeformable(), ) return
2,070
Python
42.145832
135
0.742995
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/franka_deformable.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample # This extension has franka related tasks and controllers as well from omni.isaac.franka import Franka from omni.isaac.franka.controllers import PickPlaceController from omni.isaac.franka.tasks import PickPlace from omni.isaac.core.tasks import BaseTask import numpy as np from omni.isaac.core.materials.deformable_material import DeformableMaterial from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.physx.scripts import deformableUtils, physicsUtils from pxr import UsdGeom, Gf, UsdPhysics import omni.physx import omni.usd import omni class FrankaPlaying(BaseTask): #NOTE: we only cover here a subset of the task functions that are available, # checkout the base class for all the available functions to override. # ex: calculate_metrics, is_done..etc. def __init__(self, name): super().__init__(name=name, offset=None) self._goal_position = np.array([-0.3, -0.3, 0.0515 / 2.0]) self._task_achieved = False return def create_cube(self, stage, prim_path): # Create cube result, path = omni.kit.commands.execute("CreateMeshPrimCommand", prim_type="Cube") omni.kit.commands.execute("MovePrim", path_from=path, path_to=prim_path) omni.usd.get_context().get_selection().set_selected_prim_paths([], False) cube_mesh = UsdGeom.Mesh.Get(stage, prim_path) physicsUtils.set_or_add_translate_op(cube_mesh, translate=Gf.Vec3f(0.3, 0.3, 0.3)) # physicsUtils.set_or_add_orient_op(cube_mesh, orient=Gf.Quatf(0.707, 0.707, 0, 0)) physicsUtils.set_or_add_scale_op(cube_mesh, scale=Gf.Vec3f(0.04, 0.04, 0.04)) cube_mesh.CreateDisplayColorAttr([(1.0, 0.0, 0.0)]) return def setup_deformable_cube(self, stage, prim_path): # Apply PhysxDeformableBodyAPI and PhysxCollisionAPI to skin mesh and set parameter to default values deformableUtils.add_physx_deformable_body( stage, prim_path, collision_simplification=True, simulation_hexahedral_resolution=4, self_collision=False, ) # Create a deformable body material and set it on the deformable body deformable_material_path = omni.usd.get_stage_next_free_path(stage, "/World/deformableBodyMaterial", True) deformableUtils.add_deformable_body_material( stage, deformable_material_path, youngs_modulus=10000.0, poissons_ratio=0.49, damping_scale=0.0, dynamic_friction=0.5, ) self._cube_prim = stage.GetPrimAtPath(prim_path) physicsUtils.add_physics_material_to_prim(stage, self._cube_prim, prim_path) return # Here we setup all the assets that we care about in this task. def set_up_scene(self, scene): super().set_up_scene(scene) scene.add_default_ground_plane() stage = omni.usd.get_context().get_stage() self.create_cube(stage, "/World/cube") self.setup_deformable_cube(stage, "/World/cube") self._franka = scene.add(Franka(prim_path="/World/Fancy_Franka", name="fancy_franka")) return # Information exposed to solve the task is returned from the task through get_observations def get_observations(self): matrix: Gf.Matrix4d = omni.usd.get_world_transform_matrix(self._cube_prim) translate: Gf.Vec3d = matrix.ExtractTranslation() cube_position = np.array([translate[0], translate[1], translate[2]]) current_joint_positions = self._franka.get_joint_positions() observations = { self._franka.name: { "joint_positions": current_joint_positions, }, "deformable_cube": { "position": cube_position, "goal_position": self._goal_position } } return observations # Called before each physics step, # for instance we can check here if the task was accomplished by # changing the color of the cube once its accomplished def pre_step(self, control_index, simulation_time): return # Called after each reset, # for instance we can always set the gripper to be opened at the beginning after each reset # also we can set the cube's color to be blue def post_reset(self): self._franka.gripper.set_joint_positions(self._franka.gripper.joint_opened_positions) self._task_achieved = False return class FrankaDeformable(BaseSample): def __init__(self) -> None: super().__init__() return def _setup_simulation(self): self._scene = PhysicsContext() self._scene.set_solver_type("TGS") self._scene.set_broadphase_type("GPU") self._scene.enable_gpu_dynamics(flag=True) def setup_scene(self): world = self.get_world() self._setup_simulation() # We add the task to the world here world.add_task(FrankaPlaying(name="deformable_franka_task")) return async def setup_post_load(self): self._world = self.get_world() # The world already called the setup_scene from the task (with first reset of the world) # so we can retrieve the task objects self._franka = self._world.scene.get_object("fancy_franka") self._controller = PickPlaceController( name="pick_place_controller", gripper=self._franka.gripper, robot_articulation=self._franka, ) self._world.add_physics_callback("sim_step", callback_fn=self.physics_step) await self._world.play_async() return async def setup_post_reset(self): self._controller.reset() await self._world.play_async() return def physics_step(self, step_size): # Gets all the tasks observations current_observations = self._world.get_observations() actions = self._controller.forward( picking_position=current_observations["deformable_cube"]["position"], placing_position=current_observations["deformable_cube"]["goal_position"], current_joint_positions=current_observations["fancy_franka"]["joint_positions"], ) self._franka.apply_action(actions) if self._controller.is_done(): self._world.pause() return
6,929
Python
37.932584
114
0.65464
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/FrankaDeformable/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .robotnik_summit import RobotnikSummit """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WheeledRobots", name="RobotnikSummitO3Wheel", title="RobotnikSummitO3Wheel", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=RobotnikSummit(), ) return
2,079
Python
42.333332
135
0.744108
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/robotnik_summit.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController import numpy as np import carb class RobotnikSummit(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) # wheel models referenced from : https://git.openlogisticsfoundation.org/silicon-economy/simulation-model/o3dynsimmodel self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/Collected_summit_xl_omni_four/summit_xl_omni_four.usd" self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ]) self._wheel_positions = np.array([ [0.229, 0.235, 0.11], [0.229, -0.235, 0.11], [-0.229, 0.235, 0.11], [-0.229, -0.235, 0.11], ]) self._wheel_orientations = np.array([ [0.7071068, 0, 0, 0.7071068], [0.7071068, 0, 0, -0.7071068], [0.7071068, 0, 0, 0.7071068], [0.7071068, 0, 0, -0.7071068], ]) self._mecanum_angles = np.array([ -135.0, -45.0, -45.0, -135.0, ]) self._wheel_axis = np.array([1, 0, 0]) self._up_axis = np.array([0, 0, 1]) return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit") self._wheeled_robot = WheeledRobot( prim_path="/World/Summit/summit_xl_base_link", name="my_summit", wheel_dof_names=[ "fl_joint", "fr_joint", "rl_joint", "rr_joint", ], create_robot=True, usd_path=self._robot_path, position=np.array([0, 0.0, 0.02]), orientation=np.array([1.0, 0.0, 0.0, 0.0]), ) self._save_count = 0 self._scene = PhysicsContext() self._scene.set_physics_dt(1 / 30.0) return async def setup_post_load(self): self._world = self.get_world() self._summit_controller = HolonomicController( name="holonomic_controller", wheel_radius=self._wheel_radius, wheel_positions=self._wheel_positions, wheel_orientations=self._wheel_orientations, mecanum_angles=self._mecanum_angles, wheel_axis=self._wheel_axis, up_axis=self._up_axis, ) self._summit_controller.reset() self._wheeled_robot.initialize() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._save_count += 1 wheel_action = None if self._save_count >= 0 and self._save_count < 150: wheel_action = self._summit_controller.forward(command=[0.5, 0.0, 0.0]) elif self._save_count >= 150 and self._save_count < 300: wheel_action = self._summit_controller.forward(command=[-0.5, 0.0, 0.0]) elif self._save_count >= 300 and self._save_count < 450: wheel_action = self._summit_controller.forward(command=[0.0, 0.5, 0.0]) elif self._save_count >= 450 and self._save_count < 600: wheel_action = self._summit_controller.forward(command=[0.0, -0.5, 0.0]) elif self._save_count >= 600 and self._save_count < 750: wheel_action = self._summit_controller.forward(command=[0.0, 0.0, 0.3]) elif self._save_count >= 750 and self._save_count < 900: wheel_action = self._summit_controller.forward(command=[0.0, 0.0, -0.3]) else: self._save_count = 0 self._wheeled_robot.apply_wheel_actions(wheel_action) return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): self._summit_controller.reset() await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
5,294
Python
36.821428
132
0.604836
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummitO3Wheel/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URBinFilling/extension.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import asyncio import os import omni.ui as ui from omni.isaac.examples.base_sample import BaseSampleExtension from omni.isaac.ui.ui_utils import btn_builder from .bin_filling import BinFilling class BinFillingExtension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="ETRIDemo", name="UR10 Bin Filling", title="UR10 Bin Filling", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_adding_manipulator.html", overview="This Example shows how to do bin filling using UR10 robot in Isaac Sim.\n It showcases a realistic surface gripper that breaks with heavy bin load.\nPress the 'Open in IDE' button to view the source code.", sample=BinFilling(), file_path=os.path.abspath(__file__), number_of_extra_frames=1, ) self.task_ui_elements = {} frame = self.get_frame(index=0) self.build_task_controls_ui(frame) return def _on_fill_bin_button_event(self): asyncio.ensure_future(self.sample.on_fill_bin_event_async()) self.task_ui_elements["Start Bin Filling"].enabled = False return def post_reset_button_event(self): self.task_ui_elements["Start Bin Filling"].enabled = True return def post_load_button_event(self): self.task_ui_elements["Start Bin Filling"].enabled = True return def post_clear_button_event(self): self.task_ui_elements["Start Bin Filling"].enabled = False return def build_task_controls_ui(self, frame): with frame: with ui.VStack(spacing=5): # Update the Frame Title frame.title = "Task Controls" frame.visible = True dict = { "label": "Start Bin Filling", "type": "button", "text": "Start Bin Filling", "tooltip": "Start Bin Filling", "on_clicked_fn": self._on_fill_bin_button_event, } self.task_ui_elements["Start Bin Filling"] = btn_builder(**dict) self.task_ui_elements["Start Bin Filling"].enabled = False
2,801
Python
38.464788
228
0.632988
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URBinFilling/__init__.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # # from omni.isaac.examples.bin_filling.bin_filling import BinFilling # from omni.isaac.examples.bin_filling.bin_filling_extension import BinFillingExtension from .extension import BinFillingExtension
633
Python
44.285711
87
0.821485
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/URBinFilling/bin_filling.py
# Copyright (c) 2021-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import h5py import numpy as np import omni.isaac.core.utils.numpy.rotations as rot_utils from omni.isaac.core.utils.rotations import euler_angles_to_quat from omni.isaac.examples.base_sample import BaseSample from omni.isaac.universal_robots.controllers.pick_place_controller import PickPlaceController from omni.isaac.universal_robots.tasks import BinFilling as BinFillingTask from omni.isaac.core import SimulationContext from omni.isaac.sensor import Camera class BinFilling(BaseSample): def __init__(self) -> None: super().__init__() self._controller = None self._articulation_controller = None self._added_screws = False self._sim_time_list = [] self._joint_positions = [] self._joint_velocities = [] self._camera1_img = [] self._camera2_img = [] self._camera3_img = [] def setup_scene(self): world = self.get_world() self.simulation_context = SimulationContext() world.add_task(BinFillingTask(name="bin_filling")) self._save_count = 0 self._camera1 = Camera( prim_path="/World/Scene/ur10/ee_link/ee_camera", # position=np.array([0.088, 0.0, 0.926]), translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 180.0, -30.0, 0.0 ]), degrees=True), ) self._camera1.set_clipping_range(0.1, 1000000.0) self._camera1.set_focal_length(1.5) self._camera1.initialize() self._camera1.add_motion_vectors_to_frame() self._camera1.set_visibility(False) self._camera2 = Camera( prim_path="/World/side_camera", position=np.array([2.5, 0.0, 0.0]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, 180.0 ]), degrees=True), ) self._camera2.set_focal_length(1.5) self._camera2.set_visibility(False) self._camera2.initialize() self._camera3 = Camera( prim_path="/World/front_camera", position=np.array([0.0, 2.0, 0.0]), # translation=np.array([0.0, 0.0, -0.1]), frequency=30, resolution=(640, 480), orientation=rot_utils.euler_angles_to_quats( np.array([ 0.0, 0.0, -90.0 ]), degrees=True), ) self._camera3.set_focal_length(1.5) self._camera3.set_visibility(False) self._camera3.initialize() self._f = h5py.File('ur_bin_filling.hdf5','w') self._group_f = self._f.create_group("isaac_dataset") self._save_count = 0 self._img_f = self._group_f.create_group("camera_images") return async def setup_post_load(self): self._ur10_task = self._world.get_task(name="bin_filling") self._task_params = self._ur10_task.get_params() self._my_ur10 = self._world.scene.get_object(self._task_params["robot_name"]["value"]) self._controller = PickPlaceController( name="pick_place_controller", gripper=self._my_ur10.gripper, robot_articulation=self._my_ur10 ) self._articulation_controller = self._my_ur10.get_articulation_controller() return def _on_fill_bin_physics_step(self, step_size): self._camera1.get_current_frame() self._camera2.get_current_frame() self._camera3.get_current_frame() current_time = self.simulation_context.current_time current_joint_state = self._my_ur10.get_joints_state() current_joint_positions = current_joint_state.positions current_joint_velocities = current_joint_state.velocities if self._save_count % 100 == 0: self._sim_time_list.append(current_time) self._joint_positions.append(current_joint_positions) self._joint_velocities.append(current_joint_velocities) self._camera1_img.append(self._camera1.get_rgba()[:, :, :3]) self._camera2_img.append(self._camera2.get_rgba()[:, :, :3]) self._camera3_img.append(self._camera3.get_rgba()[:, :, :3]) print("Collecting data...") observations = self._world.get_observations() actions = self._controller.forward( picking_position=observations[self._task_params["bin_name"]["value"]]["position"], placing_position=observations[self._task_params["bin_name"]["value"]]["target_position"], current_joint_positions=observations[self._task_params["robot_name"]["value"]]["joint_positions"], end_effector_offset=np.array([0, -0.098, 0.03]), end_effector_orientation=euler_angles_to_quat(np.array([np.pi, 0, np.pi / 2.0])), ) # if not self._added_screws and self._controller.get_current_event() == 6 and not self._controller.is_paused(): # self._controller.pause() # self._ur10_task.add_screws(screws_number=20) # self._added_screws = True # if self._controller.is_done(): # self._world.pause() self._articulation_controller.apply_action(actions) self._save_count += 1 if self._controller.is_done(): self.save_data() return async def on_fill_bin_event_async(self): world = self.get_world() world.add_physics_callback("sim_step", self._on_fill_bin_physics_step) await world.play_async() return async def setup_pre_reset(self): world = self.get_world() if world.physics_callback_exists("sim_step"): world.remove_physics_callback("sim_step") self._controller.reset() self._added_screws = False return def world_cleanup(self): self._controller = None self._added_screws = False return def save_data(self): self._group_f.create_dataset(f"sim_time", data=self._sim_time_list, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_positions", data=self._joint_positions, compression='gzip', compression_opts=9) self._group_f.create_dataset(f"joint_velocities", data=self._joint_velocities, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"ee_camera", data=self._camera1_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"side_camera", data=self._camera2_img, compression='gzip', compression_opts=9) self._img_f.create_dataset(f"front_camera", data=self._camera3_img, compression='gzip', compression_opts=9) self._f.close() print("Data saved") self._save_count = 0 self._world.pause() return
7,425
Python
38.291005
126
0.61037
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .limo_ackermann import LimoAckermann """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WheeledRobots", name="LimoAckermann_ROS2_Ackermann", title="LimoAckermann_ROS2_Ackermann", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=LimoAckermann(), ) return
2,090
Python
42.562499
135
0.743541
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/limo_ackermann.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController import omni.graph.core as og import numpy as np import usdrt.Sdf import carb class LimoAckermann(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/limo_ackermann.usd" self._domain_id = 30 self._maxWheelRotation = 1e6 self._maxWheelVelocity = 1e6 self._trackWidth = 0.13 self._turningWheelRadius = 0.045 self._wheelBase = 0.2 self._targetPrim = "/World/Limo/base_footprint" self._robotPath = "/World/Limo/base_footprint" return def og_setup(self): try: # AckermannSteering reference : https://docs.omniverse.nvidia.com/py/isaacsim/source/extensions/omni.isaac.wheeled_robots/docs/index.html#ackermannsteering og.Controller.edit( {"graph_path": "/ROS2Ackermann", "evaluator_name": "execution"}, { og.Controller.Keys.CREATE_NODES: [ ("onPlaybackTick", "omni.graph.action.OnPlaybackTick"), ("context", "omni.isaac.ros2_bridge.ROS2Context"), ("subscribeAckermann", "omni.isaac.ros2_bridge.ROS2SubscribeAckermannDrive"), ("scaleToFromStage", "omni.isaac.core_nodes.OgnIsaacScaleToFromStageUnit"), ("ackermannCtrl", "omni.isaac.wheeled_robots.AckermannSteering"), ("wheelJointNames", "omni.graph.nodes.ConstructArray"), ("wheelRotationVel", "omni.graph.nodes.ConstructArray"), ("hingeJointNames", "omni.graph.nodes.ConstructArray"), ("hingePosVel", "omni.graph.nodes.ConstructArray"), ("articulationRotation", "omni.isaac.core_nodes.IsaacArticulationController"), ("articulationPosition", "omni.isaac.core_nodes.IsaacArticulationController"), ], og.Controller.Keys.SET_VALUES: [ ("context.inputs:domain_id", self._domain_id), ("subscribeAckermann.inputs:topicName", "ackermann_cmd"), ("ackermannCtrl.inputs:maxWheelRotation", self._maxWheelRotation), ("ackermannCtrl.inputs:maxWheelVelocity", self._maxWheelVelocity), ("ackermannCtrl.inputs:trackWidth", self._trackWidth), ("ackermannCtrl.inputs:turningWheelRadius", self._turningWheelRadius), ("ackermannCtrl.inputs:useAcceleration", False), ("ackermannCtrl.inputs:wheelBase", self._wheelBase), ("wheelJointNames.inputs:arraySize", 4), ("wheelJointNames.inputs:arrayType", "token[]"), ("wheelJointNames.inputs:input0", "rear_left_wheel"), ("wheelJointNames.inputs:input1", "rear_right_wheel"), ("wheelJointNames.inputs:input2", "front_left_wheel"), ("wheelJointNames.inputs:input3", "front_right_wheel"), ("hingeJointNames.inputs:arraySize", 2), ("hingeJointNames.inputs:arrayType", "token[]"), ("hingeJointNames.inputs:input0", "left_steering_hinge_wheel"), ("hingeJointNames.inputs:input1", "right_steering_hinge_wheel"), ("wheelRotationVel.inputs:arraySize", 4), ("wheelRotationVel.inputs:arrayType", "double[]"), ("hingePosVel.inputs:arraySize", 2), ("hingePosVel.inputs:arrayType", "double[]"), ("articulationRotation.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationRotation.inputs:robotPath", self._robotPath), ("articulationRotation.inputs:usePath", False), ("articulationPosition.inputs:targetPrim", [usdrt.Sdf.Path(self._targetPrim)]), ("articulationPosition.inputs:robotPath", self._robotPath), ("articulationPosition.inputs:usePath", False), ], og.Controller.Keys.CREATE_ATTRIBUTES: [ ("wheelJointNames.inputs:input1", "token"), ("wheelJointNames.inputs:input2", "token"), ("wheelJointNames.inputs:input3", "token"), ("hingeJointNames.inputs:input1", "token"), ("wheelRotationVel.inputs:input1", "double"), ("wheelRotationVel.inputs:input2", "double"), ("wheelRotationVel.inputs:input3", "double"), ("hingePosVel.inputs:input1", "double"), ], og.Controller.Keys.CONNECT: [ ("onPlaybackTick.outputs:tick", "subscribeAckermann.inputs:execIn"), ("context.outputs:context", "subscribeAckermann.inputs:context"), ("subscribeAckermann.outputs:speed", "scaleToFromStage.inputs:value"), ("subscribeAckermann.outputs:execOut", "ackermannCtrl.inputs:execIn"), ("scaleToFromStage.outputs:result", "ackermannCtrl.inputs:speed"), ("subscribeAckermann.outputs:steeringAngle", "ackermannCtrl.inputs:steeringAngle"), ("ackermannCtrl.outputs:leftWheelAngle", "hingePosVel.inputs:input0"), ("ackermannCtrl.outputs:rightWheelAngle", "hingePosVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input0"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input1"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input2"), ("ackermannCtrl.outputs:wheelRotationVelocity", "wheelRotationVel.inputs:input3"), ("ackermannCtrl.outputs:execOut", "articulationRotation.inputs:execIn"), ("wheelJointNames.outputs:array", "articulationRotation.inputs:jointNames"), ("wheelRotationVel.outputs:array", "articulationRotation.inputs:velocityCommand"), ("ackermannCtrl.outputs:execOut", "articulationPosition.inputs:execIn"), ("hingeJointNames.outputs:array", "articulationPosition.inputs:jointNames"), ("hingePosVel.outputs:array", "articulationPosition.inputs:positionCommand"), ], }, ) except Exception as e: print(e) def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Limo") self._save_count = 0 self.og_setup() return async def setup_post_load(self): self._world = self.get_world() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._save_count += 1 return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): self._summit_controller.reset() await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
9,065
Python
51.709302
167
0.588969
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotLimoAckermannROS2/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/ik_solver.py
from omni.isaac.motion_generation import ArticulationKinematicsSolver, LulaKinematicsSolver from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.articulations import Articulation from typing import Optional import carb class KinematicsSolver(ArticulationKinematicsSolver): def __init__(self, robot_articulation: Articulation, end_effector_frame_name: Optional[str] = None) -> None: #TODO: change the config path # desktop # my_path = "/home/kimsooyoung/Documents/IsaacSim/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/" # self._urdf_path = "/home/kimsooyoung/Downloads/USD/cobotta_pro_900/" # lactop self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/" self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/" self._kinematics = LulaKinematicsSolver( robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml", urdf_path=self._urdf_path+"cobotta_pro_900.urdf" ) if end_effector_frame_name is None: end_effector_frame_name = "onrobot_rg6_base_link" ArticulationKinematicsSolver.__init__(self, robot_articulation, self._kinematics, end_effector_frame_name) return
1,388
Python
45.299998
125
0.698127
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .follow_target_example import FollowTargetExample """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="AddingNewManip", name="FollowTarget", title="FollowTarget", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=FollowTargetExample(), ) return
2,078
Python
42.312499
135
0.743503
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/follow_target_example.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.manipulators.grippers import ParallelGripper from omni.isaac.manipulators import SingleManipulator import omni.isaac.core.tasks as tasks from typing import Optional import numpy as np import carb from .ik_solver import KinematicsSolver from .controllers.rmpflow import RMPFlowController # Inheriting from the base class Follow Target class FollowTarget(tasks.FollowTarget): def __init__( self, name: str = "denso_follow_target", target_prim_path: Optional[str] = None, target_name: Optional[str] = None, target_position: Optional[np.ndarray] = None, target_orientation: Optional[np.ndarray] = None, offset: Optional[np.ndarray] = None, ) -> None: tasks.FollowTarget.__init__( self, name=name, target_prim_path=target_prim_path, target_name=target_name, target_position=target_position, target_orientation=target_orientation, offset=offset, ) carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._robot_path = self._server_root + "/Projects/RBROS2/cobotta_pro_900/cobotta_pro_900/cobotta_pro_900.usd" self._joints_default_positions = np.zeros(12) self._joints_default_positions[7] = 0.628 self._joints_default_positions[8] = 0.628 return def set_robot(self) -> SingleManipulator: # add robot to the scene add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/cobotta") #define the gripper gripper = ParallelGripper( #We chose the following values while inspecting the articulation end_effector_prim_path="/World/cobotta/onrobot_rg6_base_link", joint_prim_names=["finger_joint", "right_outer_knuckle_joint"], joint_opened_positions=np.array([0, 0]), joint_closed_positions=np.array([0.628, -0.628]), action_deltas=np.array([-0.628, 0.628]), ) # define the manipulator manipulator = SingleManipulator( prim_path="/World/cobotta", name="cobotta_robot", end_effector_prim_name="onrobot_rg6_base_link", gripper=gripper ) manipulator.set_joints_default_state(positions=self._joints_default_positions) return manipulator class FollowTargetExample(BaseSample): def __init__(self) -> None: super().__init__() self._articulation_controller = None # simulation step counter self._sim_step = 0 return def setup_scene(self): self._world = self.get_world() self._world.scene.add_default_ground_plane() # We add the task to the world here my_task = FollowTarget( name="denso_follow_target", target_position=np.array([0.5, 0, 0.5]) ) self._world.add_task(my_task) return async def setup_post_load(self): self._world = self.get_world() self._task_params = self._world.get_task("denso_follow_target").get_params() self._target_name = self._task_params["target_name"]["value"] self._my_denso = self._world.scene.get_object(self._task_params["robot_name"]["value"]) self._my_controller = KinematicsSolver(self._my_denso) # self._my_controller = RMPFlowController(name="target_follower_controller", robot_articulation=self._my_denso) self._articulation_controller = self._my_denso.get_articulation_controller() self._world.add_physics_callback("sim_step", callback_fn=self.sim_step_cb) return async def setup_post_reset(self): self._my_controller.reset() await self._world.play_async() return def sim_step_cb(self, step_size): observations = self._world.get_observations() pos = observations[self._target_name]["position"] ori = observations[self._target_name]["orientation"] print(self._target_name) print(pos) print(ori) # IK controller actions, succ = self._my_controller.compute_inverse_kinematics( target_position=pos, target_orientation=ori, ) if succ: self._articulation_controller.apply_action(actions) else: carb.log_warn("IK did not converge to a solution. No action is being taken.") # # RMPFlow controller # actions = self._my_controller.forward( # target_end_effector_position=pos, # target_end_effector_orientation=ori, # ) # self._articulation_controller.apply_action(actions) return
5,582
Python
34.560509
119
0.645468
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/rmpflow/robot_descriptor.yaml
api_version: 1.0 cspace: - joint_1 - joint_2 - joint_3 - joint_4 - joint_5 - joint_6 root_link: world default_q: [ 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 ] cspace_to_urdf_rules: [] composite_task_spaces: []
230
YAML
15.499999
38
0.56087
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/rmpflow/denso_rmpflow_common.yaml
joint_limit_buffers: [.01, .01, .01, .01, .01, .01] rmp_params: cspace_target_rmp: metric_scalar: 50. position_gain: 100. damping_gain: 50. robust_position_term_thresh: .5 inertia: 1. cspace_trajectory_rmp: p_gain: 100. d_gain: 10. ff_gain: .25 weight: 50. cspace_affine_rmp: final_handover_time_std_dev: .25 weight: 2000. joint_limit_rmp: metric_scalar: 1000. metric_length_scale: .01 metric_exploder_eps: 1e-3 metric_velocity_gate_length_scale: .01 accel_damper_gain: 200. accel_potential_gain: 1. accel_potential_exploder_length_scale: .1 accel_potential_exploder_eps: 1e-2 joint_velocity_cap_rmp: max_velocity: 1. velocity_damping_region: .3 damping_gain: 1000.0 metric_weight: 100. target_rmp: accel_p_gain: 30. accel_d_gain: 85. accel_norm_eps: .075 metric_alpha_length_scale: .05 min_metric_alpha: .01 max_metric_scalar: 10000 min_metric_scalar: 2500 proximity_metric_boost_scalar: 20. proximity_metric_boost_length_scale: .02 xi_estimator_gate_std_dev: 20000. accept_user_weights: false axis_target_rmp: accel_p_gain: 210. accel_d_gain: 60. metric_scalar: 10 proximity_metric_boost_scalar: 3000. proximity_metric_boost_length_scale: .08 xi_estimator_gate_std_dev: 20000. accept_user_weights: false collision_rmp: damping_gain: 50. damping_std_dev: .04 damping_robustness_eps: 1e-2 damping_velocity_gate_length_scale: .01 repulsion_gain: 800. repulsion_std_dev: .01 metric_modulation_radius: .5 metric_scalar: 10000. metric_exploder_std_dev: .02 metric_exploder_eps: .001 damping_rmp: accel_d_gain: 30. metric_scalar: 50. inertia: 100. canonical_resolve: max_acceleration_norm: 50. projection_tolerance: .01 verbose: false body_cylinders: - name: base pt1: [0,0,.333] pt2: [0,0,0.] radius: .05 body_collision_controllers: - name: onrobot_rg6_base_link radius: .05
2,282
YAML
28.64935
51
0.583699
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/controllers/rmpflow.py
import omni.isaac.motion_generation as mg from omni.isaac.core.articulations import Articulation class RMPFlowController(mg.MotionPolicyController): def __init__(self, name: str, robot_articulation: Articulation, physics_dt: float = 1.0 / 60.0) -> None: # TODO: chamge the follow paths # laptop self._desc_path = "/home/kimsooyoung/Documents/IssacSimTutorials/rb_issac_tutorial/RoadBalanceEdu/ManipFollowTarget/" self._urdf_path = "/home/kimsooyoung/Downloads/Source/cobotta_pro_900/" self.rmpflow = mg.lula.motion_policies.RmpFlow( robot_description_path=self._desc_path+"rmpflow/robot_descriptor.yaml", rmpflow_config_path=self._desc_path+"rmpflow/denso_rmpflow_common.yaml", urdf_path=self._urdf_path+"cobotta_pro_900.urdf", end_effector_frame_name="onrobot_rg6_base_link", maximum_substep_size=0.00334 ) self.articulation_rmp = mg.ArticulationMotionPolicy(robot_articulation, self.rmpflow, physics_dt) mg.MotionPolicyController.__init__(self, name=name, articulation_motion_policy=self.articulation_rmp) self._default_position, self._default_orientation = ( self._articulation_motion_policy._robot_articulation.get_world_pose() ) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation ) return def reset(self): mg.MotionPolicyController.reset(self) self._motion_policy.set_robot_base_pose( robot_position=self._default_position, robot_orientation=self._default_orientation )
1,686
Python
45.86111
125
0.68446
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/global_variables.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # EXTENSION_TITLE = "MyExtension" EXTENSION_DESCRIPTION = ""
492
Python
36.923074
76
0.802846
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/extension.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from omni.isaac.examples.base_sample import BaseSampleExtension from .robotnik_summit import RobotnikSummit """ This file serves as a basic template for the standard boilerplate operations that make a UI-based extension appear on the toolbar. This implementation is meant to cover most use-cases without modification. Various callbacks are hooked up to a seperate class UIBuilder in .ui_builder.py Most users will be able to make their desired UI extension by interacting solely with UIBuilder. This class sets up standard useful callback functions in UIBuilder: on_menu_callback: Called when extension is opened on_timeline_event: Called when timeline is stopped, paused, or played on_physics_step: Called on every physics step on_stage_event: Called when stage is opened or closed cleanup: Called when resources such as physics subscriptions should be cleaned up build_ui: User function that creates the UI they want. """ class Extension(BaseSampleExtension): def on_startup(self, ext_id: str): super().on_startup(ext_id) super().start_extension( menu_name="RoadBalanceEdu", submenu_name="WheeledRobots", name="RobotnikSummit", title="RobotnikSummit", doc_link="https://docs.omniverse.nvidia.com/isaacsim/latest/core_api_tutorials/tutorial_core_hello_world.html", overview="This Example introduces the user on how to do cool stuff with Isaac Sim through scripting in asynchronous mode.", file_path=os.path.abspath(__file__), sample=RobotnikSummit(), ) return
2,065
Python
42.041666
135
0.742373
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/__init__.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from .extension import Extension
464
Python
45.499995
76
0.814655
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/ui_builder.py
# Copyright (c) 2022-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # import os from typing import List import omni.ui as ui from omni.isaac.ui.element_wrappers import ( Button, CheckBox, CollapsableFrame, ColorPicker, DropDown, FloatField, IntField, StateButton, StringField, TextBlock, XYPlot, ) from omni.isaac.ui.ui_utils import get_style class UIBuilder: def __init__(self): # Frames are sub-windows that can contain multiple UI elements self.frames = [] # UI elements created using a UIElementWrapper from omni.isaac.ui.element_wrappers self.wrapped_ui_elements = [] ################################################################################### # The Functions Below Are Called Automatically By extension.py ################################################################################### def on_menu_callback(self): """Callback for when the UI is opened from the toolbar. This is called directly after build_ui(). """ pass def on_timeline_event(self, event): """Callback for Timeline events (Play, Pause, Stop) Args: event (omni.timeline.TimelineEventType): Event Type """ pass def on_physics_step(self, step): """Callback for Physics Step. Physics steps only occur when the timeline is playing Args: step (float): Size of physics step """ pass def on_stage_event(self, event): """Callback for Stage Events Args: event (omni.usd.StageEventType): Event Type """ pass def cleanup(self): """ Called when the stage is closed or the extension is hot reloaded. Perform any necessary cleanup such as removing active callback functions Buttons imported from omni.isaac.ui.element_wrappers implement a cleanup function that should be called """ # None of the UI elements in this template actually have any internal state that needs to be cleaned up. # But it is best practice to call cleanup() on all wrapped UI elements to simplify development. for ui_elem in self.wrapped_ui_elements: ui_elem.cleanup() def build_ui(self): """ Build a custom UI tool to run your extension. This function will be called any time the UI window is closed and reopened. """ # Create a UI frame that prints the latest UI event. self._create_status_report_frame() # Create a UI frame demonstrating simple UI elements for user input self._create_simple_editable_fields_frame() # Create a UI frame with different button types self._create_buttons_frame() # Create a UI frame with different selection widgets self._create_selection_widgets_frame() # Create a UI frame with different plotting tools self._create_plotting_frame() def _create_status_report_frame(self): self._status_report_frame = CollapsableFrame("Status Report", collapsed=False) with self._status_report_frame: with ui.VStack(style=get_style(), spacing=5, height=0): self._status_report_field = TextBlock( "Last UI Event", num_lines=3, tooltip="Prints the latest change to this UI", include_copy_button=True, ) def _create_simple_editable_fields_frame(self): self._simple_fields_frame = CollapsableFrame("Simple Editable Fields", collapsed=False) with self._simple_fields_frame: with ui.VStack(style=get_style(), spacing=5, height=0): int_field = IntField( "Int Field", default_value=1, tooltip="Type an int or click and drag to set a new value.", lower_limit=-100, upper_limit=100, on_value_changed_fn=self._on_int_field_value_changed_fn, ) self.wrapped_ui_elements.append(int_field) float_field = FloatField( "Float Field", default_value=1.0, tooltip="Type a float or click and drag to set a new value.", step=0.5, format="%.2f", lower_limit=-100.0, upper_limit=100.0, on_value_changed_fn=self._on_float_field_value_changed_fn, ) self.wrapped_ui_elements.append(float_field) def is_usd_or_python_path(file_path: str): # Filter file paths shown in the file picker to only be USD or Python files _, ext = os.path.splitext(file_path.lower()) return ext == ".usd" or ext == ".py" string_field = StringField( "String Field", default_value="Type Here or Use File Picker on the Right", tooltip="Type a string or use the file picker to set a value", read_only=False, multiline_okay=False, on_value_changed_fn=self._on_string_field_value_changed_fn, use_folder_picker=True, item_filter_fn=is_usd_or_python_path, ) self.wrapped_ui_elements.append(string_field) def _create_buttons_frame(self): buttons_frame = CollapsableFrame("Buttons Frame", collapsed=False) with buttons_frame: with ui.VStack(style=get_style(), spacing=5, height=0): button = Button( "Button", "CLICK ME", tooltip="Click This Button to activate a callback function", on_click_fn=self._on_button_clicked_fn, ) self.wrapped_ui_elements.append(button) state_button = StateButton( "State Button", "State A", "State B", tooltip="Click this button to transition between two states", on_a_click_fn=self._on_state_btn_a_click_fn, on_b_click_fn=self._on_state_btn_b_click_fn, physics_callback_fn=None, # See Loaded Scenario Template for example usage ) self.wrapped_ui_elements.append(state_button) check_box = CheckBox( "Check Box", default_value=False, tooltip=" Click this checkbox to activate a callback function", on_click_fn=self._on_checkbox_click_fn, ) self.wrapped_ui_elements.append(check_box) def _create_selection_widgets_frame(self): self._selection_widgets_frame = CollapsableFrame("Selection Widgets", collapsed=False) with self._selection_widgets_frame: with ui.VStack(style=get_style(), spacing=5, height=0): def dropdown_populate_fn(): return ["Option A", "Option B", "Option C"] dropdown = DropDown( "Drop Down", tooltip=" Select an option from the DropDown", populate_fn=dropdown_populate_fn, on_selection_fn=self._on_dropdown_item_selection, ) self.wrapped_ui_elements.append(dropdown) dropdown.repopulate() # This does not happen automatically, and it triggers the on_selection_fn color_picker = ColorPicker( "Color Picker", default_value=[0.69, 0.61, 0.39, 1.0], tooltip="Select a Color", on_color_picked_fn=self._on_color_picked, ) self.wrapped_ui_elements.append(color_picker) def _create_plotting_frame(self): self._plotting_frame = CollapsableFrame("Plotting Tools", collapsed=False) with self._plotting_frame: with ui.VStack(style=get_style(), spacing=5, height=0): import numpy as np x = np.arange(-1, 6.01, 0.01) y = np.sin((x - 0.5) * np.pi) plot = XYPlot( "XY Plot", tooltip="Press mouse over the plot for data label", x_data=[x[:300], x[100:400], x[200:]], y_data=[y[:300], y[100:400], y[200:]], x_min=None, # Use default behavior to fit plotted data to entire frame x_max=None, y_min=-1.5, y_max=1.5, x_label="X [rad]", y_label="Y", plot_height=10, legends=["Line 1", "Line 2", "Line 3"], show_legend=True, plot_colors=[ [255, 0, 0], [0, 255, 0], [0, 100, 200], ], # List of [r,g,b] values; not necessary to specify ) ###################################################################################### # Functions Below This Point Are Callback Functions Attached to UI Element Wrappers ###################################################################################### def _on_int_field_value_changed_fn(self, new_value: int): status = f"Value was changed in int field to {new_value}" self._status_report_field.set_text(status) def _on_float_field_value_changed_fn(self, new_value: float): status = f"Value was changed in float field to {new_value}" self._status_report_field.set_text(status) def _on_string_field_value_changed_fn(self, new_value: str): status = f"Value was changed in string field to {new_value}" self._status_report_field.set_text(status) def _on_button_clicked_fn(self): status = "The Button was Clicked!" self._status_report_field.set_text(status) def _on_state_btn_a_click_fn(self): status = "State Button was Clicked in State A!" self._status_report_field.set_text(status) def _on_state_btn_b_click_fn(self): status = "State Button was Clicked in State B!" self._status_report_field.set_text(status) def _on_checkbox_click_fn(self, value: bool): status = f"CheckBox was set to {value}!" self._status_report_field.set_text(status) def _on_dropdown_item_selection(self, item: str): status = f"{item} was selected from DropDown" self._status_report_field.set_text(status) def _on_color_picked(self, color: List[float]): formatted_color = [float("%0.2f" % i) for i in color] status = f"RGBA Color {formatted_color} was picked in the ColorPicker" self._status_report_field.set_text(status)
11,487
Python
38.888889
112
0.542178
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/robotnik_summit.py
# Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. # # NVIDIA CORPORATION and its licensors retain all intellectual property # and proprietary rights in and to this software, related documentation # and any modifications thereto. Any use, reproduction, disclosure or # distribution of this software and related documentation without an express # license agreement from NVIDIA CORPORATION is strictly prohibited. # from omni.isaac.examples.base_sample import BaseSample from omni.isaac.wheeled_robots.robots import WheeledRobot from omni.isaac.core.utils.types import ArticulationAction from omni.isaac.core.utils.stage import add_reference_to_stage from omni.isaac.core.physics_context.physics_context import PhysicsContext from omni.isaac.core.utils.nucleus import get_assets_root_path, get_url_root from omni.isaac.wheeled_robots.controllers.holonomic_controller import HolonomicController import numpy as np import carb class RobotnikSummit(BaseSample): def __init__(self) -> None: super().__init__() carb.log_info("Check /persistent/isaac/asset_root/default setting") default_asset_root = carb.settings.get_settings().get("/persistent/isaac/asset_root/default") self._server_root = get_url_root(default_asset_root) self._robot_path = self._server_root + "/Projects/RBROS2/WheeledRobot/summit_xl_original.usd" self._wheel_radius = np.array([ 0.127, 0.127, 0.127, 0.127 ]) self._wheel_positions = np.array([ [0.229, 0.235, 0.11], [0.229, -0.235, 0.11], [-0.229, 0.235, 0.11], [-0.229, -0.235, 0.11], ]) self._wheel_orientations = np.array([ # w, x, y, z [0.7071068, 0, 0, 0.7071068], [0.7071068, 0, 0, 0.7071068], [0.7071068, 0, 0, 0.7071068], [0.7071068, 0, 0, 0.7071068], ]) self._mecanum_angles = np.array([ -135.0, -45.0, -45.0, -135.0, ]) self._wheel_axis = np.array([1, 0, 0]) self._up_axis = np.array([0, 0, 1]) return def setup_scene(self): world = self.get_world() world.scene.add_default_ground_plane() add_reference_to_stage(usd_path=self._robot_path, prim_path="/World/Summit") self._wheeled_robot = WheeledRobot( prim_path="/World/Summit/summit_xl_base_link", name="my_summit", wheel_dof_names=[ "summit_xl_front_left_wheel_joint", "summit_xl_front_right_wheel_joint", "summit_xl_back_left_wheel_joint", "summit_xl_back_right_wheel_joint", ], create_robot=True, usd_path=self._robot_path, position=np.array([0, 0.0, 0.02]), orientation=np.array([1.0, 0.0, 0.0, 0.0]), ) self._save_count = 0 self._scene = PhysicsContext() self._scene.set_physics_dt(1 / 30.0) return async def setup_post_load(self): self._world = self.get_world() self._summit_controller = HolonomicController( name="holonomic_controller", wheel_radius=self._wheel_radius, wheel_positions=self._wheel_positions, wheel_orientations=self._wheel_orientations, mecanum_angles=self._mecanum_angles, wheel_axis=self._wheel_axis, up_axis=self._up_axis, ) self._summit_controller.reset() self._wheeled_robot.initialize() self._world.add_physics_callback("sending_actions", callback_fn=self.send_robot_actions) return def send_robot_actions(self, step_size): self._save_count += 1 wheel_action = None if self._save_count >= 0 and self._save_count < 150: wheel_action = self._summit_controller.forward(command=[0.5, 0.0, 0.0]) elif self._save_count >= 150 and self._save_count < 300: wheel_action = self._summit_controller.forward(command=[-0.5, 0.0, 0.0]) elif self._save_count >= 300 and self._save_count < 450: wheel_action = self._summit_controller.forward(command=[0.0, 0.5, 0.0]) elif self._save_count >= 450 and self._save_count < 600: wheel_action = self._summit_controller.forward(command=[0.0, -0.5, 0.0]) elif self._save_count >= 600 and self._save_count < 750: wheel_action = self._summit_controller.forward(command=[0.0, 0.0, 0.5]) elif self._save_count >= 750 and self._save_count < 900: wheel_action = self._summit_controller.forward(command=[0.0, 0.0, -0.5]) else: self._save_count = 0 self._wheeled_robot.apply_wheel_actions(wheel_action) return async def setup_pre_reset(self): if self._world.physics_callback_exists("sim_step"): self._world.remove_physics_callback("sim_step") self._world.pause() return async def setup_post_reset(self): self._summit_controller.reset() await self._world.play_async() self._world.pause() return def world_cleanup(self): self._world.pause() return
5,254
Python
36.535714
101
0.601447
kimsooyoung/rb_issac_tutorial/RoadBalanceEdu/WheeledRobotSummit/README.md
# Loading Extension To enable this extension, run Isaac Sim with the flags --ext-folder {path_to_ext_folder} --enable {ext_directory_name} The user will see the extension appear on the toolbar on startup with the title they specified in the Extension Generator # Extension Usage This template provides the example usage for a library of UIElementWrapper objects that help to quickly develop custom UI tools with minimal boilerplate code. # Template Code Overview The template is well documented and is meant to be self-explanatory to the user should they start reading the provided python files. A short overview is also provided here: global_variables.py: A script that stores in global variables that the user specified when creating this extension such as the Title and Description. extension.py: A class containing the standard boilerplate necessary to have the user extension show up on the Toolbar. This class is meant to fulfill most ues-cases without modification. In extension.py, useful standard callback functions are created that the user may complete in ui_builder.py. ui_builder.py: This file is the user's main entrypoint into the template. Here, the user can see useful callback functions that have been set up for them, and they may also create UI buttons that are hooked up to more user-defined callback functions. This file is the most thoroughly documented, and the user should read through it before making serious modification.
1,488
Markdown
58.559998
132
0.793011
kimsooyoung/rb_issac_tutorial/config/extension.toml
[core] reloadable = true order = 0 [package] version = "1.0.0" category = "Simulation" title = "RoadBalanceEdu" description = "NVIDIA Isaac Sim tutorial Extension" authors = ["RoadBalanceEdu"] repository = "" keywords = [] changelog = "docs/CHANGELOG.md" readme = "docs/README.md" preview_image = "data/preview.png" icon = "data/icon.png" [dependencies] "omni.kit.uiapp" = {} "omni.isaac.ui" = {} "omni.isaac.core" = {} [[python.module]] name = "RoadBalanceEdu.HelloWorld" [[python.module]] name = "RoadBalanceEdu.HelloRobot" [[python.module]] name = "RoadBalanceEdu.HelloManipulator" [[python.module]] name = "RoadBalanceEdu.HelloMultiRobot" [[python.module]] name = "RoadBalanceEdu.HelloMultiTask" [[python.module]] name = "RoadBalanceEdu.HelloCamera" [[python.module]] name = "RoadBalanceEdu.HelloLight" [[python.module]] name = "RoadBalanceEdu.HelloDeformable" [[python.module]] name = "RoadBalanceEdu.FootEnv" [[python.module]] name = "RoadBalanceEdu.FrankaNuts" [[python.module]] name = "RoadBalanceEdu.FrankaNutsTable" [[python.module]] name = "RoadBalanceEdu.FrankaDeformable" [[python.module]] name = "RoadBalanceEdu.URBinFilling" [[python.module]] name = "RoadBalanceEdu.URPalletizing" [[python.module]] name = "RoadBalanceEdu.DingoLibrary" [[python.module]] name = "RoadBalanceEdu.FrankaFactory" [[python.module]] name = "RoadBalanceEdu.ManipGripperControl" [[python.module]] name = "RoadBalanceEdu.ManipFollowTarget" [[python.module]] name = "RoadBalanceEdu.ManipPickandPlace" [[python.module]] name = "RoadBalanceEdu.ManipLULA" [[python.module]] name = "RoadBalanceEdu.MirobotGripperControl" [[python.module]] name = "RoadBalanceEdu.MirobotFollowTarget" [[python.module]] name = "RoadBalanceEdu.MirobotPickandPlace" [[python.module]] name = "RoadBalanceEdu.ManipURGripper" [[python.module]] name = "RoadBalanceEdu.MirobotPickandPlaceROS2" [[python.module]] name = "RoadBalanceEdu.SurfaceGripper" [[python.module]] name = "RoadBalanceEdu.WheeledRobotLimoDiff" [[python.module]] name = "RoadBalanceEdu.WheeledRobotLimoDiffROS2" [[python.module]] name = "RoadBalanceEdu.WheeledRobotLimoAckermannROS2" [[python.module]] name = "RoadBalanceEdu.WheeledRobotLimoAckermannTwistROS2" [[python.module]] name = "RoadBalanceEdu.WheeledRobotsKaya" [[python.module]] name = "RoadBalanceEdu.WheeledRobotSummit" [[python.module]] name = "RoadBalanceEdu.WheeledRobotSummitO3Wheel" [[python.module]] name = "RoadBalanceEdu.WheeledRobotSummitO3WheelROS2" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorCubeRandomRotation" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorSpamRandomPose" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorScatter2D" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorBinwithStuffs" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorFactory" #[[python.module]] #name = "RoadBalanceEdu.ReplicatorFactoryDemo" # [[python.module]] # name = "RoadBalanceEdu.ReplicatorFactoryDemoROS2" [[python.module]] name = "RoadBalanceEdu.ETRIusbA" [[python.module]] name = "RoadBalanceEdu.ETRIcable" [[python.module]] name = "RoadBalanceEdu.ETRIUR10" [[python.module]] name = "RoadBalanceEdu.ETRIFrankaGripper" [[python.module]] name = "RoadBalanceEdu.ETRIUR102F85" #[[python.module]] #name = "RoadBalanceEdu.FrankaFollowTarget" #[[python.module]] #name = "RoadBalanceEdu.FrankaCabinet" [[python.module]] name = "RoadBalanceEdu.LimoDiffROS2" [[python.module]] name = "RoadBalanceEdu.LimoAckermannROS2" [[python.module]] name = "RoadBalanceEdu.SimpleRobotFollowTarget"
3,548
TOML
19.164773
58
0.755637
kimsooyoung/rb_issac_tutorial/docs/CHANGELOG.md
# Changelog ## [0.1.0] - 2024-02-23 ### Added - Initial version of RoadBalanceEdu Extension
95
Markdown
10.999999
45
0.673684