file_path
stringlengths 20
202
| content
stringlengths 9
3.85M
| size
int64 9
3.85M
| lang
stringclasses 9
values | avg_line_length
float64 3.33
100
| max_line_length
int64 8
993
| alphanum_fraction
float64 0.26
0.93
|
---|---|---|---|---|---|---|
AshisGhosh/roboai/isaac_sim/humble_ws/src/robot_api/robot_api/task_manager.py | from enum import Enum
from collections import deque
from uuid import uuid4
import threading
import asyncio
from pathlib import Path
from nicegui import Client, app, ui, ui_run
from abc import ABC, abstractmethod
import copy
# generic ros libraries
import rclpy
from rclpy.node import Node
from rclpy.action import ActionClient
from rclpy.executors import MultiThreadedExecutor
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import Image as ROSImage
from roboai_interfaces.action import MoveArm, ControlGripper, GetGrasp
# RoboAI Interface imports
from starlette.responses import StreamingResponse
from PIL import Image
import io
import numpy as np
def pose_to_list(pose):
return [
pose.position.x,
pose.position.y,
pose.position.z,
pose.orientation.x,
pose.orientation.y,
pose.orientation.z,
pose.orientation.w,
]
class TaskStatus(Enum):
PENDING = "PENDING"
RUNNING = "RUNNING"
SUCCESS = "SUCCESS"
FAILURE = "FAILURE"
ABORTED = "ABORTED"
PAUSED = "PAUSED"
class Task(ABC):
def __init__(self, name, logger=None) -> None:
self.name = name
self.status = TaskStatus.PENDING
self.uuid = uuid4()
self.logger = logger
self.result = None
self.log(f"TASK ({self.uuid}): {self.name} created; Status: {self.status}")
@abstractmethod
def run(self) -> None:
pass
def abort(self) -> None:
self.status = TaskStatus.ABORTED
def update_status(self, status) -> None:
self.status = status
self.log(f"TASK ({self.uuid}): {self.name} updated to: {status}")
def log(self, message) -> None:
if self.logger:
self.logger.info(message)
else:
print(message)
def __str__(self) -> str:
return f"{self.name}; Status: {self.status}"
def __repr__(self) -> str:
return super().__repr__() + f" {self.name}; Status: {self.status}"
class ActionClientTask(Task):
def __init__(self, name, action_client, action_type, logger=None) -> None:
super().__init__(name, logger)
self._action_client = action_client
self.action_type = action_type
self.goal_handle = None
def run(self) -> None:
self.log(f"Sending goal to action server: {self.action_type}")
self.update_status(TaskStatus.RUNNING)
try:
self.send_goal()
except Exception as e:
self.log(f"Error while sending goal: {e}")
self.update_status(TaskStatus.FAILURE)
@abstractmethod
def create_goal_msg(self) -> None:
pass
def send_goal(self) -> None:
goal_msg = self.create_goal_msg()
self._action_client.wait_for_server(timeout_sec=1)
future = self._action_client.send_goal_async(goal_msg)
future.add_done_callback(self.goal_response_callback)
def goal_response_callback(self, future) -> None:
self.goal_handle = future.result()
if not self.goal_handle.accepted:
self.log("Goal rejected :(")
self.update_status(TaskStatus.FAILURE)
return
self.log("Goal accepted :)")
# Wait for the result
result_future = self.goal_handle.get_result_async()
result_future.add_done_callback(self.get_result_callback)
def get_result_callback(self, future) -> None:
self.result = future.result().result
self.log(f"Result received: {self.result}, {type(self.result.status)}")
if self.result.status == "SUCCEEDED":
self.log(f"Result received: {self.result.message}")
self.update_status(TaskStatus.SUCCESS)
else:
self.log(f"Action did not succeed with status: {self.result.status}")
self.update_status(TaskStatus.FAILURE)
def abort(self) -> None:
if self.goal_handle:
self.goal_handle.cancel_goal()
self._action_client._cancel_goal(self.goal_handle)
super().abort()
class MoveArmTask(ActionClientTask):
def __init__(
self, name, goal: str | list[float], action_client, logger=None
) -> None:
super().__init__(name, action_client, MoveArm, logger=None)
self.goal = goal
def create_goal_msg(self) -> None:
goal_msg = MoveArm.Goal()
if isinstance(self.goal, str):
goal_msg.configuration_goal = self.goal
elif isinstance(self.goal, list):
if len(self.goal) == 6:
goal_msg.joint_goal = self.goal
elif len(self.goal) == 7:
goal_msg.cartesian_goal = self.goal
else:
raise ValueError(
f"Invalid goal length: {self.goal}, length: {len(self.goal)}"
)
elif isinstance(self.goal, PoseStamped):
goal_msg.cartesian_pose_goal = self.goal
else:
raise ValueError(f"Invalid goal: {self.goal}, type: {type(self.goal)}")
return goal_msg
class ControlGripperTask(ActionClientTask):
def __init__(self, name, goal: str, action_client, logger=None) -> None:
super().__init__(name, action_client, ControlGripper, logger=None)
self.goal = goal
def create_goal_msg(self) -> None:
goal_msg = ControlGripper.Goal()
if isinstance(self.goal, str):
goal_msg.goal_state = self.goal
else:
raise ValueError(f"Invalid goal: {self.goal}")
return goal_msg
class GetGraspTask(ActionClientTask):
def __init__(
self, name, goal_object: str, action_client, task_vars, logger=None
) -> None:
super().__init__(name, action_client, GetGrasp, logger=None)
self.goal_object = goal_object
self.task_vars = task_vars
def create_goal_msg(self) -> None:
goal_msg = GetGrasp.Goal()
if isinstance(self.goal_object, str):
goal_msg.object_name = self.goal_object
else:
raise ValueError(f"Invalid goal: {self.goal_object}")
return goal_msg
def get_result_callback(self, future) -> None:
self.result = future.result().result
self.log(f"Result received: {self.result}")
if self.result.success:
self.log("Grasp received")
self.update_status(TaskStatus.SUCCESS)
self.task_vars["grasp_pose"] = self.result.grasp
else:
self.log("Grasp not received")
self.update_status(TaskStatus.FAILURE)
class PlannerTask(Task):
def __init__(self, name, task_manager, task_vars, logger=None) -> None:
super().__init__(name, logger)
self.task_manager = task_manager
self.states = []
self.current_state = None
self.task_vars = task_vars
def run(self) -> None:
self.log(f"Running planner: {self.name}")
self.update_status(TaskStatus.RUNNING)
try:
self.plan()
except Exception as e:
self.log(f"Error while planning: {e}")
self.update_status(TaskStatus.FAILURE)
def get_next_state(self) -> str:
if self.current_state is None:
self.current_state = self.states.pop(0)
else:
self.current_state = self.states[self.states.index(self.current_state) + 1]
return self.current_state
@abstractmethod
def plan(self) -> None:
pass
class PickTask(PlannerTask):
def __init__(
self,
name,
task_manager,
task_vars,
object_name,
current_state=None,
logger=None,
) -> None:
super().__init__(name, task_manager, task_vars, logger)
self.object_name = object_name
self.states = [
"get_grasp",
"execute_grasp",
"move_to_ready",
]
self.current_state = current_state or self.states[0]
def plan(self) -> None:
self.log(f"Running pick task: {self.name}")
self.update_status(TaskStatus.RUNNING)
if self.current_state == "get_grasp":
task = self.task_manager.add_task(
GetGraspTask(
name=f"Get grasp for {self.object_name}",
goal_object=self.object_name,
action_client=self.task_manager.get_grasp_action_client,
task_vars=self.task_vars,
),
after=self,
)
self.add_next_plan(after=task)
self.update_status(TaskStatus.SUCCESS)
return
if self.current_state == "execute_grasp":
grasp = copy.deepcopy(self.task_vars["grasp_pose"])
gripper_grasp = copy.deepcopy(grasp)
gripper_grasp.pose.position.z += 0.09
pre_grasp = copy.deepcopy(gripper_grasp)
pre_grasp.pose.position.z += 0.2
task = self.task_manager.add_task_to_move_to_position(
pre_grasp, name="Move to pregrasp", after=self
)
task = self.task_manager.add_task_to_control_gripper(
"open", name="Open gripper", after=task
)
task = self.task_manager.add_task_to_move_to_position(
gripper_grasp, name="Move to grasp", after=task
)
task = self.task_manager.add_task_to_control_gripper(
"close", name="Close gripper", after=task
)
task = self.task_manager.add_task_to_move_to_position(
pre_grasp, name="Move to pregrasp", after=task
)
self.add_next_plan(after=task)
self.update_status(TaskStatus.SUCCESS)
return
if self.current_state == "move_to_ready":
self.task_manager.add_task(
MoveArmTask(
name="Move to ready",
goal="ready",
action_client=self.task_manager.move_arm_action_client,
),
after=self,
)
self.update_status(TaskStatus.SUCCESS)
return
def add_next_plan(self, after: Task = None) -> None:
next_state = self.get_next_state()
self.task_manager.add_task(
PickTask(
name=f"Pick {self.object_name} - {next_state}",
task_manager=self.task_manager,
task_vars=self.task_vars,
object_name=self.object_name,
current_state=next_state,
),
after=after,
)
class TaskManager(Node):
def __init__(self) -> None:
super().__init__("task_manager")
self.tasks = deque()
self.current_task = None
self.task_history = []
self.task_vars = {}
self.move_arm_action_client = ActionClient(self, MoveArm, "/move_arm")
self.control_gripper_action_client = ActionClient(
self, ControlGripper, "/control_gripper"
)
self.get_grasp_action_client = ActionClient(self, GetGrasp, "/get_grasp")
self.setup_gui()
self.get_logger().info("Task Manager initialized")
self.add_task(
MoveArmTask(
name="Move to extended",
goal="extended",
action_client=self.move_arm_action_client,
)
)
self.add_task(
ControlGripperTask(
name="Open gripper",
goal="open",
action_client=self.control_gripper_action_client,
)
)
self.add_task(
MoveArmTask(
name="Move to ready",
goal="ready",
action_client=self.move_arm_action_client,
)
)
self.add_task(
ControlGripperTask(
name="Close gripper",
goal="close",
action_client=self.control_gripper_action_client,
)
)
def setup_gui(self) -> None:
with Client.auto_index_client:
ui.label("Task Manager").style("font-size: 24px")
self.grid = ui.aggrid(
{
"defaultColDef": {"flex": 1},
"columnDefs": [
{"headerName": "Name", "field": "name", "sortable": True},
{"headerName": "Status", "field": "status", "sortable": True},
],
"rowData": [],
},
).classes("h-96")
self.update_grid()
arm_positions = ["extended", "ready", "pick_center", "drop"]
self.position_input = ui.input(
label="Enter Move Arm position:",
placeholder=f"{', '.join(arm_positions)}",
autocomplete=arm_positions,
)
ui.button(
"Add Move Arm Task (Configuration)",
on_click=self.add_move_arm_task_click,
)
gripper_positions = ["open", "close"]
self.gripper_position_input = ui.input(
label="Enter Control Gripper position:",
placeholder=f"{', '.join(gripper_positions)}",
autocomplete=gripper_positions,
)
ui.button(
"Add Control Gripper Task", on_click=self.add_control_gripper_task_click
)
self.numerical_list_input = ui.input(
label="Enter cartesian position as list of 7 numbers separated by commas:",
placeholder="x, y, z, qx, qy, qz, qw",
)
ui.button(
"Add Move Arm Task (Cartesian)",
on_click=self.add_move_arm_task_cartesian_click,
)
ui.button("Add Pick Tasks", on_click=self.add_pick_tasks_click)
ui.button(
"Run Tasks", on_click=lambda: asyncio.create_task(self.run_tasks())
)
ui.button(
"Abort Current Task",
on_click=lambda: asyncio.create_task(self.abort_current_task()),
)
ui.button("Clear Tasks", on_click=self.clear_tasks)
ui.button("Retry Last Task", on_click=self.retry_last_task)
def update_grid(self) -> None:
task_dict = [
{"name": task.name, "status": task.status} for task in self.task_history
] + [{"name": task.name, "status": task.status} for task in self.tasks]
self.grid.options["rowData"] = task_dict
self.get_logger().debug(f"{task_dict}")
self.grid.update()
def add_move_arm_task_click(self, event):
position = (
self.position_input.value
) # Get the current value from the input field
self.add_task_to_move_to_position(position)
def add_task_to_move_to_position(
self,
position: str | list[float] | PoseStamped,
name: str = None,
after: Task = None,
) -> None:
if name is None:
name = f"Move to {position}"
return self.add_task(
MoveArmTask(
name=name,
goal=position,
action_client=self.move_arm_action_client,
),
after=after,
)
def add_control_gripper_task_click(self, event):
position = self.gripper_position_input.value
self.add_task_to_control_gripper(position)
def add_task_to_control_gripper(
self, position: str, name=None, after: Task = None
) -> None:
if name is None:
name = f"Control gripper to {position}"
return self.add_task(
ControlGripperTask(
name=f"Control gripper to {position}",
goal=position,
action_client=self.control_gripper_action_client,
),
after=after,
)
def add_move_arm_task_cartesian_click(self, event):
position = [float(x) for x in self.numerical_list_input.value.split(",")]
self.add_task_to_move_to_position(
position, name=f"Move to cartesian {position}"
)
def add_pick_tasks_click(self, event):
# position = [0.5, 0.1, 0.3, 0.924, -0.383, 0.0, 0.0]
# self.add_pick_tasks(position)
self.add_task(
PickTask(
name="Pick task",
task_manager=self,
task_vars=self.task_vars,
object_name="cereal",
)
)
def add_pick_tasks(self, grasp_pose: list[float]) -> None:
pre_grasp = grasp_pose.copy()
pre_grasp[2] += 0.1
self.add_task_to_move_to_position(pre_grasp)
self.add_task_to_control_gripper("open")
self.add_task_to_move_to_position(grasp_pose)
self.add_task_to_control_gripper("close")
self.add_task_to_move_to_position(pre_grasp)
self.add_task_to_move_to_position("ready")
def add_task(self, task: Task, after: Task = None) -> None:
task.logger = self.get_logger()
if after:
if after in self.tasks:
self.tasks.insert(self.tasks.index(after) + 1, task)
elif after in self.task_history:
self.tasks.insert(0, task)
else:
self.get_logger().error(f"Task not found: {after}, cannot add task.")
else:
self.tasks.append(task)
self.update_grid()
self.get_logger().info(f"Task added: {task}")
return task
def remove_task(self, task: Task) -> None:
self.tasks.remove(task)
self.update_grid()
self.get_logger().info(f"Task removed: {task}")
def clear_tasks(self) -> None:
self.tasks.clear()
self.task_history.clear()
self.update_grid()
self.get_logger().info("Tasks cleared")
def retry_last_task(self) -> None:
if self.task_history:
self.retry_task(self.task_history[-1])
else:
self.get_logger().info("No tasks in history to retry")
def retry_task(self, task: Task) -> None:
self.task_history.remove(task)
task.status = TaskStatus.PENDING
self.tasks.appendleft(task)
self.update_grid()
self.get_logger().info(f"Task retried: {task}")
async def run_tasks(self) -> None:
while self.tasks:
self.set_current_task(self.tasks.popleft())
self.current_task.run()
self.update_grid()
while self.current_task.status == TaskStatus.RUNNING:
await asyncio.sleep(0.1)
if self.current_task.status in [TaskStatus.ABORTED, TaskStatus.FAILURE]:
self.get_logger().error(f"Task failed: {self.current_task}")
self.update_grid()
return
self.set_current_task(None)
self.get_logger().info("All tasks completed")
def set_current_task(self, task: Task | None) -> None:
self.current_task = task
if task:
self.task_history.append(task)
self.get_logger().info(f"Current task: {task}")
self.update_grid()
async def abort_current_task(self) -> None:
if self.current_task:
self.current_task.abort()
self.get_logger().info(f"Current task aborted: {self.current_task}")
else:
self.get_logger().info("No current task to abort")
def get_tasks(self) -> deque[Task]:
return self.tasks
def destroy_node(self) -> None:
self.move_arm_action_client.destroy()
self.abort_current_task()
super().destroy_node()
global agentview_image
global task_manager
class RoboAIInterface(Node):
def __init__(self, task_manager: TaskManager):
super().__init__("roboai_interface")
self.task_manager = task_manager
self.agentview_image = None
self.create_subscription(
ROSImage,
"/agentview/rgb",
self.image_callback,
10,
)
self.get_logger().info("RoboAI Interface initialized")
def image_callback(self, msg: ROSImage) -> None:
self.agentview_image = msg
global agentview_image
agentview_image = msg
@classmethod
@app.get("/get_image")
async def get_image() -> str:
if agentview_image:
# return base64.b64encode(agentview_image.data).decode("utf-8")
# Image.frombytes("RGB", (agentview_image.width, agentview_image.height), agentview_image.data)
print(f"Image type: {type(agentview_image.data)}")
img_array = np.frombuffer(agentview_image.data, np.uint8).reshape(
agentview_image.height, agentview_image.width, 3
)
img = Image.fromarray(img_array)
buf = io.BytesIO()
img.save(buf, format="PNG")
buf.seek(0)
return StreamingResponse(buf, media_type="image/png")
return None
@classmethod
@app.post("/add_task")
async def add_task(task: str) -> None:
if task == "pick":
task_manager.add_task(
PickTask(
name="Pick task",
task_manager=task_manager,
task_vars=task_manager.task_vars,
object_name="cereal",
)
)
return True
return False
@app.post("/run_tasks")
async def run_tasks() -> None:
asyncio.create_task(task_manager.run_tasks())
def destroy_node(self):
self.task_manager.destroy_node()
super().destroy_node()
def main() -> None:
# NOTE: This function is defined as the ROS entry point in setup.py, but it's empty to enable NiceGUI auto-reloading
# https://github.com/zauberzeug/nicegui/blob/main/examples/ros2/ros2_ws/src/gui/gui/node.py
pass
def ros_main() -> None:
rclpy.init()
global task_manager
task_manager = TaskManager()
executor = MultiThreadedExecutor()
executor.add_node(task_manager)
task_manager.get_logger().info("Task Manager started")
roboai_interface = RoboAIInterface(task_manager)
executor.add_node(roboai_interface)
task_manager.get_logger().info("RoboAI Interface started")
try:
executor.spin()
finally:
task_manager.destroy_node()
roboai_interface.destroy_node()
rclpy.shutdown()
app.on_startup(lambda: threading.Thread(target=ros_main).start())
ui_run.APP_IMPORT_STRING = f"{__name__}:app" # ROS2 uses a non-standard module name, so we need to specify it here
ui.run(uvicorn_reload_dirs=str(Path(__file__).parent.resolve()), favicon="🤖")
| 22,691 | Python | 32.224012 | 120 | 0.561236 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/robot_api/robot_api/manipulation.py | import time
from typing import List
from dataclasses import dataclass
# generic ros libraries
import rclpy
from tf2_ros import Buffer, TransformListener
from tf2_ros import LookupException, ConnectivityException, ExtrapolationException
from tf2_geometry_msgs import do_transform_pose_stamped
# moveit python library
from moveit.core.robot_state import RobotState
from moveit.planning import (
MoveItPy,
PlanRequestParameters,
)
from rclpy.node import Node
from geometry_msgs.msg import PoseStamped, Pose
from moveit_msgs.msg import Constraints
from rclpy.action import ActionServer, CancelResponse, GoalResponse, ActionClient
from control_msgs.action import GripperCommand
from visualization_msgs.msg import Marker
from roboai_interfaces.action import MoveArm, ControlGripper
@dataclass
class ArmState:
JOINT_VALUES = "joint_values"
POSE = "pose"
name: str
type: str
joint_values: List[float | int] | None = None
pose: List[float | int] | None = None
def __post_init__(self):
if self.joint_values is not None and self.pose is not None:
raise ValueError("Only one of joint_values or pose can be set")
if self.joint_values is None and self.pose is None:
raise ValueError("Either joint_values or pose must be set")
@classmethod
def get_pose_array_as_pose(self, pose_array: List[float | int]) -> Pose:
pose = Pose()
pose.position.x = pose_array[0]
pose.position.y = pose_array[1]
pose.position.z = pose_array[2]
pose.orientation.x = pose_array[3]
pose.orientation.y = pose_array[4]
pose.orientation.z = pose_array[5]
pose.orientation.w = pose_array[6]
return pose
@classmethod
def get_pose_array_as_pose_stamped(
self, pose_array: List[float | int]
) -> PoseStamped:
pose_stamped = PoseStamped()
pose_stamped.pose = self.get_pose_array_as_pose(pose_array)
return pose_stamped
# Arm states
# LOOK_DOWN_QUAT = [0.924, -0.383, 0.0, 0.0]
LOOK_DOWN_QUAT = [1.0, 0.0, 0.0, 0.0]
PICK_CENTER = ArmState(
name="pick_center", type=ArmState.POSE, pose=[0.5, 0.0, 0.5, *LOOK_DOWN_QUAT]
)
DROP = ArmState(name="drop", type=ArmState.POSE, pose=[0.5, -0.5, 0.5, *LOOK_DOWN_QUAT])
ARM_STATE_LIST = [PICK_CENTER, DROP]
ARM_STATES = {state.name: state for state in ARM_STATE_LIST}
class ManipulationAPI(Node):
def __init__(
self,
robot_arm_planning_component="panda_arm",
robot_arm_eef_link="panda_hand",
):
super().__init__("manipulation_api")
moveit_config = self._get_moveit_config()
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.robot_arm_planning_component_name = robot_arm_planning_component
self.robot_arm_eef_link = robot_arm_eef_link
self.robot = MoveItPy(node_name="moveit_py", config_dict=moveit_config)
self.robot_arm_planning_component = self.robot.get_planning_component(
self.robot_arm_planning_component_name
)
self._action_server = ActionServer(
self,
MoveArm,
"move_arm",
execute_callback=self.execute_callback,
goal_callback=self.goal_callback,
cancel_callback=self.cancel_callback,
)
self._last_gripper_result = None
self._gripper_action_client = ActionClient(
self, GripperCommand, "/panda_hand_controller/gripper_cmd"
)
self._gripper_action_server = ActionServer(
self,
ControlGripper,
"control_gripper",
execute_callback=self.gripper_execute_callback,
goal_callback=self.gripper_goal_callback,
cancel_callback=self.cancel_callback,
)
self.cartesian_goal_marker_publisher = self.create_publisher(
Marker, "cartesian_goal_marker", 10
)
self.get_logger().info("Manipulation API initialized")
def _get_moveit_config(self):
from moveit_configs_utils import MoveItConfigsBuilder
from ament_index_python.packages import get_package_share_directory
moveit_config = (
MoveItConfigsBuilder(
robot_name="panda", package_name="moveit_resources_panda_moveit_config"
)
.robot_description(file_path="config/panda.urdf.xacro")
.trajectory_execution(file_path="config/gripper_moveit_controllers.yaml")
.moveit_cpp(
file_path=get_package_share_directory("robot_api")
+ "/config/moveit_franka_python.yaml"
)
.to_moveit_configs()
)
moveit_config = moveit_config.to_dict()
return moveit_config
def destroy(self):
self._action_server.destroy()
super().destroy_node()
def goal_callback(self, goal_request):
"""Accept or reject a client request to begin an action."""
# This server allows multiple goals in parallel
self.get_logger().info("Received goal request")
return GoalResponse.ACCEPT
def cancel_callback(self, goal_handle):
"""Accept or reject a client request to cancel an action."""
# TODO: Implement cancel
self.get_logger().info("Received cancel request")
self.get_logger().error("Cancel not implemented")
return CancelResponse.REJECT
def execute_callback(self, goal_handle):
goal = goal_handle.request
self.get_logger().info(f"Received goal: {goal}")
result = MoveArm.Result()
status = self.move_arm(
goal.configuration_goal,
goal.cartesian_goal,
goal.joint_goal,
goal.constraints_goal,
goal.cartesian_pose_goal,
goal.start_state,
)
self.get_logger().info(f"Move arm status: {status.status}")
result.status = status.status
if result.status == "SUCCEEDED":
goal_handle.succeed()
else:
goal_handle.abort()
return result
def gripper_goal_callback(self, goal_request):
"""Accept or reject a client request to begin an action."""
self.get_logger().info("Received gripper goal request")
return GoalResponse.ACCEPT
def gripper_execute_callback(self, goal_handle):
goal = goal_handle.request
self.get_logger().info(f"Received gripper goal: {goal}")
result = ControlGripper.Result()
status = self.control_gripper(goal.goal_state)
self.get_logger().info(f"Gripper status: {status}")
result.status = status
if result.status == "SUCCEEDED":
goal_handle.succeed()
else:
goal_handle.abort()
return result
def publish_cartesian_goal_marker(self, pose_stamped: PoseStamped):
marker = Marker()
marker.header = pose_stamped.header
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.pose = pose_stamped.pose
marker.scale.x = 0.1
marker.scale.y = 0.01
marker.scale.z = 0.01
marker.color.a = 1.0
marker.color.r = 1.0
marker.color.g = 0.0
marker.color.b = 0.0
self.cartesian_goal_marker_publisher.publish(marker)
def plan(
self,
goal_state,
start_state=None,
):
self.get_logger().info("Planning trajectory")
self.get_logger().info(
f"Goal state: {goal_state} type {type(goal_state)}: {isinstance(goal_state, str)}"
)
plan_request_parameters = None
if start_state is None:
self.robot_arm_planning_component.set_start_state_to_current_state()
else:
self.robot_arm_planning_component.set_start_state(robot_state=start_state)
if isinstance(goal_state, str):
self.get_logger().info(f"Setting goal state to {goal_state}")
self.robot_arm_planning_component.set_goal_state(
configuration_name=goal_state
)
elif isinstance(goal_state, RobotState):
self.robot_arm_planning_component.set_goal_state(robot_state=goal_state)
elif isinstance(goal_state, PoseStamped):
self.robot_arm_planning_component.set_goal_state(
pose_stamped_msg=goal_state, pose_link=self.robot_arm_eef_link
)
plan_request_parameters = PlanRequestParameters(
self.robot, "pilz_industrial_motion_planner"
)
plan_request_parameters.planning_time = 1.0
plan_request_parameters.planning_attempts = 1
plan_request_parameters.max_velocity_scaling_factor = 0.1
plan_request_parameters.max_acceleration_scaling_factor = 0.1
plan_request_parameters.planning_pipeline = "pilz_industrial_motion_planner"
plan_request_parameters.planner_id = "PTP"
elif isinstance(goal_state, Constraints):
self.robot_arm_planning_component.set_goal_state(
motion_plan_constraints=[goal_state]
)
elif isinstance(goal_state, list):
self.robot_arm_planning_component.set_goal_state(
motion_plan_constraints=goal_state
)
else:
raise ValueError("Invalid goal state type")
self.get_logger().info(
f"Planning trajectory for goal of type {type(goal_state)}"
)
start_time = time.time()
if plan_request_parameters is not None:
plan_result = self.robot_arm_planning_component.plan(
single_plan_parameters=plan_request_parameters
)
else:
plan_result = self.robot_arm_planning_component.plan()
end_time = time.time()
self.get_logger().info("Planning completed")
self.get_logger().info(f"Planning time: {end_time - start_time}")
return plan_result
def execute(self, trajectory):
self.get_logger().info("Executing trajectory")
return self.robot.execute(trajectory, controllers=[])
# execution_manager = self.robot.get_trajactory_execution_manager()
# current_status = execution_manager.get_execution_status()
# # https://moveit.picknik.ai/main/api/html/structmoveit__controller__manager_1_1ExecutionStatus.html
def move_arm(
self,
configuration_goal=None,
cartesian_goal=None,
joint_goal=None,
constraints_goal=None,
cartesian_pose_goal=None,
start_state=None,
):
self.get_logger().info("Moving arm")
if start_state:
raise NotImplementedError("Custom start state not implemented")
if configuration_goal:
if configuration_goal in ["extended", "ready"]:
goal_state = configuration_goal
elif configuration_goal in ARM_STATES:
goal_state = ARM_STATES[configuration_goal]
if goal_state.type == ArmState.JOINT_VALUES:
return self.move_arm(joint_goal=goal_state.joint_values)
elif goal_state.type == ArmState.POSE:
return self.move_arm(cartesian_goal=goal_state.pose)
else:
raise ValueError("Invalid configuration goal")
elif cartesian_goal:
pose_stamped = PoseStamped()
pose_stamped.header.frame_id = "panda_link0"
pose_stamped.pose = ArmState.get_pose_array_as_pose(cartesian_goal)
goal_state = pose_stamped
self.publish_cartesian_goal_marker(goal_state)
elif joint_goal:
robot_model = self.robot.get_robot_model()
robot_state = RobotState(robot_model)
robot_state.set_joint_group_positions(
self.robot_arm_planning_component_name, joint_goal
)
goal_state = robot_state
elif constraints_goal:
raise NotImplementedError("Constraints goal not implemented")
goal_state = constraints_goal
elif cartesian_pose_goal:
goal_state = cartesian_pose_goal
if goal_state.header.frame_id == "":
goal_state.header.frame_id = "panda_link0"
if goal_state.header.frame_id != "panda_link0":
self.get_logger().warn(
f"Transforming goal state from {goal_state.header.frame_id} to panda_link0"
)
self.get_logger().info(f"Goal state: {type(goal_state)}")
try:
transform = self.tf_buffer.lookup_transform(
"panda_link0",
goal_state.header.frame_id,
goal_state.header.stamp,
timeout=rclpy.duration.Duration(seconds=1),
)
goal_state = do_transform_pose_stamped(goal_state, transform)
except (
LookupException,
ConnectivityException,
ExtrapolationException,
) as e:
self.get_logger().error(f"Failed to transform point: {str(e)}")
self.publish_cartesian_goal_marker(goal_state)
else:
raise ValueError("No goal state provided")
plan_result = self.plan(goal_state)
return self.execute(plan_result.trajectory)
def gripper_send_goal(self, goal: str):
goal_msg = GripperCommand.Goal()
goal_msg.command.position = 0.04 if goal == "open" else 0.0
self._gripper_action_client.wait_for_server(timeout_sec=1)
future = self._gripper_action_client.send_goal_async(goal_msg)
future.add_done_callback(self.goal_response_callback)
def goal_response_callback(self, future) -> None:
self.goal_handle = future.result()
if not self.goal_handle.accepted:
self.get_logger().error("Goal rejected :(")
return
self.get_logger().info("Goal accepted :)")
# Wait for the result
result_future = self.goal_handle.get_result_async()
result_future.add_done_callback(self.gripper_get_result_callback)
def gripper_get_result_callback(self, future) -> None:
result = future.result().result
self.get_logger().info(
f"Result received: {result}, reached goal: {result.reached_goal}, stalled: {result.stalled}"
)
if result.reached_goal or result.stalled:
self.get_logger().info("Gripper command success.")
else:
self.get_logger().error("Gripper command failed.")
self._last_gripper_result = result
def control_gripper(self, goal: str):
self._last_gripper_result = None
if goal not in ["open", "close"]:
raise ValueError("Invalid gripper goal")
self.get_logger().info(f"Control gripper to {goal}")
self.gripper_send_goal(goal)
while self._last_gripper_result is None:
rclpy.spin_once(self, timeout_sec=0.1)
self.get_logger().info(f"Result: {self._last_gripper_result}")
return "SUCCEEDED"
def main():
rclpy.init()
node = ManipulationAPI()
try:
while True:
rclpy.spin_once(node)
except KeyboardInterrupt:
node.get_logger().info("Shutting down")
node.destroy()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 15,500 | Python | 36.172662 | 109 | 0.608968 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/robot_api/robot_api/manipulation_example.py | #!/usr/bin/env python3
"""
A script to outline the fundamentals of the moveit_py motion planning API.
"""
import time
# generic ros libraries
import rclpy
from rclpy.logging import get_logger
# moveit python library
from moveit.core.robot_state import RobotState
from moveit.planning import (
MoveItPy,
MultiPipelinePlanRequestParameters,
)
def plan_and_execute(
robot,
planning_component,
logger,
single_plan_parameters=None,
multi_plan_parameters=None,
sleep_time=0.0,
):
"""Helper function to plan and execute a motion."""
# plan to goal
logger.info("Planning trajectory")
if multi_plan_parameters is not None:
plan_result = planning_component.plan(
multi_plan_parameters=multi_plan_parameters
)
elif single_plan_parameters is not None:
plan_result = planning_component.plan(
single_plan_parameters=single_plan_parameters
)
else:
plan_result = planning_component.plan()
# execute the plan
if plan_result:
logger.info("Executing plan")
robot_trajectory = plan_result.trajectory
robot.execute(robot_trajectory, controllers=[])
else:
logger.error("Planning failed")
time.sleep(sleep_time)
def main():
###################################################################
# MoveItPy Setup
###################################################################
rclpy.init()
logger = get_logger("moveit_py.pose_goal")
from moveit_configs_utils import MoveItConfigsBuilder
from ament_index_python.packages import get_package_share_directory
moveit_config = (
MoveItConfigsBuilder(
robot_name="panda", package_name="moveit_resources_panda_moveit_config"
)
.robot_description(file_path="config/panda.urdf.xacro")
.trajectory_execution(file_path="config/gripper_moveit_controllers.yaml")
.moveit_cpp(
file_path=get_package_share_directory("robot_api")
+ "/config/moveit_franka_python.yaml"
)
.to_moveit_configs()
)
moveit_config = moveit_config.to_dict()
# instantiate MoveItPy instance and get planning component
panda = MoveItPy(node_name="moveit_py", config_dict=moveit_config)
panda_arm = panda.get_planning_component("panda_arm")
logger.info("MoveItPy instance created")
###########################################################################
# Plan 1 - set states with predefined string
###########################################################################
# set plan start state using predefined state
panda_arm.set_start_state(configuration_name="ready")
# set pose goal using predefined state
panda_arm.set_goal_state(configuration_name="extended")
# plan to goal
plan_and_execute(panda, panda_arm, logger, sleep_time=3.0)
###########################################################################
# Plan 2 - set goal state with RobotState object
###########################################################################
# instantiate a RobotState instance using the current robot model
robot_model = panda.get_robot_model()
robot_state = RobotState(robot_model)
# randomize the robot state
robot_state.set_to_random_positions()
# set plan start state to current state
panda_arm.set_start_state_to_current_state()
# set goal state to the initialized robot state
logger.info("Set goal state to the initialized robot state")
panda_arm.set_goal_state(robot_state=robot_state)
# plan to goal
plan_and_execute(panda, panda_arm, logger, sleep_time=3.0)
###########################################################################
# Plan 3 - set goal state with PoseStamped message
###########################################################################
# set plan start state to current state
panda_arm.set_start_state_to_current_state()
# set pose goal with PoseStamped message
from geometry_msgs.msg import PoseStamped
pose_goal = PoseStamped()
pose_goal.header.frame_id = "panda_link0"
pose_goal.pose.orientation.w = 1.0
pose_goal.pose.position.x = 0.28
pose_goal.pose.position.y = -0.2
pose_goal.pose.position.z = 0.5
panda_arm.set_goal_state(pose_stamped_msg=pose_goal, pose_link="panda_link8")
# plan to goal
plan_and_execute(panda, panda_arm, logger, sleep_time=3.0)
###########################################################################
# Plan 4 - set goal state with constraints
###########################################################################
# set plan start state to current state
panda_arm.set_start_state_to_current_state()
# set constraints message
from moveit.core.kinematic_constraints import construct_joint_constraint
joint_values = {
"panda_joint1": -1.0,
"panda_joint2": 0.7,
"panda_joint3": 0.7,
"panda_joint4": -1.5,
"panda_joint5": -0.7,
"panda_joint6": 2.0,
"panda_joint7": 0.0,
}
robot_state.joint_positions = joint_values
joint_constraint = construct_joint_constraint(
robot_state=robot_state,
joint_model_group=panda.get_robot_model().get_joint_model_group("panda_arm"),
)
panda_arm.set_goal_state(motion_plan_constraints=[joint_constraint])
# plan to goal
plan_and_execute(panda, panda_arm, logger, sleep_time=3.0)
###########################################################################
# Plan 5 - Planning with Multiple Pipelines simultaneously
###########################################################################
# set plan start state to current state
panda_arm.set_start_state_to_current_state()
# set pose goal with PoseStamped message
panda_arm.set_goal_state(configuration_name="ready")
# initialise multi-pipeline plan request parameters
multi_pipeline_plan_request_params = MultiPipelinePlanRequestParameters(
panda, ["ompl_rrtc", "pilz_lin", "chomp_planner"]
)
# plan to goal
plan_and_execute(
panda,
panda_arm,
logger,
multi_plan_parameters=multi_pipeline_plan_request_params,
sleep_time=3.0,
)
if __name__ == "__main__":
main()
| 6,354 | Python | 31.927461 | 85 | 0.572081 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/robot_api/config/moveit_franka_python.yaml | planning_scene_monitor_options:
name: "planning_scene_monitor"
robot_description: "robot_description"
joint_state_topic: "/joint_states"
attached_collision_object_topic: "/moveit_cpp/planning_scene_monitor"
publish_planning_scene_topic: "/moveit_cpp/publish_planning_scene"
monitored_planning_scene_topic: "/moveit_cpp/monitored_planning_scene"
wait_for_initial_state_timeout: 10.0
planning_pipelines:
pipeline_names: ["ompl", "pilz_industrial_motion_planner", "chomp"]
plan_request_params:
planning_attempts: 1
planning_pipeline: ompl
max_velocity_scaling_factor: 1.0
max_acceleration_scaling_factor: 1.0
ompl_rrtc: # Namespace for individual plan request
plan_request_params: # PlanRequestParameters similar to the ones that are used by the single pipeline planning of moveit_cpp
planning_attempts: 1 # Number of attempts the planning pipeline tries to solve a given motion planning problem
planning_pipeline: ompl # Name of the pipeline that is being used
planner_id: "RRTConnectkConfigDefault" # Name of the specific planner to be used by the pipeline
max_velocity_scaling_factor: 1.0 # Velocity scaling parameter for the trajectory generation algorithm that is called (if configured) after the path planning
max_acceleration_scaling_factor: 1.0 # Acceleration scaling parameter for the trajectory generation algorithm that is called (if configured) after the path planning
planning_time: 1.0 # Time budget for the motion plan request. If the planning problem cannot be solved within this time, an empty solution with error code is returned
pilz_lin:
plan_request_params:
planning_attempts: 1
planning_pipeline: pilz_industrial_motion_planner
planner_id: "PTP"
max_velocity_scaling_factor: 1.0
max_acceleration_scaling_factor: 1.0
planning_time: 0.8
chomp_planner:
plan_request_params:
planning_attempts: 1
planning_pipeline: chomp
max_velocity_scaling_factor: 1.0
max_acceleration_scaling_factor: 1.0
planning_time: 1.5
| 2,036 | YAML | 45.295454 | 171 | 0.761297 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/data_gen/setup.py | import os
from setuptools import find_packages, setup
package_name = "data_gen"
setup(
name=package_name,
version="0.0.0",
packages=find_packages(exclude=["test"]),
data_files=[
("share/ament_index/resource_index/packages", ["resource/" + package_name]),
("share/" + package_name, ["package.xml"]),
(
os.path.join("share", package_name, "launch"),
[os.path.join("launch", "object_sorter.launch.py")],
),
],
install_requires=["setuptools"],
zip_safe=True,
maintainer="root",
maintainer_email="[email protected]",
description="TODO: Package description",
license="TODO: License declaration",
tests_require=["pytest"],
entry_points={
"console_scripts": ["object_sorter = data_gen.object_sorter:main"],
},
)
| 823 | Python | 27.413792 | 84 | 0.606318 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/data_gen/launch/object_sorter.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription(
[
Node(
package="data_gen",
executable="object_sorter",
name="object_sorter",
parameters=[
{"rgb_topic": "/agentview/rgb"},
{"segmentation_topic": "/agentview/instance_segmentation_repub"},
{"labels_topic": "/agentview/semantic_labels"},
],
)
]
)
| 571 | Python | 27.599999 | 85 | 0.499124 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/data_gen/data_gen/object_sorter.py | import json
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from std_msgs.msg import String
from roboai_interfaces.msg import ObjectOrder
from roboai_interfaces.srv import SaveObjects
import numpy as np
import cv2
from cv_bridge import CvBridge
class ObjectSorter(Node):
def __init__(self):
super().__init__("object_sorter")
# Parameters
self.declare_parameter("rgb_topic", "/rgb")
self.declare_parameter("segmentation_topic", "/instance_segmentation")
self.declare_parameter("labels_topic", "/segmentation_labels")
# Subscribers
self.rgb_subscriber = self.create_subscription(
Image,
self.get_parameter("rgb_topic").get_parameter_value().string_value,
self.rgb_callback,
10,
)
self.segmentation_subscriber = self.create_subscription(
Image,
self.get_parameter("segmentation_topic").get_parameter_value().string_value,
self.segmentation_callback,
10,
)
self.labels_subscriber = self.create_subscription(
String,
self.get_parameter("labels_topic").get_parameter_value().string_value,
self.labels_callback,
10,
)
# Publisher
self.order_publisher = self.create_publisher(ObjectOrder, "sorted_objects", 10)
# Service
self.save_service = self.create_service(
SaveObjects, "save_objects", self.save_objects_handler
)
# Variables
self.bridge = CvBridge()
self.current_rgb_image = None
self.current_segmentation_image = None
self.labels = {}
def rgb_callback(self, msg):
self.current_rgb_image = self.bridge.imgmsg_to_cv2(msg, "bgr8")
def segmentation_callback(self, msg):
segmentation_image = self.bridge.imgmsg_to_cv2(msg, "mono8")
self.current_segmentation_image = segmentation_image
self.process_and_publish_order(segmentation_image)
def labels_callback(self, msg):
# self.labels = json.loads(msg.data)
# labels indexes are 0, 1, 2, 3, etc but pixel values scale to 255
labels = json.loads(msg.data)
labels.pop("time_stamp", None)
# pop where value is BACKGROUND or UNLABBELED
labels = {
k: v for k, v in labels.items() if v not in ["BACKGROUND", "UNLABELLED"]
}
self.labels = {
int((i + 1) * 255 / len(labels)): v
for i, (k, v) in enumerate(labels.items())
}
def process_and_publish_order(self, segmentation_image):
object_order = self.sort_objects(segmentation_image)
if object_order:
order_msg = ObjectOrder(object_names=object_order)
self.order_publisher.publish(order_msg)
def sort_objects(self, segmentation_image):
unique_objects = np.unique(segmentation_image)
object_positions = {}
self.get_logger().info(f"Unique objects: {unique_objects}")
self.get_logger().info(f"Labels: {self.labels}")
for obj_id in unique_objects:
if (
obj_id == 0 or obj_id not in self.labels
): # Skip background or unknown labels
self.get_logger().info(f"Skipping object {obj_id}")
continue
y, x = np.where(segmentation_image == obj_id)
min_x = np.min(x) # Leftmost point
self.get_logger().info(f"Object {obj_id} at {min_x}")
object_positions[self.labels[obj_id]] = min_x
# Sort objects by their leftmost points
sorted_objects = sorted(object_positions.items(), key=lambda x: x[1])
return [obj[0] for obj in sorted_objects]
def save_objects_handler(self, request, response):
if self.current_rgb_image is None or self.current_segmentation_image is None:
response.success = False
response.message = "No data available to save"
return response
# Save the RGB image and the object order
cv2.imwrite("latest_rgb_image.png", self.current_rgb_image)
order = self.sort_objects(self.current_segmentation_image)
data = {"objects": {"count": len(order), "names": order}}
with open("latest_object_order.json", "w") as f:
json.dump(data, f)
response.success = True
response.message = "Saved successfully"
return response
def main(args=None):
rclpy.init(args=args)
node = ObjectSorter()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 4,659 | Python | 34.30303 | 88 | 0.6085 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/grasps_ros/launch/image_processor.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
node_action = Node(
package="grasps_ros",
executable="image_processor",
name="image_processor",
output="screen",
remappings=[
("/rgb_image", "/rgb"),
("/depth_image", "/depth"),
("/camera_info", "/camera_info"),
("/grasp_image", "/grasp_image"),
("/grasp_markers", "/grasp_markers"),
],
)
return LaunchDescription([node_action])
| 560 | Python | 25.714284 | 49 | 0.55 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/grasps_ros/grasps_ros/image_processor.py | import time
import cv2
from PIL import Image
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.action import ActionServer, CancelResponse, GoalResponse
from tf2_ros import Buffer, TransformListener
from tf2_ros import LookupException, ConnectivityException, ExtrapolationException
from tf2_geometry_msgs import do_transform_pose_stamped
import message_filters
from sensor_msgs.msg import Image as ROSImage
from sensor_msgs.msg import CameraInfo
from cv_bridge import CvBridge
from visualization_msgs.msg import Marker
from geometry_msgs.msg import Point, PoseStamped
from roboai_interfaces.action import GetGrasp
from roboai.shared.utils.grasp_client import get_grasp_from_image
def interpolate(p1, p2, num_points=5):
"""Interpolates num_points between p1 and p2, inclusive of p1 and p2."""
return [
((1 - t) * np.array(p1) + t * np.array(p2))
for t in np.linspace(0, 1, num_points)
]
def get_grid_from_box(box):
sides = []
for i in range(len(box)):
p1 = box[i]
p2 = box[(i + 1) % len(box)]
if i < len(box) - 1:
sides.append(interpolate(p1, p2)[:-1])
else:
sides.append(interpolate(p1, p2))
grid = []
for i in range(len(sides[0])):
for j in range(len(sides[1])):
grid.extend(interpolate(sides[0][i], sides[1][j]))
return grid
def get_angle_from_box(box):
p1 = box[2]
p2 = box[3]
angle = np.arctan2(p2[1] - p1[1], p2[0] - p1[0])
return angle
class ImageProcessor(Node):
def __init__(self):
super().__init__("image_processor")
self.get_logger().info("Image Processor node has been initialized")
self.tf_buffer = Buffer()
self.tf_listener = TransformListener(self.tf_buffer, self)
self.last_image_ts = None
rgb_sub = message_filters.Subscriber(self, ROSImage, "/rgb_image")
depth_sub = message_filters.Subscriber(self, ROSImage, "/depth_image")
ts = message_filters.TimeSynchronizer([rgb_sub, depth_sub], 10)
ts.registerCallback(self.image_callback)
self.camera_info = None
self.camera_info_sub = self.create_subscription(
CameraInfo, "/camera_info", self.camera_info_callback, 10
)
self.publisher = self.create_publisher(ROSImage, "/grasp_image", 10)
self.bridge = CvBridge()
self.marker_pub = self.create_publisher(Marker, "/grasp_markers", 10)
self.grasp_axis_pub = self.create_publisher(Marker, "/grasp_axis_markers", 10)
self.grasps = None
self._action_server = ActionServer(
self,
GetGrasp,
"get_grasp",
self.execute_callback,
goal_callback=self.goal_callback,
cancel_callback=self.cancel_callback,
)
def camera_info_callback(self, msg):
self.camera_info = msg
def image_callback(self, rgb_msg, depth_msg):
# Convert ROS Image message to OpenCV format
if not self.camera_info:
self.get_logger().warn("Camera info not available")
return
self.last_image_ts = rclpy.time.Time()
cv_rgb_image = self.bridge.imgmsg_to_cv2(
rgb_msg, desired_encoding="passthrough"
)
cv_depth_image = self.bridge.imgmsg_to_cv2(depth_msg, "32FC1")
image = Image.fromarray(cv_rgb_image)
start_time = time.time()
response = get_grasp_from_image(image)
self.get_logger().info(f"Time taken to get grasps: {time.time() - start_time}")
self.handle_response(response, cv_rgb_image, cv_depth_image)
def handle_response(self, response, cv_rgb_image, cv_depth_image):
try:
grasps = response["result"]
if grasps:
self.get_logger().info(
f"Received grasp poses: {[(grasp['cls_name'], round(grasp['obj'],2)) for grasp in response['result']]}"
)
self.publish_grasp_image(grasps, cv_rgb_image)
self.publish_grasp_markers(grasps, cv_depth_image)
grasp_dict = self.get_grasp_poses(grasps, cv_depth_image)
grasp_timestamp = self.get_clock().now().to_msg()
self.grasps = {
"timestamp": grasp_timestamp,
"grasps": grasp_dict,
}
self.publish_grasp_axis_markers()
except KeyError as e:
self.get_logger().warn(
f"KeyError: Failed to receive valid response or grasp poses: {e}"
)
def publish_grasp_image(self, grasps, original_image):
for grasp in grasps:
points = np.array(grasp["r_bbox"], np.int32)
points = points.reshape((-1, 1, 2))
cv2.polylines(
original_image, [points], isClosed=True, color=(0, 255, 0), thickness=2
)
# Get the label for the class
class_label = grasp["cls_name"]
score = grasp["obj"]
label_with_score = (
f"{class_label} ({score:.2f})" # Formatting score to 2 decimal places
)
label_position = (points[0][0][0], points[0][0][1] - 10)
cv2.putText(
original_image,
label_with_score,
label_position,
cv2.FONT_HERSHEY_SIMPLEX,
0.5,
(255, 255, 255),
2,
)
ros_image = self.bridge.cv2_to_imgmsg(original_image, "rgb8")
self.publisher.publish(ros_image)
def project_to_3d(self, x, y, depth):
depth = float(depth)
fx = self.camera_info.k[0]
fy = self.camera_info.k[4]
cx = self.camera_info.k[2]
cy = self.camera_info.k[5]
x = (x - cx) * depth / fx
y = (y - cy) * depth / fy
return x, y, depth
def get_grasp_poses(self, grasps, cv_depth_image):
grasp_poses = {}
timestamp = self.last_image_ts.to_msg()
for grasp in grasps:
grasp_points = grasp["r_bbox"]
center = np.mean(grasp_points, axis=0)
average_depth = np.mean(
[
cv_depth_image[int(pt[1]), int(pt[0])]
for pt in get_grid_from_box(grasp_points)
]
)
point_3d = self.project_to_3d(center[0], center[1], average_depth)
if point_3d:
pose_msg = PoseStamped()
pose_msg.header.frame_id = self.camera_info.header.frame_id
pose_msg.header.stamp = timestamp
pose_msg.pose.position.x = point_3d[0]
pose_msg.pose.position.y = point_3d[1]
pose_msg.pose.position.z = point_3d[2]
angle = get_angle_from_box(grasp_points)
pose_msg.pose.orientation.z = np.sin(angle / 2)
pose_msg.pose.orientation.w = np.cos(angle / 2)
try:
transform = self.tf_buffer.lookup_transform(
"world",
pose_msg.header.frame_id,
timestamp,
timeout=rclpy.duration.Duration(seconds=10),
)
pose_msg = do_transform_pose_stamped(pose_msg, transform)
grasp_poses[grasp["cls_name"]] = pose_msg
except (
LookupException,
ConnectivityException,
ExtrapolationException,
) as e:
self.get_logger().error(f"Failed to transform point: {str(e)}")
self.get_logger().info(f"Grasp poses: {len(grasp_poses)}")
return grasp_poses
def publish_grasp_markers(self, grasps, cv_depth_image, publish_grid=False):
if not self.camera_info:
return
scale = 0.02
if publish_grid:
scale = 0.002
marker = Marker()
marker.header.frame_id = self.camera_info.header.frame_id
marker.header.stamp = self.last_image_ts.to_msg()
marker.ns = "grasps"
marker.id = 0
marker.type = Marker.POINTS
marker.action = Marker.ADD
marker.pose.orientation.w = 1.0
marker.scale.x = scale
marker.scale.y = scale
marker.scale.z = scale
marker.color.r = 1.0
marker.color.a = 1.0
marker.points = []
for grasp in grasps:
grasp_points = grasp["r_bbox"]
if publish_grid:
grasp_points = get_grid_from_box(grasp_points)
for pt in grasp_points:
point_3d = self.project_to_3d(
pt[0], pt[1], cv_depth_image[int(pt[1]), int(pt[0])]
)
if point_3d:
marker.points.append(
Point(x=point_3d[0], y=point_3d[1], z=point_3d[2])
)
self.marker_pub.publish(marker)
def publish_grasp_axis_markers(self):
if not self.grasps:
return
marker = Marker()
marker.header.frame_id = list(self.grasps["grasps"].values())[0].header.frame_id
marker.header.stamp = self.last_image_ts.to_msg()
marker.ns = "grasp_axis"
marker.id = 0
marker.type = Marker.ARROW
marker.action = Marker.ADD
marker.pose.orientation.w = 1.0
marker.scale.x = 0.1
marker.scale.y = 0.015
marker.scale.z = 0.015
marker.color.b = 1.0
marker.color.a = 0.5
# for grasp in self.grasps["grasps"].values():
grasp = list(self.grasps["grasps"].values())[0]
# Draw the axis
marker.pose.position = grasp.pose.position
marker.pose.orientation = grasp.pose.orientation
self.grasp_axis_pub.publish(marker)
def goal_callback(self, goal_request):
self.get_logger().info("Received goal request")
return GoalResponse.ACCEPT
def cancel_callback(self, goal_handle):
self.get_logger().info("Received cancel request")
self.get_logger().error("Cancel not implemented")
return CancelResponse.REJECT
def execute_callback(self, goal_handle):
self.get_logger().info("Received execute request")
object_name = goal_handle.request.object_name
self.get_logger().info(f"Looking for object name: {object_name}")
time_tolerance = rclpy.time.Duration(seconds=3)
timeout = 10.0
while True and timeout > 0:
self.get_logger().info(
f"Grasps: {len(self.grasps['grasps'])}, TS: {self.grasps['timestamp']}, now: {self.get_clock().now()}"
)
self.get_logger().info(
f"Time diff: {(self.get_clock().now() - rclpy.time.Time.from_msg(self.grasps['timestamp'])).nanoseconds/1e9}"
)
if (
self.grasps
and self.get_clock().now()
- rclpy.time.Time.from_msg(self.grasps["timestamp"])
< time_tolerance
):
self.get_logger().info(f"Found grasps for object: {object_name}")
result = GetGrasp.Result(success=True)
grasp = list(self.grasps["grasps"].values())[0]
result.grasp = grasp
goal_handle.succeed()
return result
timeout -= 0.1
rclpy.spin_once(self, timeout_sec=0.1)
self.get_logger().warn(f"Couldn't find grasps for object: {object_name}")
goal_handle.succeed()
return GetGrasp.Result(success=False)
def main(args=None):
rclpy.init(args=args)
image_processor = ImageProcessor()
try:
while True:
rclpy.spin_once(image_processor)
except KeyboardInterrupt:
image_processor.get_logger().info("Shutting down")
image_processor.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 12,018 | Python | 33.736994 | 125 | 0.555999 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/navigation/isaac_ros_navigation_goal/isaac_ros_navigation_goal/goal_generators/__init__.py | from .random_goal_generator import RandomGoalGenerator
from .goal_reader import GoalReader
__all__ = ["RandomGoalGenerator", "GoalReader"]
| 140 | Python | 27.199995 | 54 | 0.785714 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/launch_pointcloud.launch.py | from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import ThisLaunchFileDir
def generate_launch_description():
# Path to the first launch file
pointcloud_gen = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[ThisLaunchFileDir(), "/pointcloud_gen.launch.py"]
)
)
# Path to the second launch file
dynamic_repub = IncludeLaunchDescription(
PythonLaunchDescriptionSource([ThisLaunchFileDir(), "/dynamic_repub.launch.py"])
)
return LaunchDescription([pointcloud_gen, dynamic_repub])
| 696 | Python | 32.190475 | 88 | 0.755747 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/dynamic_repub.launch.py | from launch import LaunchDescription
from launch_ros.actions import Node
def generate_launch_description():
return LaunchDescription(
[
Node(
package="ros_utils",
executable="dynamic_repub",
name="dynamic_repub",
parameters=[
{
"topics": [
"/pointcloud",
"/instance_segmentation",
"/agentview/instance_segmentation",
]
}
], # Ensure this matches the expected type
),
]
)
| 674 | Python | 27.124999 | 63 | 0.412463 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/launch/pointcloud_gen.launch.py | from launch import LaunchDescription
from launch_ros.actions import ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
def generate_launch_description():
container = ComposableNodeContainer(
namespace="",
name="depth_image_proc_container",
package="rclcpp_components",
executable="component_container",
composable_node_descriptions=[
ComposableNode(
package="depth_image_proc",
plugin="depth_image_proc::PointCloudXyzrgbNode",
name="point_cloud_xyzrgb_node",
remappings=[
("rgb/camera_info", "/camera_info"),
("rgb/image_rect_color", "rgb"),
("depth_registered/image_rect", "depth"),
("points", "pointcloud"),
],
parameters=[
{
"use_sim_time": False,
"queue_size": 10,
"qos_overrides./parameter_events.publisher.durability": "transient_local",
}
],
),
],
)
return LaunchDescription([container])
| 1,210 | Python | 33.599999 | 98 | 0.516529 |
AshisGhosh/roboai/isaac_sim/humble_ws/src/ros_utils/ros_utils/dynamic_repub.py | #!/usr/bin/env python3
import numpy as np
import rclpy
from rclpy.node import Node
from rclpy.qos import QoSProfile, QoSReliabilityPolicy, QoSDurabilityPolicy
import rcl_interfaces
from sensor_msgs.msg import Image
class DynamicRepub(Node):
def __init__(self):
super().__init__("dynamic_repub")
self.custom_publishers = {}
self.initialized_topics = set()
# Retrieve the list of topics from the parameters
self.declare_parameter(
"topics",
rcl_interfaces.msg.ParameterValue(
type=rcl_interfaces.msg.ParameterType.PARAMETER_STRING_ARRAY
),
)
self.topics_to_handle = (
self.get_parameter("topics").get_parameter_value().string_array_value
)
# Check topics periodically to set up publishers and subscribers
self.timer = self.create_timer(
5.0, self.check_and_initialize_topics
) # Check every 5 seconds
def check_and_initialize_topics(self):
current_topics = self.get_topic_names_and_types()
self.get_logger().info(f"Expected topics: {self.topics_to_handle}")
self.get_logger().info(f"Current topics: {len(current_topics)}")
for required_topic in self.topics_to_handle:
if required_topic not in self.initialized_topics:
for topic_name, types in current_topics:
if topic_name == required_topic:
self.initialize_pub_sub(topic_name, types[0])
break
def initialize_pub_sub(self, topic_name, type_name):
if topic_name in self.initialized_topics:
return # Already initialized
# Dynamically import the message type
msg_type = self.load_message_type(type_name)
if msg_type is None:
self.get_logger().error(
f"Could not find or load message type for {type_name}"
)
return
sub_qos_profile = QoSProfile(
depth=10,
reliability=QoSReliabilityPolicy.BEST_EFFORT,
durability=QoSDurabilityPolicy.VOLATILE,
)
repub_topic_name = f"{topic_name}_repub" # Rename republished topic
self.custom_publishers[repub_topic_name] = self.create_publisher(
msg_type, repub_topic_name, QoSProfile(depth=10)
)
self.create_subscription(
msg_type,
topic_name,
lambda msg, repub_topic_name=repub_topic_name: self.repub_callback(
msg, repub_topic_name
),
sub_qos_profile,
)
self.initialized_topics.add(topic_name)
self.get_logger().info(
f"Set up republishing from {topic_name} to {repub_topic_name} with type {type_name}"
)
def load_message_type(self, type_name):
# Dynamically load message type from type name
try:
package_name, _, message_name = type_name.split("/")
relative_module = ".msg"
msg_module = __import__(
f"{package_name}{relative_module}", fromlist=[message_name]
)
return getattr(msg_module, message_name)
except (ValueError, ImportError, AttributeError) as e:
self.get_logger().error(f"Error loading message type {type_name}: {str(e)}")
return None
def repub_callback(self, msg, repub_topic_name):
if hasattr(msg, "header") and hasattr(msg.header, "stamp"):
msg.header.stamp = self.get_clock().now().to_msg()
if type(msg) == Image:
if msg.encoding == "32SC1":
msg = self._reencode_image(msg)
self.custom_publishers[repub_topic_name].publish(msg)
def _reencode_image(self, image):
if image.encoding == "32SC1":
# Convert the raw data to a numpy array of type int32
array = np.frombuffer(image.data, dtype=np.int32).reshape(
image.height, image.width
)
# Calculate local minimum and maximum values from the array
min_value = np.min(array)
max_value = np.max(array)
# Avoid division by zero if max_value equals min_value
if max_value == min_value:
max_value += 1 # Increment max_value to avoid zero division
# Normalize the array to the range 0-255
normalized_array = (array - min_value) / (max_value - min_value) * 255
clipped_array = np.clip(
normalized_array, 0, 255
) # Ensure all values are within 0 to 255
# Convert back to byte format and update the image data
image.data = clipped_array.astype(np.uint8).tobytes()
image.encoding = "mono8"
image.step = image.width # Number of bytes in a row
return image
def main(args=None):
rclpy.init(args=args)
node = DynamicRepub()
rclpy.spin(node)
node.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 5,066 | Python | 34.683098 | 96 | 0.586261 |
AshisGhosh/roboai/isaac_sim/isaac_sim/planner.py | import numpy as np
from PIL import Image
from roboai.enums import CameraMode
from roboai.shared.utils.grasp_client import get_grasp_from_image # noqa: F401
from roboai.shared.utils.robotic_grasping_client import get_grasps_from_rgb_and_depth
class Planner:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
def clean_plan(self):
"""
Get and image of the scene and get a plan to clean the environment
"""
pass
def grasp_plan(self):
"""
Get an image of the scene and get a plan to grasp an object
"""
img = self.sim_manager.get_image(camera_name="realsense", mode=CameraMode.RGB)
image = Image.fromarray(img)
depth = self.sim_manager.get_image(
camera_name="realsense", mode=CameraMode.DEPTH
)
squeezed_depth = np.squeeze(depth)
normalized_depth = (
(squeezed_depth - np.min(squeezed_depth))
/ (np.max(squeezed_depth) - np.min(squeezed_depth))
* 255
)
depth_uint8 = normalized_depth.astype(np.uint8)
depth_image = Image.fromarray(depth_uint8)
grasps = get_grasps_from_rgb_and_depth(image, depth_image)
grasp = grasps[0]
print(grasp)
# grasp = get_grasp_from_image(image)
return grasp
class GraspHandler:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
def grasp_object(self, object_name):
"""
Grasp an object in the scene
"""
pass
def release_object(self, object_name):
"""
Release an object in the scene
"""
pass
| 1,776 | Python | 28.616666 | 86 | 0.603604 |
AshisGhosh/roboai/isaac_sim/isaac_sim/robosim.py | import os
import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
from roboai.enums import CameraMode
from roboai.robot import RobotActor
from roboai.tasks import TaskManager
from roboai.planner import Planner
global \
World, \
Robot, \
Franka, \
extensions, \
nucleus, \
stage, \
prims, \
rotations, \
viewports, \
Gf, \
UsdGeom, \
ArticulationMotionPolicy, \
RMPFlowController, \
og
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
class SimManager:
def __init__(self):
self.sim = None
self.assets_root_path = None
self.world = None
self.cameras = {}
self.controller = None
self.robot_actor = None
self.task_manager = None
def start_sim(self, headless=True):
CONFIG = {
"renderer": "RayTracedLighting",
"headless": headless,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
self.sim = SimulationApp(CONFIG)
carb.log_warn(
f"Time taken to load simulation: {time.time() - start_time} seconds"
)
if headless:
self.sim.set_setting("/app/window/drawMouse", True)
self.sim.set_setting("/app/livestream/proto", "ws")
self.sim.set_setting("/app/livestream/websocket/framerate_limit", 120)
self.sim.set_setting("/ngx/enabled", False)
from omni.isaac.core.utils.extensions import enable_extension
enable_extension("omni.kit.livestream.native")
self._do_imports()
if self.assets_root_path is None:
self.assets_root_path = self._get_assets_root_path()
start_time = time.time()
self.world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
self._load_stage()
self._load_robot()
self._load_objects()
# self._create_markers()
self._init_cameras()
self._enable_ros2_bridge_ext()
self._load_omnigraph()
franka = self.world.scene.get_object("franka")
self.controller = RMPFlowController(
name="target_follower_controller", robot_articulation=franka
)
articulation_controller = franka.get_articulation_controller()
self.robot_actor = RobotActor(
world=self.world,
robot=franka,
controller=self.controller,
articulator=articulation_controller,
)
self.task_manager = TaskManager(sim_manager=self, robot_actor=self.robot_actor)
self.planner = Planner(sim_manager=self, robot_actor=self.robot_actor)
def _do_imports(self):
global \
World, \
Robot, \
Franka, \
extensions, \
nucleus, \
stage, \
prims, \
rotations, \
viewports, \
Gf, \
UsdGeom, \
ArticulationMotionPolicy, \
RMPFlowController, \
og
from omni.isaac.core import World
from omni.isaac.core.robots import Robot
from omni.isaac.franka import Franka
from omni.isaac.core.utils import (
extensions,
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
from omni.isaac.motion_generation.articulation_motion_policy import (
ArticulationMotionPolicy,
)
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController
import omni.graph.core as og
def _get_assets_root_path(self):
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
self.sim.close()
sys.exit()
carb.log_warn(
f"Time taken to get assets root path: {time.time() - start_time} seconds"
)
return assets_root_path
def _load_stage(self):
start_time = time.time()
stage.add_reference_to_stage(
self.assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
def _load_robot(self):
start_time = time.time()
stage.add_reference_to_stage(
self.assets_root_path + FRANKA_USD_PATH, FRANKA_STAGE_PATH
)
self.world.scene.add(
Franka(
prim_path=FRANKA_STAGE_PATH,
name="franka",
position=np.array([0, -0.64, 0]),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)
),
)
)
carb.log_warn(
f"Time taken to create Franka: {time.time() - start_time} seconds"
)
self.sim.update()
def __rand_position_in_bounds(self, bounds, height):
x = np.random.uniform(bounds[0][0], bounds[1][0])
y = np.random.uniform(bounds[0][1], bounds[1][1])
z = height
return np.array([x, y, z])
def _load_objects(self):
start_time = time.time()
bounds = [[-0.5, -0.35], [0.5, 0.35]]
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
# position=np.array([-0.2, -0.25, 0.15]),
position=self.__rand_position_in_bounds(bounds, 0.15),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
semantic_label="cracker_box",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
# position=np.array([-0.07, -0.25, 0.1]),
position=self.__rand_position_in_bounds(bounds, 0.1),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
semantic_label="sugar_box",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
# position=np.array([0.1, -0.25, 0.10]),
position=self.__rand_position_in_bounds(bounds, 0.10),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
semantic_label="soup_can",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
# position=np.array([0.0, 0.15, 0.12]),
position=self.__rand_position_in_bounds(bounds, 0.12),
orientation=rotations.gf_rotation_to_np_array(
Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)
),
usd_path=self.assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
semantic_label="mustard_bottle",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
self.sim.update()
def _create_markers(self):
from omni.isaac.core.objects import VisualCuboid
from omni.isaac.core.materials import OmniGlass
marker_cube = self.world.scene.add(
VisualCuboid(
prim_path=WORLD_STAGE_PATH + "/marker_cube",
name="marker_cube",
scale=np.array([0.025, 0.2, 0.05]),
position=np.array([0.0, 0.0, 0.0]),
color=np.array([1.0, 0.0, 0.0]),
)
)
material = OmniGlass(
prim_path="/World/material/glass", # path to the material prim to create
ior=1.25,
depth=0.001,
thin_walled=True,
color=np.array([1.5, 0.0, 0.0]),
)
marker_cube.apply_visual_material(material)
self.sim.update()
def _init_cameras(self):
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
realsense_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
# realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocalLengthAttr().Set(12.7)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
from omni.isaac.sensor import Camera
render_product_path = rs_viewport.viewport_api.get_render_product_path()
self.cameras["realsense"] = Camera(
prim_path=CAMERA_PRIM_PATH,
name="realsense",
resolution=(640, 480),
render_product_path=render_product_path,
)
self.cameras["realsense"].add_distance_to_camera_to_frame()
self.cameras["realsense"].add_distance_to_image_plane_to_frame()
camera_rot = Gf.Rotation(Gf.Vec3d(0, 0, 1), -90) * Gf.Rotation(
Gf.Vec3d(1, 0, 0), 45
)
self.cameras["agentview"] = Camera(
prim_path="/World/agentview_camera",
name="agentview",
resolution=(1024, 768),
position=(0, 2.75, 2.67),
orientation=rotations.gf_rotation_to_np_array(camera_rot),
)
# viewports.create_viewport_for_camera("agentview", "/World/agentview_camera")
# agentview_prim = UsdGeom.Camera(
# stage.get_current_stage().GetPrimAtPath("/World/agentview_camera")
# )
# agentview_viewport = omni.ui.Workspace.get_window("agentview")
# render_product_path = agentview_viewport.viewport_api.get_render_product_path()
# self.cameras["agentview"].initialize(render_product_path)
self.world.reset()
for cam in self.cameras.values():
cam.initialize()
def _enable_ros2_bridge_ext(self):
extensions.enable_extension("omni.isaac.ros2_bridge")
def _load_omnigraph(self):
carb.log_warn("Loading Omnigraph")
try:
ros_domain_id = int(os.environ["ROS_DOMAIN_ID"])
print("Using ROS_DOMAIN_ID: ", ros_domain_id)
except ValueError:
print("Invalid ROS_DOMAIN_ID integer value. Setting value to 0")
ros_domain_id = 0
except KeyError:
print("ROS_DOMAIN_ID environment variable is not set. Setting value to 0")
ros_domain_id = 0
try:
og.Controller.edit(
{"graph_path": GRAPH_PATH, "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
(
"ReadSimTime",
"omni.isaac.core_nodes.IsaacReadSimulationTime",
),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
(
"PublishJointState",
"omni.isaac.ros2_bridge.ROS2PublishJointState",
),
(
"SubscribeJointState",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ArticulationController",
"omni.isaac.core_nodes.IsaacArticulationController",
),
# Hand Controller Nodes
(
"SubscribeJointStateHand",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ArticulationControllerHand",
"omni.isaac.core_nodes.IsaacArticulationController",
),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
("OnTick", "omni.graph.action.OnTick"),
# Realsense Camera Helper
("createViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(
"getRenderProduct",
"omni.isaac.core_nodes.IsaacGetViewportRenderProduct",
),
(
"setCamera",
"omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct",
),
("cameraHelperRgb", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("cameraHelperInfo", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
(
"cameraHelperDepth",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperInstanceSegmentation",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
# Agent View Camera Helper
(
"createAgentView",
"omni.isaac.core_nodes.IsaacCreateViewport",
),
(
"getRenderProductAgentView",
"omni.isaac.core_nodes.IsaacGetViewportRenderProduct",
),
(
"setCameraAgentView",
"omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct",
),
(
"cameraHelperAgentViewRgb",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewInfo",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewDepth",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
(
"cameraHelperAgentViewInstanceSegmentation",
"omni.isaac.ros2_bridge.ROS2CameraHelper",
),
],
og.Controller.Keys.CONNECT: [
(
"OnImpulseEvent.outputs:execOut",
"PublishJointState.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"SubscribeJointState.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"PublishClock.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"ArticulationController.inputs:execIn",
),
("Context.outputs:context", "PublishJointState.inputs:context"),
(
"Context.outputs:context",
"SubscribeJointState.inputs:context",
),
("Context.outputs:context", "PublishClock.inputs:context"),
(
"ReadSimTime.outputs:simulationTime",
"PublishJointState.inputs:timeStamp",
),
(
"ReadSimTime.outputs:simulationTime",
"PublishClock.inputs:timeStamp",
),
(
"SubscribeJointState.outputs:jointNames",
"ArticulationController.inputs:jointNames",
),
(
"SubscribeJointState.outputs:positionCommand",
"ArticulationController.inputs:positionCommand",
),
(
"SubscribeJointState.outputs:velocityCommand",
"ArticulationController.inputs:velocityCommand",
),
(
"SubscribeJointState.outputs:effortCommand",
"ArticulationController.inputs:effortCommand",
),
# Hand Controller Connects
(
"OnImpulseEvent.outputs:execOut",
"SubscribeJointStateHand.inputs:execIn",
),
(
"OnImpulseEvent.outputs:execOut",
"ArticulationControllerHand.inputs:execIn",
),
(
"Context.outputs:context",
"SubscribeJointStateHand.inputs:context",
),
(
"SubscribeJointStateHand.outputs:jointNames",
"ArticulationControllerHand.inputs:jointNames",
),
(
"SubscribeJointStateHand.outputs:positionCommand",
"ArticulationControllerHand.inputs:positionCommand",
),
(
"SubscribeJointStateHand.outputs:velocityCommand",
"ArticulationControllerHand.inputs:velocityCommand",
),
(
"SubscribeJointStateHand.outputs:effortCommand",
"ArticulationControllerHand.inputs:effortCommand",
),
# Realsense Camera Key Connects
("OnTick.outputs:tick", "createViewport.inputs:execIn"),
(
"createViewport.outputs:execOut",
"getRenderProduct.inputs:execIn",
),
(
"createViewport.outputs:viewport",
"getRenderProduct.inputs:viewport",
),
("getRenderProduct.outputs:execOut", "setCamera.inputs:execIn"),
(
"getRenderProduct.outputs:renderProductPath",
"setCamera.inputs:renderProductPath",
),
("setCamera.outputs:execOut", "cameraHelperRgb.inputs:execIn"),
("setCamera.outputs:execOut", "cameraHelperInfo.inputs:execIn"),
(
"setCamera.outputs:execOut",
"cameraHelperDepth.inputs:execIn",
),
(
"setCamera.outputs:execOut",
"cameraHelperInstanceSegmentation.inputs:execIn",
),
("Context.outputs:context", "cameraHelperRgb.inputs:context"),
("Context.outputs:context", "cameraHelperInfo.inputs:context"),
("Context.outputs:context", "cameraHelperDepth.inputs:context"),
(
"Context.outputs:context",
"cameraHelperInstanceSegmentation.inputs:context",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperRgb.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperInfo.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperDepth.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperInstanceSegmentation.inputs:renderProductPath",
),
# Agent View Camera Key Connects
("OnTick.outputs:tick", "createAgentView.inputs:execIn"),
(
"createAgentView.outputs:execOut",
"getRenderProductAgentView.inputs:execIn",
),
(
"createAgentView.outputs:viewport",
"getRenderProductAgentView.inputs:viewport",
),
(
"getRenderProductAgentView.outputs:execOut",
"setCameraAgentView.inputs:execIn",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"setCameraAgentView.inputs:renderProductPath",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewRgb.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewInfo.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewDepth.inputs:execIn",
),
(
"setCameraAgentView.outputs:execOut",
"cameraHelperAgentViewInstanceSegmentation.inputs:execIn",
),
(
"Context.outputs:context",
"cameraHelperAgentViewRgb.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewInfo.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewDepth.inputs:context",
),
(
"Context.outputs:context",
"cameraHelperAgentViewInstanceSegmentation.inputs:context",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewRgb.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewInfo.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewDepth.inputs:renderProductPath",
),
(
"getRenderProductAgentView.outputs:renderProductPath",
"cameraHelperAgentViewInstanceSegmentation.inputs:renderProductPath",
),
],
og.Controller.Keys.SET_VALUES: [
("Context.inputs:domain_id", ros_domain_id),
# Setting the /Franka target prim to Articulation Controller node
("ArticulationController.inputs:usePath", True),
("ArticulationController.inputs:robotPath", FRANKA_STAGE_PATH),
("PublishJointState.inputs:topicName", "isaac_joint_states"),
(
"SubscribeJointState.inputs:topicName",
"isaac_joint_commands",
),
# Hand Controller Set Values
("ArticulationControllerHand.inputs:usePath", True),
(
"ArticulationControllerHand.inputs:robotPath",
FRANKA_STAGE_PATH,
),
(
"SubscribeJointStateHand.inputs:topicName",
"isaac_hand_joint_commands",
),
# Realsense Camera Key Values
("createViewport.inputs:name", REALSENSE_VIEWPORT_NAME),
("createViewport.inputs:viewportId", 1),
("cameraHelperRgb.inputs:frameId", "sim_camera"),
("cameraHelperRgb.inputs:topicName", "rgb"),
("cameraHelperRgb.inputs:type", "rgb"),
("cameraHelperInfo.inputs:frameId", "sim_camera"),
("cameraHelperInfo.inputs:topicName", "camera_info"),
("cameraHelperInfo.inputs:type", "camera_info"),
("cameraHelperDepth.inputs:frameId", "sim_camera"),
("cameraHelperDepth.inputs:topicName", "depth"),
("cameraHelperDepth.inputs:type", "depth"),
(
"cameraHelperInstanceSegmentation.inputs:frameId",
"sim_camera",
),
(
"cameraHelperInstanceSegmentation.inputs:topicName",
"instance_segmentation",
),
(
"cameraHelperInstanceSegmentation.inputs:type",
"instance_segmentation",
),
# Agent View Camera Key Values
("createAgentView.inputs:name", "agentview"),
("createAgentView.inputs:viewportId", 2),
(
"setCameraAgentView.inputs:cameraPrim",
"/World/agentview_camera",
),
("cameraHelperAgentViewRgb.inputs:frameId", "agentview"),
("cameraHelperAgentViewRgb.inputs:topicName", "agentview/rgb"),
("cameraHelperAgentViewRgb.inputs:type", "rgb"),
("cameraHelperAgentViewInfo.inputs:frameId", "agentview"),
(
"cameraHelperAgentViewInfo.inputs:topicName",
"agentview/camera_info",
),
("cameraHelperAgentViewInfo.inputs:type", "camera_info"),
("cameraHelperAgentViewDepth.inputs:frameId", "agentview"),
(
"cameraHelperAgentViewDepth.inputs:topicName",
"agentview/depth",
),
("cameraHelperAgentViewDepth.inputs:type", "depth"),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:frameId",
"agentview",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:topicName",
"agentview/instance_segmentation",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:type",
"instance_segmentation",
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:enableSemanticLabels",
True,
),
(
"cameraHelperAgentViewInstanceSegmentation.inputs:semanticLabelsTopicName",
"agentview/semantic_labels",
),
],
},
)
carb.log_warn("Omnigraph loaded successfully")
except Exception as e:
carb.log_error(e)
carb.log_warn("Failed to load Omnigraph")
from omni.isaac.core_nodes.scripts.utils import set_target_prims
set_target_prims(
primPath="/ActionGraph/PublishJointState",
targetPrimPaths=[FRANKA_STAGE_PATH],
)
prims.set_targets(
prim=stage.get_current_stage().GetPrimAtPath(GRAPH_PATH + "/setCamera"),
attribute="inputs:cameraPrim",
target_prim_paths=[CAMERA_PRIM_PATH],
)
def close_sim(self):
self.sim.close()
def run_sim(self):
while self.sim.is_running():
self.world.step(render=True)
if self.world.is_playing():
if self.world.current_time_step_index == 0:
self.world.reset()
self.controller.reset()
# Tick the Publish/Subscribe JointState, Publish TF and Publish Clock nodes each frame
og.Controller.set(
og.Controller.attribute(
"/ActionGraph/OnImpulseEvent.state:enableImpulse"
),
True,
)
# self.task_manager.do_tasks()
self.sim.update()
def get_image(self, camera_name="realsense", mode=CameraMode.RGB, visualize=False):
self.world.step(render=True)
camera = self.cameras[camera_name]
try:
if mode == CameraMode.RGB:
img = camera.get_rgb()
if mode == CameraMode.RGBA:
img = camera.get_rgba()
if mode == CameraMode.DEPTH:
img = camera.get_depth()
if visualize:
import cv2
img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
cv2.imshow("Color", img)
cv2.waitKey(0)
return img
except Exception as e:
print(e)
if __name__ == "__main__":
sim_manager = SimManager()
sim_manager.start_sim(headless=False)
sim_manager.task_manager.test_task()
sim_manager.world.pause()
sim_manager.run_sim()
# sim_manager.get_image()
sim_manager.close_sim()
| 32,565 | Python | 41.403646 | 103 | 0.469461 |
AshisGhosh/roboai/isaac_sim/isaac_sim/test.py | import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
CONFIG = {
"renderer": "RayTracedLighting",
"headless": False,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
sim = SimulationApp(CONFIG)
carb.log_warn(f"Time taken to load simulation: {time.time() - start_time} seconds")
from omni.isaac.core import World # noqa E402
from omni.isaac.core.utils import ( # noqa E402
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
start_time = time.time()
world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
sim.close()
sys.exit()
carb.log_warn(f"Time taken to get assets root path: {time.time() - start_time} seconds")
start_time = time.time()
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
start_time = time.time()
prims.create_prim(
FRANKA_STAGE_PATH,
"Xform",
position=np.array([0, -0.64, 0]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)),
usd_path=assets_root_path + FRANKA_USD_PATH,
)
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
position=np.array([-0.2, -0.25, 0.15]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
position=np.array([-0.07, -0.25, 0.1]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
position=np.array([0.1, -0.25, 0.10]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
position=np.array([0.0, 0.15, 0.12]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
sim.update()
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
# Fix camera settings since the defaults in the realsense model are inaccurate
realsense_prim = camera_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
while sim.is_running():
world.step(render=True)
sim.close()
| 4,058 | Python | 30.465116 | 88 | 0.704041 |
AshisGhosh/roboai/isaac_sim/isaac_sim/standalone_stream_server.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.kit import SimulationApp
class StreamServer:
def __init__(self):
pass
def start(self):
# This sample enables a livestream server to connect to when running headless
CONFIG = {
"width": 1280,
"height": 720,
"window_width": 1920,
"window_height": 1080,
"headless": True,
"renderer": "RayTracedLighting",
"display_options": 3286, # Set display options to show default grid
}
# Start the omniverse application
kit = SimulationApp(launch_config=CONFIG)
from omni.isaac.core.utils.extensions import enable_extension
# Default Livestream settings
kit.set_setting("/app/window/drawMouse", True)
kit.set_setting("/app/livestream/proto", "ws")
kit.set_setting("/app/livestream/websocket/framerate_limit", 120)
kit.set_setting("/ngx/enabled", False)
# Note: Only one livestream extension can be enabled at a time
# Enable Native Livestream extension
# Default App: Streaming Client from the Omniverse Launcher
enable_extension("omni.kit.livestream.native")
# Enable WebSocket Livestream extension(Deprecated)
# Default URL: http://localhost:8211/streaming/client/
# enable_extension("omni.services.streamclient.websocket")
# Enable WebRTC Livestream extension
# Default URL: http://localhost:8211/streaming/webrtc-client/
# enable_extension("omni.services.streamclient.webrtc")
# Run until closed
while kit._app.is_running() and not kit.is_exiting():
# Run in realtime mode, we don't specify the step size
kit.update()
kit.close()
| 2,196 | Python | 36.237288 | 85 | 0.664845 |
AshisGhosh/roboai/isaac_sim/isaac_sim/robot.py | from enum import Enum
import numpy as np
import time
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
def distance_between_quaternions(q1, q2):
q1 = np.array(q1)
q2 = np.array(q2)
dot_product = np.dot(q1, q2)
dot_product = np.clip(dot_product, -1.0, 1.0)
angle = 2 * np.arccos(np.abs(dot_product))
angle = min(angle, np.pi - angle)
return angle
class RobotStatus(Enum):
PENDING = 0
RUNNING = 1
COMPLETED = 2
FAILED = 3
class RobotActor:
POS_TOLERANCE = 0.01
ORI_TOLERANCE = 0.021 # radians, ~1.2deg
def __init__(self, world, robot, controller, articulator):
self.world = world
self.robot = robot
self.controller = controller
self.articulator = articulator
self.__goal_pos = None
self.__goal_ori = None
self.__pose_history = []
self.__moving_timeout = 3.0
def _get_end_effector_pose(self):
return self.robot.end_effector.get_world_pose()
def _goal_marker(self):
marker_cube = self.world.scene.get_object("marker_cube")
return marker_cube
def _check_if_goal_reached(self, pos, ori):
current_pos, current_ori = self._get_end_effector_pose()
pos_diff = np.linalg.norm(current_pos - pos)
ori_diff = distance_between_quaternions(current_ori, ori)
logger.warn(
f"Position difference: {pos_diff}, Orientation difference: {ori_diff}"
)
return pos_diff < self.POS_TOLERANCE and ori_diff < self.ORI_TOLERANCE
def _is_moving(self):
if len(self.__pose_history) == 0:
self.__pose_history = [time.time(), *self._get_end_effector_pose()]
return True
dt = time.time() - self.__pose_history[0]
if dt < self.__moving_timeout:
return True
current_pos, current_ori = self._get_end_effector_pose()
delta_pos = np.linalg.norm(current_pos - self.__pose_history[1])
logger.warn(f" delta_pos: {delta_pos}")
delta_ori = distance_between_quaternions(current_ori, self.__pose_history[2])
logger.warn(f" delta_ori: {delta_ori}")
if delta_pos < self.POS_TOLERANCE and delta_ori < self.ORI_TOLERANCE:
self.__pose_history = []
return False
self.__pose_history = [time.time(), *self._get_end_effector_pose()]
return True
def move(self, pos, ori):
if self.__goal_pos is None:
self.__goal_pos = pos
if self.__goal_ori is None:
self.__goal_ori = ori
goal_marker = self._goal_marker()
goal_marker.set_world_pose(position=pos, orientation=ori)
if self._check_if_goal_reached(pos, ori):
logger.warn("Goal reached")
self.__goal_pos = None
self.__goal_ori = None
return RobotStatus.COMPLETED
if not self._is_moving():
logger.error("Robot not moving")
self.__goal_pos = None
self.__goal_ori = None
return RobotStatus.FAILED
actions = self.controller.forward(
target_end_effector_position=pos,
target_end_effector_orientation=ori,
)
logger.debug(f"Actions: {actions}")
self.articulator.apply_action(actions)
return RobotStatus.RUNNING
def move_pos(self, pos):
if self.__goal_ori is None:
self.__goal_ori = self._get_end_effector_pose()[1]
return self.move(pos, self.__goal_ori)
def move_pos_relative(self, rel_pos=np.array([0.01, 0.01, 0.01])):
pos, ori = self._get_end_effector_pose()
if self.__goal_pos is None:
self.__goal_pos = pos + rel_pos
return self.move_pos(self.__goal_pos)
def move_to_preset(self, preset_name="pick_center"):
robot_presets = {
"pick_center": (
np.array([0.0, -0.25, 0.85]),
np.array([0.0, -0.707, 0.707, 0.0]),
),
}
pos, ori = robot_presets[preset_name]
return self.move(pos, ori)
| 4,099 | Python | 29.597015 | 85 | 0.577458 |
AshisGhosh/roboai/isaac_sim/isaac_sim/tasks.py | import carb
from enum import Enum
from roboai.robot import RobotStatus
class TaskClass(Enum):
CONTROL_TASK = 0
DATA_TASK = 1
ASYNC_DATA_TASK = 2
class TaskManagerStatus(Enum):
PENDING = 0
RUNNING = 1
COMPLETED = 2
FAILED = 3
class Task:
def __init__(self, name, function, task_class, *args, **kwargs):
self.name = name
self.function = function
self.task_class = task_class
self.args = args
self.kwargs = kwargs
def execute(self):
try:
return self.function(*self.args, **self.kwargs)
except Exception as e:
carb.log_error(f"Error executing task {self.name}: {e}")
def __str__(self):
return f"Task: {self.name}\n Function: {self.function}\n Args: {self.args}\n Kwargs: {self.kwargs}"
class TaskManager:
def __init__(self, sim_manager, robot_actor):
self.sim_manager = sim_manager
self.robot_actor = robot_actor
self.tasks = []
self._current_task = None
self.status = TaskManagerStatus.PENDING
def do_tasks(self):
if self._current_task is None:
if len(self.tasks) > 0:
self._current_task = self.tasks.pop(0)
carb.log_warn(f"Executing task {self._current_task.name}")
self.status = TaskManagerStatus.RUNNING
else:
self.status = TaskManagerStatus.COMPLETED
return self.status
if self._current_task.task_class == TaskClass.DATA_TASK:
result = self._current_task.execute()
carb.log_warn(
f"Task {self._current_task.name} completed with result {result}"
)
self._current_task = None
self.status = TaskManagerStatus.PENDING
if len(self.tasks) == 0:
carb.log_warn("All tasks completed")
self.status = TaskManagerStatus.COMPLETED
return self.status
status = self._current_task.execute()
if status == RobotStatus.COMPLETED:
self._current_task = None
self.status = TaskManagerStatus.PENDING
if len(self.tasks) == 0:
carb.log_warn("All tasks completed")
self.status = TaskManagerStatus.COMPLETED
elif status == RobotStatus.FAILED:
carb.log_error(f"Task {self._current_task.name} failed")
self._current_task = None
self.status = TaskManagerStatus.FAILED
return self.status
def add_task(self, task):
self.tasks.append(task)
def test_task(self):
self.add_task(
Task(
name="go to center",
function=self.robot_actor.move_to_preset,
task_class=TaskClass.CONTROL_TASK,
preset_name="pick_center",
)
)
self.add_task(
Task(
name="get grasp image",
function=self.sim_manager.planner.grasp_plan,
task_class=TaskClass.DATA_TASK,
)
)
| 3,103 | Python | 29.732673 | 116 | 0.557847 |
AshisGhosh/roboai/isaac_sim/isaac_sim/enums.py | from enum import Enum
class CameraMode(Enum):
RGB = 0
RGBA = 1
DEPTH = 2
| 87 | Python | 9.999999 | 23 | 0.597701 |
AshisGhosh/roboai/isaac_sim/isaac_sim/quick_start.py | import sys
import time
import carb
import omni
import numpy as np
from omni.isaac.kit import SimulationApp
WORLD_STAGE_PATH = "/World"
FRANKA_STAGE_PATH = WORLD_STAGE_PATH + "/Franka"
FRANKA_USD_PATH = "/Isaac/Robots/Franka/franka_alt_fingers.usd"
CAMERA_PRIM_PATH = f"{FRANKA_STAGE_PATH}/panda_hand/geometry/realsense/realsense_camera"
BACKGROUND_STAGE_PATH = WORLD_STAGE_PATH + "/background"
BACKGROUND_USD_PATH = "/Isaac/Environments/Simple_Room/simple_room.usd"
GRAPH_PATH = "/ActionGraph"
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
CONFIG = {
"renderer": "RayTracedLighting",
"headless": False,
"window_width": 2560,
"window_height": 1440,
}
start_time = time.time()
sim = SimulationApp(CONFIG)
carb.log_warn(f"Time taken to load simulation: {time.time() - start_time} seconds")
from omni.isaac.core import World # noqa E402
from omni.isaac.franka import Franka # noqa E402
from omni.isaac.core.utils import ( # noqa E402
nucleus,
stage,
prims,
rotations,
viewports,
)
from pxr import Gf, UsdGeom # noqa E402
from omni.isaac.franka.controllers.rmpflow_controller import RMPFlowController # noqa E402
from omni.isaac.core.objects import VisualCuboid # noqa E402
from omni.isaac.core.materials import OmniGlass # noqa E402
from omni.isaac.sensor import Camera # noqa E402
from roboai.robot import RobotActor # noqa E402
from roboai.tasks import TaskManager # noqa E402
# INITIALIZE WORLD
start_time = time.time()
world = World(stage_units_in_meters=1.0)
carb.log_warn(f"Time taken to create world: {time.time() - start_time} seconds")
# GET ASSET PATH
start_time = time.time()
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
sim.close()
sys.exit()
carb.log_warn(f"Time taken to get assets root path: {time.time() - start_time} seconds")
# LOAD STAGE/BACKGROUND
start_time = time.time()
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
carb.log_warn(
f"Time taken to add reference to stage: {time.time() - start_time} seconds"
)
# LOAD FRANKA
start_time = time.time()
stage.add_reference_to_stage(assets_root_path + FRANKA_USD_PATH, FRANKA_STAGE_PATH)
world.scene.add(Franka(prim_path=FRANKA_STAGE_PATH, name="franka"))
carb.log_warn(f"Time taken to create Franka: {time.time() - start_time} seconds")
sim.update()
# CREATE OBJECT PRIMS
start_time = time.time()
prims.create_prim(
WORLD_STAGE_PATH + "/cracker_box",
"Xform",
position=np.array([-0.2, -0.25, 0.15]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/003_cracker_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/sugar_box",
"Xform",
position=np.array([-0.07, -0.25, 0.1]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 1, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/004_sugar_box.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/soup_can",
"Xform",
position=np.array([0.1, -0.25, 0.10]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/005_tomato_soup_can.usd",
)
prims.create_prim(
WORLD_STAGE_PATH + "/mustard_bottle",
"Xform",
position=np.array([0.0, 0.15, 0.12]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(1, 0, 0), -90)),
usd_path=assets_root_path
+ "/Isaac/Props/YCB/Axis_Aligned_Physics/006_mustard_bottle.usd",
)
carb.log_warn(f"Time taken to create prims: {time.time() - start_time} seconds")
sim.update()
# CREATE MARKER OBJECTS
marker_cube = world.scene.add(
VisualCuboid(
prim_path=WORLD_STAGE_PATH + "/marker_cube",
name="marker_cube",
scale=np.array([0.025, 0.2, 0.05]),
position=np.array([0.0, 0.0, 0.0]),
color=np.array([1.0, 0.0, 0.0]),
)
)
material = OmniGlass(
prim_path="/World/material/glass", # path to the material prim to create
ior=1.25,
depth=0.001,
thin_walled=True,
color=np.array([1.5, 0.0, 0.0]),
)
marker_cube.apply_visual_material(material)
# prims.set_prim_attribute_value(WORLD_STAGE_PATH + "/marker_cube", "primvars:displayOpacity", [0.5])
sim.update()
# CREATE REALSENSE VIEWPORT & CAMERA
viewports.create_viewport_for_camera(REALSENSE_VIEWPORT_NAME, CAMERA_PRIM_PATH)
# Fix camera settings since the defaults in the realsense model are inaccurate
realsense_prim = camera_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(15.7)
realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocusDistanceAttr().Set(400)
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT, ratio=0.3)
carb.log_warn(
f"{REALSENSE_VIEWPORT_NAME} docked in {viewport.title}: {rs_viewport.docked}"
)
camera = Camera(prim_path=CAMERA_PRIM_PATH)
world.reset()
camera.initialize()
franka = world.scene.get_object("franka")
controller = RMPFlowController(
name="target_follower_controller", robot_articulation=franka
)
articulation_controller = franka.get_articulation_controller()
robot_actor = RobotActor(
world=world,
robot=franka,
controller=controller,
articulator=articulation_controller,
)
task_manager = TaskManager(robot_actor=robot_actor)
task_manager.test_task()
world.pause()
while sim.is_running():
world.step(render=True)
if world.is_playing():
if world.current_time_step_index == 0:
world.reset()
controller.reset()
task_manager.do_tasks()
sim.close()
| 5,964 | Python | 30.230366 | 101 | 0.707411 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/priminfo.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from pxr import Usd, UsdGeom, Gf
class PrimInfo:
# Class that stores the prim info
def __init__(self, prim: Usd.Prim, name: str = "") -> None:
self.prim = prim
self.child = prim.GetAllChildren()[0]
self.bbox: Gf.Range3d = self.compute_bbox()
self.length = self.GetLengthOfPrim()
self.width = self.GetWidthOfPrim()
self.origin = self.GetPrimOrigin()
self.area_name = name
def compute_bbox(self) -> Gf.Range3d:
"""
https://docs.omniverse.nvidia.com/prod_kit/prod_kit/programmer_ref/usd/transforms/compute-prim-bounding-box.html
"""
imageable = UsdGeom.Imageable(self.prim)
time = Usd.TimeCode.Default() # The time at which we compute the bounding box
bound = imageable.ComputeWorldBound(time, UsdGeom.Tokens.default_)
bound_range = bound.ComputeAlignedBox()
return bound_range
def GetLengthOfPrim(self):
return self.bbox.max[0] - self.bbox.min[0]
def GetWidthOfPrim(self):
return self.bbox.max[2] - self.bbox.min[2]
def GetPrimOrigin(self) -> str:
attr = self.prim.GetAttribute('xformOp:translate')
origin = Gf.Vec3d(0,0,0)
if attr:
origin = attr.Get()
phrase = str(origin[0]) + ", " + str(origin[1]) + ", " + str(origin[2])
return phrase | 2,044 | Python | 39.098038 | 120 | 0.663405 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/chatgpt_apiconnect.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import json
import omni.usd
import carb
import os
import aiohttp
import asyncio
from pxr import Sdf
from .prompts import system_input, user_input, assistant_input
from .deep_search import query_items
from .item_generator import place_greyboxes, place_deepsearch_results
from .results_office import ds_office_1, ds_office_2, ds_office_3, gpt_office_1
async def chatGPT_call(prompt: str):
# Load your API key from an environment variable or secret management service
settings = carb.settings.get_settings()
apikey = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
my_prompt = prompt.replace("\n", " ")
# Send a request API
try:
parameters = {
"model": "gpt-3.5-turbo",
"messages": [
{"role": "system", "content": system_input},
{"role": "user", "content": user_input},
{"role": "assistant", "content": assistant_input},
{"role": "user", "content": my_prompt}
]
}
chatgpt_url = "https://api.openai.com/v1/chat/completions"
headers = {"Authorization": "Bearer %s" % apikey}
# Create a completion using the chatGPT model
async with aiohttp.ClientSession() as session:
async with session.post(chatgpt_url, headers=headers, json=parameters) as r:
response = await r.json()
text = response["choices"][0]["message"]['content']
except Exception as e:
carb.log_error("An error as occurred")
return None, str(e)
# Parse data that was given from API
try:
#convert string to object
data = json.loads(text)
except ValueError as e:
carb.log_error(f"Exception occurred: {e}")
return None, text
else:
# Get area_objects_list
object_list = data['area_objects_list']
return object_list, text
async def call_Generate(prim_info, prompt, use_gpt, use_deepsearch, progress_widget, target, agent_task_path):
try:
run_loop = asyncio.get_event_loop()
progress_widget.show_bar(True)
progress_bar_task = run_loop.create_task(progress_widget.play_anim_forever())
response = ""
#chain the prompt
area_name = prim_info.area_name
concat_prompt = area_name[-1].replace("_", " ") + ", " + str(prim_info.length) + "x" + str(prim_info.width) + ", origin at (0.0, 0.0, 0.0), generate a list of appropriate items in the correct places. " + prompt
if use_gpt: #when calling the API
objects, response = await chatGPT_call(concat_prompt)
else: #when testing and you want to skip the API call
data = json.loads(gpt_office_1)
objects = data['area_objects_list']
if objects is None:
return
agent_name = "kit"
# region Check if agent sub-layer exists else create
stage = omni.usd.get_context().get_stage()
root_layer: Sdf.Layer = stage.GetRootLayer()
root_directory = os.path.dirname(root_layer.realPath)
sub_layers = root_layer.subLayerPaths
sub_layer_path = root_directory + "/" + agent_name + ".usd"
# This looks for the agent sub_layer in the stage (not on the nucleus server)
# TODO: Make this relative path more flexible
sub_layer = None
for layer in sub_layers:
if layer == sub_layer_path or layer == "./" + agent_name + ".usd":
sub_layer = Sdf.Layer.Find(sub_layer_path)
break
#This assumes that if the agent sub_layer is not in the stage it does not exist on Nucleus
# HACK: This will fail if the layer with this name exists on nucleus next to the root scene
if not sub_layer:
sub_layer = Sdf.Layer.CreateNew(sub_layer_path)
root_layer.subLayerPaths.append(sub_layer.identifier)
# endregion
# set the agent layer as the edit target
stage.SetEditTarget(sub_layer)
target_variant_sets = target.GetVariantSets()
color_variant_set = target_variant_sets.GetVariantSet("Kit")
if not color_variant_set:
color_variant_set = target_variant_sets.AddVariantSet("Kit")
variant_count = len(color_variant_set.GetVariantNames())
variant_index = variant_count + 1
root_prim_path = target.GetPath().pathString + "/AIResults_" + "{:02d}".format(variant_index) + "/"
# HACK: Hard-coded leading zeros, should look at how many variant are there
# and then rename existing variants if necessary to add 0s as needed
variant_name = "Version_" + "{:02d}".format(variant_index)
color_variant_set.AddVariant(variant_name)
color_variant_set.SetVariantSelection(variant_name)
# With VariantContext
with color_variant_set.GetVariantEditContext():
if use_deepsearch:
settings = carb.settings.get_settings()
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
if nucleus_path == "" or nucleus_path == "(ENTERPRISE ONLY) Enter Nucleus Path Here":
nucleus_path = "omniverse://ov-simready/"
filter_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/filter_path")
filter_paths = filter_path.split(',')
if len(filter_paths) == 0 or (len(filter_paths) == 1 and filter_paths[0] == ""):
filter_paths = ["/Projects/simready_content/common_assets/props/",
"/Projects/simready_content/common_assets/vehicle/toyota/forklift/",
"/Projects/simready_content/common_assets/props_vegetation/"]
queries = list()
for item in objects:
queries.append(item['object_name'])
query_result = await query_items(queries=queries, url=nucleus_path, paths=filter_paths)
# query_result = json.loads(ds_office_1)
if query_result is not None and len(query_result) > 0:
carb.log_info("placing deepsearch results")
place_deepsearch_results(
gpt_results=objects,
query_result=query_result,
root_prim_path=root_prim_path,
prim_info=prim_info)
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
carb.log_info("results placed")
else:
place_greyboxes(
gpt_results=objects,
root_prim_path=root_prim_path)
# Change the layer edit target back to the root layer
stage.SetEditTarget(root_layer)
except:
carb.log_error("gpt or deepsearch failed")
finally:
progress_bar_task.cancel
await asyncio.sleep(1)
progress_widget.show_bar(False)
| 7,951 | Python | 42.217391 | 218 | 0.600302 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/style.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
from pathlib import Path
icons_path = Path(__file__).parent.parent.parent.parent / "icons"
gen_ai_style = {
"HStack": {
"margin": 3
},
"Button.Image::create": {"image_url": f"{icons_path}/plus.svg", "color": 0xFF00B976},
"Button.Image::properties": {"image_url": f"{icons_path}/cog.svg", "color": 0xFF989898},
"Line": {
"margin": 3
},
"Label": {
"margin_width": 5
}
}
guide = """
Step 1: Select your Room
- Select your room and then click the '+' button. This will fill your room's path into the Area path box.
Step 2: Prompt
- Type in a prompt that you want to send along to ChatGPT. This can be information about what is inside of the room.
For example, "generate a comfortable reception area that contains a front desk and an area for guest to sit down".
Step 3: Generate
- Select 'use ChatGPT' if you want to recieve a response from ChatGPT otherwise it will use a premade response.
To use GPT you will need to enter an Open AI API key in the settings by clicking on the gear icon.
- Select 'use Deepsearch' if you want to use the deepsearch functionality.
To use Deepsearch you will need a connection to an enterprise nucleus server with deepsearch enabled.
Enter the path to this server in the "Nucleus Path" setting.
Enter folder paths with props (rather than scenes) separated by commas (no spaces) in the "Path Filter" setting.
When deepsearch is false it will spawn in cubes that greybox the scene.
- Hit Generate, after hitting generate it will start making the appropriate calls. Loading bar will be shown as api-calls are being made.
- Note: This extension assumes your scene is Y-up and that your assets are scaled in meters.
Step 4: More Rooms
- To add another room you can repeat Steps 1-3.
- If you do not like the items it generated, you can hit the generate button until you are satisfied with the items.
""" | 2,617 | Python | 43.372881 | 137 | 0.727933 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/item_generator.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#hotkey
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from pxr import Usd, Sdf, Gf
from .utils import scale_object_if_needed, apply_material_to_prim, create_prim, set_transformTRS_attrs
def place_deepsearch_results(gpt_results, query_result, root_prim_path, prim_info):
index = 0
max_x = sys.float_info.min
max_y = sys.float_info.min
index = 0
#region determine scaling
for item in query_result:
next_object = gpt_results[index]
index = index + 1
# find the furthest object out in each direction
x_bound = next_object['X']
y_bound = next_object['Z']
if abs(x_bound) > max_x:
max_x = abs(x_bound)
if abs(y_bound) > max_y:
max_y = abs(y_bound)
# multiply by to (from 'radius' to diameter)
max_x = max_x * 2
max_y = max_y * 2
# The factory is scaled up by 100....need to figure out how to get these global numbers...
x_scale = (prim_info.length * 0.65) / max_x / 100
y_scale = (prim_info.width * 0.65) / max_y / 100
#endregion
index = 0
for item in query_result:
item_name = item[0]
item_paths = item[1]
# Define Prim
prim_parent_path = root_prim_path + item_name.replace(" ", "_")
prim_path = prim_parent_path + "/" + item_name.replace(" ", "_")
parent_prim = create_prim(prim_parent_path)
item_variant_sets = parent_prim.GetVariantSets()
item_variant_set = item_variant_sets.GetVariantSet("Deepsearch")
if not item_variant_set:
item_variant_set = item_variant_sets.AddVariantSet("Deepsearch")
# region start variants here
for item_path in item_paths:
variant_count = len(item_variant_set.GetVariantNames())
variant_index = variant_count + 1
variant_name = "Version_" + "{:02d}".format(variant_index)
item_variant_set.AddVariant(variant_name)
item_variant_set.SetVariantSelection(variant_name)
with item_variant_set.GetVariantEditContext():
next_prim = create_prim(prim_path)
# Add reference to USD Asset
references: Usd.references = next_prim.GetReferences()
# TODO: The query results should returnt he full path of the prim
references.AddReference(
assetPath="omniverse://ov-simready" + item_path)
# Add reference for future search refinement
config = next_prim.CreateAttribute("DeepSearch:Query", Sdf.ValueTypeNames.String)
config.Set(item_name)
item_variant_set.SetVariantSelection("Version_01")
# endregion end variant here
# HACK: All "GetAttribute" calls should need to check if the attribute exists
# translate prim
next_object = gpt_results[index]
index = index + 1
x = next_object['X'] * x_scale * 100
y = next_object['Y'] * 1
z = next_object['Z'] * y_scale * 100
set_transformTRS_attrs(parent_prim, Gf.Vec3d(x, y, z), Gf.Vec3d(-90, 0, 0), Gf.Vec3d(1, 1, 1))
scale_object_if_needed(prim_parent_path)
def place_greyboxes(gpt_results, root_prim_path):
index = 0
for item in gpt_results:
# Define Prim
prim_parent_path = root_prim_path + item['object_name'].replace(" ", "_")
prim_path = prim_parent_path + "/" + item['object_name'].replace(" ", "_")
# Define Dimensions and material
length = item['Length']
width = item['Width']
height = item['Height']
x = item['X']
y = item['Z'] # shift bottom of object to y=0
z = item['Y'] + height / 2
material = item['Material']
# Create Prim
parent_prim = create_prim(prim_parent_path)
set_transformTRS_attrs(parent_prim)
prim = create_prim(prim_path, 'Cube')
set_transformTRS_attrs(prim, translate=Gf.Vec3d(x, z, y), scale=Gf.Vec3d(length, width, height), rotate=Gf.Vec3d(-90, 0, 0))
prim.GetAttribute('extent').Set([(-0.5, -0.5, -0.5), (0.5, 0.5, 0.5)])
prim.GetAttribute('size').Set(1)
index = index + 1
# Add Attribute and Material
attr = prim.CreateAttribute("object_name", Sdf.ValueTypeNames.String)
attr.Set(item['object_name'])
apply_material_to_prim(material, prim_path)
| 5,165 | Python | 36.708029 | 132 | 0.601162 |
roadwarriorslive/AI-Room-Gen/exts/omni.example.airoomgenerator/omni/example/airoomgenerator/window.py | # SPDX-FileCopyrightText: Copyright (c) 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import omni.ui as ui
import omni.usd
import carb
import asyncio
import omni.kit.commands
from omni.kit.window.popup_dialog.form_dialog import FormDialog
from .utils import CreateCubeFromCurve
from .style import gen_ai_style, guide
from .chatgpt_apiconnect import call_Generate
from .priminfo import PrimInfo
from pxr import Sdf
from .widgets import ProgressBar
class GenAIWindow(ui.Window):
progress = None
use_deepsearch = None
use_chatgpt = None
def __init__(self, title: str, **kwargs) -> None:
super().__init__(title, **kwargs)
# Models
self._path_model = ui.SimpleStringModel()
self._prompt_model = ui.SimpleStringModel("generate warehouse objects")
GenAIWindow.use_deepsearch = ui.SimpleBoolModel(True)
GenAIWindow.use_chatgpt = ui.SimpleBoolModel(True)
self.response_log = None
self.current_index = -1
self.current_area = None
self.frame.set_build_fn(self._build_fn)
def _build_fn(self):
with self.frame:
with ui.ScrollingFrame():
with ui.VStack(style=gen_ai_style):
with ui.HStack(height=0):
ui.Label("Content Generatation with ChatGPT", style={"font_size": 18})
ui.Button(name="properties", tooltip="Configure API Key and Nucleus Path", width=30, height=30, clicked_fn=lambda: self._open_settings())
with ui.CollapsableFrame("Getting Started Instructions", height=0, collapsed=True):
ui.Label(guide, word_wrap=True)
ui.Line()
with ui.HStack(height=0):
ui.Label("Area Path", width=ui.Percent(30))
ui.StringField(model=self._path_model)
ui.Button(name="create", width=30, height=30, clicked_fn=lambda: self._get_area_path())
ui.Line()
with ui.HStack(height=ui.Percent(50)):
ui.Label("Prompt", width=0)
ui.StringField(model=self._prompt_model, multiline=True)
ui.Line()
with ui.HStack(height=0):
ui.Spacer()
ui.Label("Use ChatGPT: ")
ui.CheckBox(model=GenAIWindow.use_chatgpt)
ui.Label("Use Deepsearch: ", tooltip="ENTERPRISE USERS ONLY")
ui.CheckBox(model=GenAIWindow.use_deepsearch)
ui.Spacer()
with ui.HStack(height=0):
ui.Spacer(width=ui.Percent(10))
ui.Button("Generate", height=40,
clicked_fn=lambda: self._generate())
ui.Spacer(width=ui.Percent(10))
GenAIWindow.progress = ProgressBar()
with ui.CollapsableFrame("ChatGPT Response / Log", height=0, collapsed=True):
self.response_log = ui.Label("", word_wrap=True)
def _save_settings(self, dialog):
values = dialog.get_values()
settings = carb.settings.get_settings()
settings.set_string("/persistent/exts/omni.example.airoomgenerator/APIKey", values["APIKey"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path", values["deepsearch_nucleus_path"])
settings.set_string("/persistent/exts/omni.example.airoomgenerator/path_filter", values["path_filter"])
dialog.hide()
def _open_settings(self):
settings = carb.settings.get_settings()
apikey_value = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/APIKey")
nucleus_path = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/deepsearch_nucleus_path")
path_filter = settings.get_as_string("/persistent/exts/omni.example.airoomgenerator/path_filter")
if apikey_value == "":
apikey_value = "Enter API Key Here"
if nucleus_path == "":
nucleus_path = "(ENTERPRISE ONLY) Enter Nucleus Path Here"
if path_filter == "":
path_filter = ""
field_defs = [
FormDialog.FieldDef("APIKey", "API Key: ", ui.StringField, apikey_value),
FormDialog.FieldDef("deepsearch_nucleus_path", "Nucleus Path: ", ui.StringField, nucleus_path),
FormDialog.FieldDef("path_filter", "Path Filter: ", ui.StringField, path_filter)
]
dialog = FormDialog(
title="Settings",
message="Your Settings: ",
field_defs = field_defs,
ok_handler=lambda dialog: self._save_settings(dialog))
dialog.show()
def rebuild_frame(self):
# we do want to update the area name and possibly last prompt?
attr_prompt = self.get_prim().GetAttribute('genai:prompt')
if attr_prompt.IsValid():
self._prompt_model.set_value(attr_prompt.Get())
else:
self._prompt_model.set_value("")
self.frame.rebuild()
def _generate(self):
target = self.get_prim()
attr = target.GetAttribute('genai:prompt')
if not attr.IsValid():
attr = target.CreateAttribute('genai:prompt', Sdf.ValueTypeNames.String)
attr.Set(self.get_prompt())
run_loop = asyncio.get_event_loop()
run_loop.create_task(call_Generate(
get_prim_info(target, target.GetName()),
self.get_prompt(),
GenAIWindow.use_chatgpt.as_bool, # use chatGPT
GenAIWindow.use_deepsearch.as_bool, # use DeepSearch
GenAIWindow.progress,
target,
agent_task_path=""))
# # Get the selected area path
def _get_area_path(self):
self._path_model.set_value(self.get_prim_path())
# # Get the prim path specified
def get_prim_path(self):
ctx = omni.usd.get_context()
selection = ctx.get_selection().get_selected_prim_paths()
if len(selection) > 0:
return str(selection[0])
carb.log_warn("No Prim Selected")
return ""
# Get the prompt specified
def get_prompt(self):
if self._prompt_model == "":
carb.log_warn("No Prompt Provided")
return self._prompt_model.as_string
# Get the prim based on the Prim Path
def get_prim(self):
ctx = omni.usd.get_context()
stage = ctx.get_stage()
prim = stage.GetPrimAtPath(self._path_model.as_string)
if prim.IsValid() is None:
carb.log_warn("No valid prim in the scene")
return prim
def destroy(self):
super().destroy()
self._path_model = None
self._prompt_model = None
self._use_deepsearch = None
self._use_chatgpt = None
# Returns a PrimInfo object containing the Length, Width, Origin and Area Name
def get_prim_info(prim, area_name: str) -> PrimInfo:
prim_info = None
if prim.IsValid():
prim_info = PrimInfo(prim, area_name)
return prim_info
| 7,989 | Python | 41.275132 | 161 | 0.587433 |
MikeWise2718/sphereflake22/README.md | # Extension Project SphereFlake Benchmark for Omniverse
Tested and works with Python 3.7 and 3.10 and Omniverse Kit 104 and 105
# To use
- Add it to create or code by adding to the Extension Search Path:
- Under `Window/Extensions` then click on the gear (or lately the hamburger menu in the top middle part of the dialog box)
- in the general case: `(your ext subdir root)/sphereflake22/exts`
- in my case: `d:/nv/ov/ext/sphereflake22/exts`
# Program Structure
- The core are the objects in the subdir `sfgen`
- `SphereFlake` - in `sphereflake.py` an object that construcsts sphereflakes in various ways
- `SphereMesh` - in `spheremesh.py` an object that constructs a spheremesh when needed
- `sfut.MatMan` - in `sfut.py` an object that manages the materials, fetching them when needed
- Additionally there are two main control classes
- `sfwindow` - in `sfwindow.py` and does all the UI and the only file that imports `Omni.ui`
- `sfcontrol` - in `sfcontrol.py` anddoes all the control logic (it has gotten a bit big)
- For UI there are a number of files organized by tabs
- `sfwintabs.py` - Most tabs
- `sfwinsess.py` - the session tab
# Adding UI ELements
## Adding a tab
- Add tab class, to `sfwintabs` probably, or to its own file if it is large
- Add invocation to `sfwindow` build function
- No settings
## Adding a collapsable frame
- Example "Ground Settings" collapsable frame
- `sfwindow.py` -Add variables to class `SfWindow` as member variables
- `optgroundframe: ui.CollapsableFrame = None`
- `docollapse_optgroundframe = False`
- `sfwindow.py` - Add load/save functionality to `LoadSettings` and `SaveSettings` for collapsed state
- `self.docollapse_optgroundframe = get_setting("ui_opt_groundframe", False)`
- `save_setting("ui_opt_logframe", self.optlogframe.collapsed)`
- `sfwintabspy` - Add frame to tab class
- `sfw.optgroundframe = ui.CollapsableFrame("Ground Settings", collapsed=sfw.docollapse_optremoteframe)`
- `sfwintabspy` - Add additional ui code to tab class:
- `with sfw.optgroundframe:`
## Adding a button to do something
- Example "Reset Materials"
- `sfwindow.py` - Add variables to class `SfWindow` as member variables (not needed here)
- `sfwintabs.py` - Add button code with lambda function (might need to move it because of width)
```
sfw.reset_materials_but = ui.Button(f"Reset Materials",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_resetmaterials())
```
- Add click function:
```
def on_click_resetmaterials(self):
self._matman.Reinitialize()
nmat = self._matman.GetMaterialCount()
self.sfw.reset_materials_but.text = f"Reset Materials ({nmat} defined)"
```
## Adding a checkbox
- Example "Add Rand" checkbox
- Decide if control variable belongs in Controller or in an object (like SphereFlake)
- Here we are putting it in the Controller "SfControl" class
- `sfwindow.py` - Add variables to class `SfWindow` as member variables
- `addrand_checkbox: ui.CheckBox = None`
- `addrand_checkbox_model: ui.SimpleBoolModel = None`
- `sfcontrol.py` - Add state variable to class `SfControl` as member variable
- `p_addrand = False`
- `sfcontrol.py` - Add load/save functionality for state variable to class `SfControl` in `LoadSettings` and `SaveSettings`
- `self.p_addrand = get_setting("p_addrand", False)`
- `save_setting("p_addrand", self.p_addrand)`
- `sfwindow.py` - Add initialization code for `SimpleBoolModel`
- self.addrand_checkbox_model = ui.SimpleBoolModel(sfc.p_addrand)
- `sfwintabs.py` - Add checkbox functionality
## Adding a stringfield
## Adding a combobox
## Adding a slider
| 3,971 | Markdown | 42.648351 | 126 | 0.672878 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwintabs.py | import omni.ui as ui
import asyncio
from ._widgets import BaseTab
from .sfgen.sphereflake import SphereFlakeFactory
from .sfcontrols import SfControls
from .sfwindow import SfWindow
class SfcTabMulti(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Multi")
self.sfw = sfw
self.sfc = sfw.sfc
# print(f"SfcTabMulti.init {type(sfc)}")
def build_fn(self):
# print("SfcTabMulti.build_fn (trc)")
sfw: SfWindow = self.sfw
sfc: SfControls = self.sfc
sff: SphereFlakeFactory = self.sfw.sff
# print(f"SfcTabMulti.build_fn {type(sfc)}")
with ui.VStack(style={"margin": sfw.marg}):
with ui.VStack():
with ui.HStack():
clkfn = lambda: asyncio.ensure_future(sfc.on_click_multi_sphereflake()) # noqa : E731
sfw._msf_spawn_but = ui.Button("Multi ShereFlake",
style={'background_color': sfw.darkred},
clicked_fn=clkfn)
with ui.VStack(width=200):
clkfn = lambda x, y, b, m: sfc.on_click_sfx(x, y, b, m) # noqa : E731
sfw._nsf_x_but = ui.Button(f"SF x: {sff.p_nsfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_sfy(x, y, b, m) # noqa : E731
sfw._nsf_y_but = ui.Button(f"SF y: {sff.p_nsfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_sfz(x, y, b, m) # noqa : E731
sfw._nsf_z_but = ui.Button(f"SF z: {sff.p_nsfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
sfw._tog_bounds_but = ui.Button(f"Bounds:{sfc._bounds_visible}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_bounds)
sfw.prframe = ui.CollapsableFrame("Partial Renders", collapsed=sfw.docollapse_prframe)
with sfw.prframe:
with ui.VStack():
sfw._partial_render_but = ui.Button(f"Partial Render {sff.p_partialRender}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_partial_render)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsx(x, y, b, m) # noqa : E731
sfw._part_nsf_sx_but = ui.Button(f"SF partial sx: {sff.p_partial_ssfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsy(x, y, b, m) # noqa : E731
sfw._part_nsf_sy_but = ui.Button(f"SF partial sy: {sff.p_partial_ssfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfsz(x, y, b, m) # noqa : E731
sfw._part_nsf_sz_but = ui.Button(f"SF partial sz: {sff.p_partial_ssfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnx(x, y, b, m) # noqa : E731
sfw._part_nsf_nx_but = ui.Button(f"SF partial nx: {sff.p_partial_nsfx}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfny(x, y, b, m) # noqa : E731
sfw._part_nsf_ny_but = ui.Button(f"SF partial ny: {sff.p_partial_nsfy}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parital_sfnz(x, y, b, m) # noqa : E731
sfw._part_nsf_nz_but = ui.Button(f"SF partial nz: {sff.p_partial_nsfz}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
sfw.drframe = ui.CollapsableFrame("Distributed Renders", collapsed=sfw.docollapse_drframe)
with sfw.drframe:
with ui.VStack():
sfw._parallel_render_but = ui.Button(f"Distributed Render {sff.p_parallelRender}",
style={'background_color': sfw.darkcyan},
clicked_fn=sfc.toggle_parallel_render)
with ui.HStack():
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nxbatch(x, y, b, m) # noqa : E731
sfw._parallel_nxbatch_but = ui.Button(f"SF batch x: {sff.p_parallel_nxbatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nybatch(x, y, b, m) # noqa : E731
sfw._parallel_nybatch_but = ui.Button(f"SF batch y: {sff.p_parallel_nybatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
clkfn = lambda x, y, b, m: sfc.on_click_parallel_nzbatch(x, y, b, m) # noqa : E731
sfw._parallel_nzbatch_but = ui.Button(f"SF batch z: {sff.p_parallel_nzbatch}",
style={'background_color': sfw.darkblue},
mouse_pressed_fn=clkfn)
class SfcTabSphereFlake(BaseTab):
sfc: SfControls = None
def __init__(self, sfw: SfWindow):
super().__init__("SphereFlake")
self.sfw = sfw
self.sfc = sfw.sfc
def build_fn(self):
# print("SfcTabSphereFlake.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc
sff = self.sfw.sff
smf = self.sfw.smf
# print(f"SfcTabMulti.build_fn sfc:{type(sfc)} ")
with ui.VStack(style={"margin": sfw.marg}):
with ui.VStack():
with ui.HStack():
sfw._sf_spawn_but = ui.Button("Spawn SphereFlake",
style={'background_color': sfw.darkred},
clicked_fn=lambda: sfc.on_click_sphereflake())
with ui.VStack(width=200):
sfw._sf_depth_but = ui.Button(f"Depth:{sff.p_depth}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_sfdepth(x, y, b, m))
with ui.HStack():
ui.Label("Radius Ratio: ",
style={'background_color': sfw.darkgreen},
width=50)
sfw._sf_radratio_slider = ui.FloatSlider(model=sfw._sf_radratio_slider_model,
min=0.0, max=1.0, step=0.01,
style={'background_color': sfw.darkblue}).model
# SF Gen Mode Combo Box
with ui.HStack():
ui.Label("Gen Mode:")
model = sfw._genmodebox_model
idx = model.as_int
sfw._genmodebox_model = ui.ComboBox(idx, *sff.GetGenModes()).model.get_item_value_model()
# SF Form Combo Box
with ui.HStack():
ui.Label("Gen Form1:")
model = sfw._genformbox_model
idx = model.as_int
sfw._genformbox_model = ui.ComboBox(idx, *sff.GetGenForms()).model.get_item_value_model()
with ui.VStack():
sfw._sf_nlat_but = ui.Button(f"Nlat:{smf.p_nlat}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_nlat(x, y, b, m))
sfw._sf_nlng_but = ui.Button(f"Nlng:{smf.p_nlng}",
style={'background_color': sfw.darkgreen},
mouse_pressed_fn= # noqa : E251
lambda x, y, b, m: sfc.on_click_nlng(x, y, b, m))
class SfcTabShapes(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Shapes")
self.sfw = sfw
self.sfc = sfw.sfc
def build_fn(self):
# print("SfcTabShapes.build_fn (trc)")
sfc = self.sfc
sfw = self.sfw
# print(f"SfcTabShapes.build_fn {type(sfc)}")
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
sfw._sf_spawn_but = ui.Button("Spawn Prim",
style={'background_color': sfw.darkred},
clicked_fn=lambda: sfc.on_click_spawnprim())
sfw._sf_primtospawn_but = ui.Button(f"{sfc._curprim}",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_changeprim())
class SfcTabMaterials(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Materials")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabMaterials.build_fn {sfc}")
def build_fn(self):
# print("SfcTabMaterials.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc
with ui.VStack(style={"margin": sfw.marg}):
# Material Combo Box
with ui.HStack():
ui.Label("SF Material 1:")
idx = sfc._matkeys.index(sfc._current_material_name)
sfw._sf_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_matbox_model = sfw._sf_matbox.model.get_item_value_model()
print("built sfw._sf_matbox")
with ui.HStack():
ui.Label("SF Material 2:")
# use the alternate material name
idx = sfc._matkeys.index(sfc._current_alt_material_name)
sfw._sf_alt_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_alt_matbox_model = sfw._sf_alt_matbox.model.get_item_value_model()
print("built sfw._sf_matbox")
# Bounds Material Combo Box
with ui.HStack():
ui.Label("Bounds Material:")
idx = sfc._matkeys.index(sfc._current_bbox_material_name)
sfw._bb_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._bb_matbox_model = sfw._bb_matbox.model.get_item_value_model()
# Bounds Material Combo Box
with ui.HStack():
ui.Label("Floor Material:")
idx = sfc._matkeys.index(sfc._current_floor_material_name)
sfw._sf_floor_matbox = ui.ComboBox(idx, *sfc._matkeys)
sfw._sf_floor_matbox_model = sfw._sf_floor_matbox.model.get_item_value_model()
sfw.reset_materials_but = ui.Button(f"Reset Materials",
style={'background_color': sfw.darkpurple},
clicked_fn=lambda: sfc.on_click_resetmaterials())
class SfcTabOptions(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Options")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}):
sfw.optlogframe = ui.CollapsableFrame("Logging Parameters", collapsed=sfw.docollapse_optlogframe)
with sfw.optlogframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Write Perf Log: ")
sfw.writelog_checkbox = ui.CheckBox(model=sfw.writelog_checkbox_model,
width=40, height=10, name="writelog", visible=True)
with ui.HStack():
ui.Label("Log Series Name:")
sfw.writelog_seriesname = ui.StringField(model=sfw.writelog_seriesname_model,
width=200, height=20, visible=True)
sfw.optremoteframe = ui.CollapsableFrame("Remote Processing", collapsed=sfw.docollapse_optremoteframe)
with sfw.optremoteframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Do Remote: ")
sfw.doremote_checkbox = ui.CheckBox(model=sfw.doremote_checkbox_model,
width=40, height=10, name="doremote", visible=True)
with ui.HStack():
ui.Label("Register Remote Endpoints: ")
sfw.doregister_remote_checkbox = ui.CheckBox(model=sfw.doregister_remote_checkbox_model,
width=40, height=10,
name="register endpoint", visible=True)
with ui.HStack():
ui.Label("Remote Type:")
# idx = sfc._remotetypes.index(sfc.p_doremotetype)
idx = sfc._remotetypes.index(sfc.p_doremotetype)
sfw.doremote_type = ui.ComboBox(idx, *sfc._remotetypes)
sfw.doremote_type_model = sfw.doremote_type.model.get_item_value_model()
with ui.HStack():
ui.Label("Remote URL:")
sfw.doremote_url = ui.StringField(model=sfw.doremote_url_model,
width=400, height=20, visible=True)
sfw.optgroundframe = ui.CollapsableFrame("Ground Settings", collapsed=sfw.docollapse_optremoteframe)
with sfw.optgroundframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Add Rand")
sfw.addrand_checkbox = ui.CheckBox(model=sfw.addrand_checkbox_model,
width=40, height=10, name="addrand", visible=True)
class SfcTabPhysics(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Physics")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}):
sfw.physcollidersframe = ui.CollapsableFrame("Colliders", collapsed=sfw.docollapse_physcollidersframe)
with sfw.physcollidersframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Equip Objects for Phyics: ")
sfw.equipforphysics_checkbox = ui.CheckBox(model=sfw.equipforphysics_checkbox_model,
width=40, height=10, name="equipforphysics",
visible=True)
| 17,875 | Python | 53.334346 | 117 | 0.443413 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/extension.py | import omni.ext # this needs to be included in an extension's extension.py
from .ovut import write_out_syspath, write_out_path
from .sfgen.sfut import MatMan
from .sfgen.sphereflake import SphereMeshFactory, SphereFlakeFactory
from .sfcontrols import SfControls
from .sfwindow import SfWindow
import omni.kit.extensions
import carb
import carb.events
import time
from pxr import Usd
# Omni imports
# import omni.client
# import omni.usd_resolver
# import os
# import contextlib
# @contextlib.asynccontextmanager
update_count = -1
start_time = time.time()
last_update_time = start_time
triggered_show = False
initialized_objects = False
gap = 1.0
_instance_handle: omni.ext.IExt = None
def on_update_event(e: carb.events.IEvent):
global update_count, last_update_time, triggered_show, start_time, instance_handle, gap
update_count += 1
# if update_count % 50 == 0:
# print(f"Update: {e.payload} count: {update_count} (trc)")
elap = time.time() - last_update_time
if elap > gap:
last_update_time = time.time()
totelap = time.time() - start_time
# stage = omni.usd.get_context().get_stage()
# stagewd = stage if stage is not None else "None"
# print(f"on_update_event {update_count} {totelap:.3f}: typ:{e.type} pay:{e.payload} elap: {elap:.3f} stage:{stagewd} (trc)")
if not triggered_show and totelap > 10:
if _instance_handle is not None and _instance_handle._sfw is not None:
print("Triggering ShowTheDamnWindow (trc)")
_instance_handle._sfw.ShowTheDamnWindow()
_instance_handle._sfw.DockWindow()
triggered_show = True
gap = 5.0
def on_stage_event(e: carb.events.IEvent):
global initialized_objects, instance_handle, update_count, start_time
totelap = time.time() - start_time
print(f"on_stage_event {update_count} {totelap:.3f} typ:{e.type} pay:{e.payload} (trc1)")
if not initialized_objects:
stage = omni.usd.get_context().get_stage()
if stage is not None:
_instance_handle.InitializeObjects()
print("Initializing objectsw (trc)")
initialized_objects = True
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class SphereflakeBenchmarkExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
_window_sfcon = None
_matman: MatMan = None
_smf: SphereMeshFactory = None
_sff: SphereFlakeFactory = None
_sfc: SfControls = None
_sfw: SfWindow = None
_settings = None
_stage: Usd.Stage = None
def WriteOutPathAndSysPath(self, basename="d:/nv/ov/sphereflake_benchmark"):
write_out_syspath(f"{basename}_syspath.txt")
write_out_path(f"{basename}_path.txt")
def setup_event_handlers(self):
update_stream = omni.kit.app.get_app().get_update_event_stream()
self._sub1 = update_stream.create_subscription_to_pop(on_update_event, name="SFB_UpdateSub")
stage_stream = omni.usd.get_context().get_stage_event_stream()
self._sub2 = stage_stream.create_subscription_to_pop(on_stage_event, name="SFB_StageSub")
print("Setup on_stage_event handler")
def InitializeObjects(self):
self._stage = omni.usd.get_context().get_stage()
# sesslayer = self._stage.GetSessionLayer()
# rootlayer = self._stage.GetRootLayer()
# print(f"Sesslayer: {sesslayer} (trc)")
# print(f"Rootlayer: {rootlayer} (trc)")
print(f"SphereflakeBenchmarkExtension on_startup - stage:{self._stage} (trc)")
self._stageid = omni.usd.get_context().get_stage_id()
# pid = os.getpid()
# Write out syspath and path
# self.WriteOutPathAndSysPath()
# Model objects
self._matman = MatMan(self._stage)
self._smf = SphereMeshFactory(self._stage, self._matman)
self._sff = SphereFlakeFactory(self._stage, self._matman, self._smf)
self._sff.LoadSettings()
# Controller objects
self._sfc = SfControls(self._matman, self._smf, self._sff)
print("SphereflakeBenchmarkExtension - _sfc assigned (trc)")
# View objects
self._sfw = SfWindow(sfc=self._sfc)
print("SphereflakeBenchmarkExtension - _sfw assigned (trc)")
self._sfw.DockWindow()
self._sfw.ShowTheDamnWindow()
print("SphereflakeBenchmarkExtension - InitialzeObjects done (trc)")
def on_startup(self, ext_id):
global _instance_handle
_instance_handle = self
print(f"[{ext_id}] SphereflakeBenchmarkExtension on_startup (trc))")
self._ext_id = ext_id
self.setup_event_handlers()
print("Subscribing to update events")
print(f"[{self._ext_id}] SphereflakeBenchmarkExtension on_startup - done (trc))")
def on_shutdown(self):
global initialized_objects
try:
print(f"[{self._ext_id}] SphereflakeBenchmarkExtension on_shutdown objs_inited:{initialized_objects}")
if initialized_objects:
if self._sfc is not None:
self._sfc.SaveSettings()
self._sfc.Close()
else:
carb.log_error(f"on_shutdown - _sfc is Unexpectedly None objs_inited:{initialized_objects}")
if self._sfw is not None:
self._sfw.SaveSettings()
self._sfw.destroy()
else:
carb.log_error(f"on_shutdown - _sfw is Unexpectedly None objs_inited:{initialized_objects}")
except Exception as e:
carb.log_error(f"on_shutdown - Exception: {e}")
| 5,990 | Python | 38.156862 | 133 | 0.644073 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/ovut.py | import omni.usd
import os
import sys
import math
import carb.settings
_settings = None
def _init_settings():
global _settings
if _settings is None:
_settings = carb.settings.get_settings()
return _settings
def get_setting(name, default, db=False):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
val = settings.get(key)
if db:
oval = val
if oval is None:
oval = "None"
if val is None:
val = default
if db:
print(f"get_setting {name} {oval} {val}")
return val
def save_setting(name, value):
settings = _init_settings()
key = f"/persistent/omni/sphereflake/{name}"
settings.set(key, value)
def truncf(number, digits) -> float:
# Improve accuracy with floating point operations, to avoid truncate(16.4, 2) = 16.39 or truncate(-1.13, 2) = -1.12
nbDecimals = len(str(number).split('.')[1])
if nbDecimals <= digits:
return number
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
def delete_if_exists(primpath: str) -> None:
ctx = omni.usd.get_context()
stage = ctx.get_stage()
if stage.GetPrimAtPath(primpath):
stage.RemovePrim(primpath)
# okc.execute("DeletePrimsCommand", paths=[primpath])
def write_out_path(fname: str = 'd:/nv/ov/path.txt') -> None:
# Write out the path to a file
path = os.environ["PATH"]
with open(fname, "w") as f:
npath = path.replace(";", "\n")
f.write(npath)
def write_out_syspath(fname: str = 'd:/nv/ov/syspath.txt', indent=False) -> None:
# Write out the python syspath to a file
# Indent should be True if to be used for the settings.json python.analsys.extraPaths setting
pplist = sys.path
with open(fname, 'w') as f:
for line in pplist:
nline = line.replace("\\", "/")
if indent:
nnline = f" \"{nline}\",\n"
else:
nnline = f"\"{nline}\",\n"
f.write(nnline)
def read_in_syspath(fname: str = 'd:/nv/ov/syspath.txt') -> None:
# Read in the python path from a file
with open(fname, 'r') as f:
for line in f:
nline = line.replace(',', '')
nline = nline.replace('"', '')
nline = nline.replace('"', '')
nline = nline.replace('\n', '')
nline = nline.replace(' ', '')
sys.path.append(nline)
| 2,463 | Python | 26.076923 | 119 | 0.577751 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwindow.py | import omni.ui as ui
from omni.ui import color as clr
from .sfgen.sphereflake import SphereMeshFactory, SphereFlakeFactory
from .sfcontrols import SfControls
from ._widgets import TabGroup
from .ovut import get_setting, save_setting
import carb
class SfWindow(ui.Window):
darkgreen = clr("#004000")
darkblue = clr("#000040")
darkred = clr("#400000")
darkyellow = clr("#404000")
darkpurple = clr("#400040")
darkcyan = clr("#004040")
marg = 2
# Status
_statuslabel: ui.Label = None
_memlabel: ui.Label = None
# Sphereflake params
prframe: ui.CollapsableFrame = None
drframe: ui.CollapsableFrame = None
physcollidersframe: ui.CollapsableFrame = None
optlogframe: ui.CollapsableFrame = None
optremoteframe: ui.CollapsableFrame = None
optgroundframe: ui.CollapsableFrame = None
optstartupframe: ui.CollapsableFrame = None
docollapse_prframe = False
docollapse_drframe = False
docollapse_optlogframe = False
docollapse_physcollidersframe = False
docollapse_optremoteframe = False
docollapse_optgroundframe = False
docollapse_optstartupframe = False
_sf_depth_but: ui.Button = None
_sf_spawn_but: ui.Button = None
_sf_nlat_but: ui.Button = None
_sf_nlng_but: ui.Button = None
_sf_radratio_slider_model: ui.SimpleFloatModel = None
_genmodebox: ui.ComboBox = None
_genmodebox_model: ui.SimpleIntModel = None
_genformbox: ui.ComboBox = None
_genformbox_model: ui.SimpleIntModel = None
# Material tab
_sf_matbox: ui.ComboBox = None
_sf_matbox_model: ui.SimpleIntModel = None
_sf_alt_matbox: ui.ComboBox = None
_sf_alt_matbox_model: ui.SimpleIntModel = None
_bb_matbox: ui.ComboBox = None
_bb_matbox_model: ui.SimpleIntModel = None
_sf_floor_matbox: ui.ComboBox = None
_sf_floor_matbox_model: ui.SimpleIntModel = None
# Options
writelog_checkbox: ui.CheckBox = None
writelog_checkbox_model: ui.SimpleBoolModel = None
writelog_seriesname: ui.StringField = None
writelog_seriesname_model: ui.SimpleStringModel = None
doremote_checkbox: ui.CheckBox = None
doremote_checkbox_model: ui.SimpleBoolModel = None
doremote_type: ui.ComboBox = None
doremote_type_model: ui.SimpleIntModel = None
doremote_url: ui.StringField = None
doremote_url_model: ui.SimpleStringModel = None
doregister_remote_checkbox: ui.CheckBox = None
doregister_remote_checkbox_model: ui.SimpleBoolModel = None
doloadusd_checkbox: ui.CheckBox = None
doloadusd_checkbox_model: ui.SimpleBoolModel = None
doloadusd_url: ui.StringField = None
doloadusd_url_model: ui.SimpleStringModel = None
doloadusd_session_checkbox: ui.CheckBox = None
doloadusd_session_checkbox_model: ui.SimpleBoolModel = None
doloadusd_sessionname: ui.StringField = None
doloadusd_sessionname_model: ui.SimpleStringModel = None
# Ground
addrand_checkbox: ui.CheckBox = None
addrand_checkbox_model: ui.SimpleBoolModel = None
# Physics
equipforphysics_checkbox_model: ui.SimpleBoolModel = None
# state
sfc: SfControls
smf: SphereMeshFactory
sff: SphereFlakeFactory
def __init__(self, *args, **kwargs):
self.wintitle = "SphereFlake Controls"
super().__init__(title=self.wintitle, height=300, width=300, *args, **kwargs)
print("SfWindow.__init__ (trc)")
# print("SfWindow.__init__ (trc)")
self.sfc = kwargs["sfc"]
self.sfc.sfw = self # intentionally circular
self.smf = self.sfc.smf
self.sff = self.sfc.sff
self.LoadSettings()
self.BuildControlModels()
self.BuildWindow()
print("Calling sfc.LateInit")
self.sfc.LateInit()
def ShowTheDamnWindow(self):
ui.Workspace.show_window(self.wintitle, True)
def BuildControlModels(self):
# models for controls that are used in the logic need to be built outside the build_fn
# since that will only be called when the tab is selected and displayed
sfc = self.sfc
sff = sfc.sff
# sphereflake params
self._sf_radratio_slider_model = ui.SimpleFloatModel(sff.p_radratio)
idx = sff.GetGenModes().index(sff.p_genmode)
self._genmodebox_model = ui.SimpleIntModel(idx)
idx = sff.GetGenForms().index(sff.p_genform)
self._genformbox_model = ui.SimpleIntModel(idx)
# materials
matlist = sfc._matkeys
idx = matlist.index(sff.p_sf_matname)
self._sf_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sff.p_sf_alt_matname)
self._sf_alt_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sff.p_bb_matname)
self._bb_matbox_model = ui.SimpleIntModel(idx)
idx = matlist.index(sfc._current_floor_material_name)
self._sf_floor_matbox_model = ui.SimpleIntModel(idx)
# options
self.writelog_checkbox_model = ui.SimpleBoolModel(sfc.p_writelog)
self.writelog_seriesname_model = ui.SimpleStringModel(sfc.p_logseriesname)
self.doremote_checkbox_model = ui.SimpleBoolModel(sfc.p_doremote)
idx = sfc._remotetypes.index(sfc.p_doremotetype)
self.doremote_type_model = ui.SimpleIntModel(idx)
self.doloadusd_checkbox_model = ui.SimpleBoolModel(sfc.p_doloadusd)
self.doloadusd_session_checkbox_model = ui.SimpleBoolModel(sfc.p_doloadusd_session)
self.doremote_url_model = ui.SimpleStringModel(sfc.p_doremoteurl)
self.doloadusd_sessionname_model = ui.SimpleStringModel(sfc.p_doloadusd_sessionname)
self.doloadusd_url_model = ui.SimpleStringModel(sfc.p_doloadusd_url)
self.equipforphysics_checkbox_model = ui.SimpleBoolModel(sfc.p_equipforphysics)
self.doregister_remote_checkbox_model = ui.SimpleBoolModel(sfc.p_register_endpoint)
# Ground
self.addrand_checkbox_model = ui.SimpleBoolModel(sfc.p_addrand)
def BuildWindow(self):
print("SfWindow.BuildWindow (trc1)")
sfc = self.sfc
sfw = self
from .sfwintabs import SfcTabMulti, SfcTabSphereFlake, SfcTabShapes, SfcTabMaterials
from .sfwintabs import SfcTabOptions, SfcTabPhysics
from .sfwinsess import SfcTabSessionInfo
with self.frame:
with ui.VStack():
t1 = SfcTabMulti(self)
t2 = SfcTabSphereFlake(self)
t3 = SfcTabShapes(self)
t4 = SfcTabMaterials(self)
t5 = SfcTabOptions(self)
t6 = SfcTabPhysics(self)
t7 = SfcTabSessionInfo(self)
print("Creating Tab Group (trc1)")
self.tab_group = TabGroup([t1, t2, t3, t4, t5, t6, t7])
if self.start_tab_idx is not None:
self.tab_group.select_tab(self.start_tab_idx)
with ui.HStack():
ui.Button("Clear Primitives",
style={'background_color': self.darkyellow},
clicked_fn=lambda: sfc.on_click_clearprims())
clkfn = lambda x, y, b, m: sfw.on_click_save_settings(x, y, b, m) # noqa : E731
ui.Button("Save Settings",
style={'background_color': self.darkpurple},
mouse_pressed_fn=clkfn)
self._statuslabel = ui.Label("Status: Ready")
self._memlabel = ui.Button("Memory tot/used/free", clicked_fn=sfc.UpdateGpuMemory)
def on_click_setup_code_env(self, x, y, button, modifier):
from omni.kit.window.extensions import ext_controller
extid = "omni.kit.window.extensions"
ext_controller.toggle_autoload(extid, True)
showit = True if button == 0 else False
viewwintitle = "Viewport"
viewhandle = ui._ui.Workspace.get_window(viewwintitle)
extwintitle = "Extensions"
exthandle = ui._ui.Workspace.get_window(extwintitle)
# print(f"Set up environment (trc) exthandle: {exthandle} viewhandle:{viewhandle} showit: {showit}")
if viewhandle is not None:
if exthandle is not None:
exthandle.dock_in(viewhandle, ui._ui.DockPosition.SAME)
ui.Workspace.show_window(extwintitle, showit)
# Environment
brsid0 = "omni.kit.environment.core"
ext_controller.toggle_autoload(brsid0, True)
brsid1 = "omni.kit.property.environment"
ext_controller.toggle_autoload(brsid1, True)
brsid2 = "omni.kit.window.environment"
ext_controller.toggle_autoload(brsid2, True)
envwintitle = "Environments"
ui.Workspace.show_window(envwintitle, showit)
def on_click_save_settings(self, x, y, button, modifier):
self.SaveSettings()
self.sfc.SaveSettings()
print("Saved Settings")
def DockWindow(self, wintitle="Property"):
# print(f"Docking to {wintitle} (trc)")
handle = ui._ui.Workspace.get_window(wintitle)
self.dock_in(handle, ui._ui.DockPosition.SAME)
self.deferred_dock_in(wintitle, ui._ui.DockPolicy.TARGET_WINDOW_IS_ACTIVE)
def LoadSettings(self):
# print("SfWindow.LoadSettings (trc1)")
self.docollapse_prframe = get_setting("ui_pr_frame_collapsed", False)
self.docollapse_drframe = get_setting("ui_dr_frame_collapsed", False)
self.docollapse_physcollidersframe = get_setting("ui_phys_collidersframe", False)
self.docollapse_optlogframe = get_setting("ui_opt_logframe", False)
self.docollapse_optgroundframe = get_setting("ui_opt_groundframe", False)
self.docollapse_optremoteframe = get_setting("ui_opt_remoteframe", False)
self.docollapse_optstartupframe = get_setting("ui_opt_startupframe", False)
self.start_tab_idx = get_setting("ui_selected_tab", 0)
# print(f"SfWindow.LoadSettings start_tab_idx:{self.start_tab_idx} (trc1)")
def SafeSaveFrame(self, name, frame: ui.CollapsableFrame):
try:
if frame is not None:
save_setting(name, frame.collapsed)
except Exception as e:
carb.log_error(f"Exception in SfWindow.SafeSaveFrame - name:{name}: {e}")
def SaveSettings(self):
try:
# print("SfWindow.SaveSettings")
self.SafeSaveFrame("ui_pr_frame_collapsed", self.prframe)
self.SafeSaveFrame("ui_dr_frame_collapsed", self.drframe)
self.SafeSaveFrame("ui_phys_collidersframe", self.physcollidersframe)
self.SafeSaveFrame("ui_opt_logframe", self.optlogframe)
self.SafeSaveFrame("ui_opt_groundframe", self.optgroundframe)
self.SafeSaveFrame("ui_opt_remoteframe", self.optremoteframe)
self.SafeSaveFrame("ui_opt_startupframe", self.optstartupframe)
curidx = self.tab_group.get_selected_tab_index()
save_setting("ui_selected_tab", curidx)
print(f"SaveSettings - ui_selected_tab:{curidx} (trc1)")
except Exception as e:
carb.log_error(f"Exception in SfWindow.SaveSettings: {e}")
# print(f"docollapse_prframe: {self.prframe.collapsed} docollapse_drframe: {self.drframe.collapsed}")
| 11,266 | Python | 40.729629 | 117 | 0.654269 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfwinsess.py | import omni.ui as ui
from ._widgets import BaseTab
from .sfcontrols import SfControls
from .sfwindow import SfWindow
import os
import omni.client
import omni.usd_resolver
# Internal imports
import omni.kit.collaboration.channel_manager as cm
# import omni.kit.layers.live_session_channel_manager as lscm
class LiveSessionInfo:
""" Live Session Info class
This class attempts to collect all of the logic around the live session file paths and URLs.
It should be first instantiated with the stage URL (omniverse://server/folder/stage.usd), then
get_session_folder_path_for_stage() can be used to list the available sessions.
Once a session is selected, set_session_name() will finish the initialization of all of the paths
and the other methods can be used.
In the folder that contains the USD to be live-edited, there exists this folder structure:
<.live> / < my_usd_file.live> / <session_name> / root.live
get_session_folder_path_for_stage: <stage_folder> / <.live> / < my_usd_file.live>
get_live_session_folder_path: <stage_folder> / <.live> / < my_usd_file.live> / <session_name>
get_live_session_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / root.live
get_live_session_toml_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.toml
get_message_channel_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.channel
"""
def __init__(self, stage_url: str):
self.OMNIVERSE_CHANNEL_FILE_NAME = "__session__.channel"
self.LIVE_SUBFOLDER = "/.live"
self.LIVE_SUBFOLDER_SUFFIX = ".live"
self.DEFAULT_LIVE_FILE_NAME = "root.live"
self.SESSION_TOML_FILE_NAME = "__session__.toml"
self.stage_url = stage_url
self.live_file_url = None
self.channel_url = None
self.toml_url = None
self.session_name = None
self.omni_url = omni.client.break_url(self.stage_url)
# construct the folder that would contain sessions - <.live> / < my_usd_file.live> / <session_name> / root.live
self.omni_session_folder_path = os.path.dirname(self.omni_url.path) + self.LIVE_SUBFOLDER + "/" + self.get_stage_file_name() + self.LIVE_SUBFOLDER_SUFFIX
self.session_folder_string = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, self.omni_session_folder_path)
def get_session_folder_path_for_stage(self):
return self.session_folder_string
def set_session_name(self, session_name):
self.session_name = session_name
def get_live_session_folder_path(self):
return self.omni_session_folder_path + "/" + self.session_name + self.LIVE_SUBFOLDER_SUFFIX
def get_stage_file_name(self):
# find the stage file's root name
usd_file_root = os.path.splitext(os.path.basename(self.omni_url.path))[0]
return usd_file_root
def get_live_session_url(self):
live_session_path = self.get_live_session_folder_path() + "/" + self.DEFAULT_LIVE_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_path)
return live_session_url
def get_live_session_toml_url(self):
live_session_toml_path = self.get_live_session_folder_path() + "/" + self.SESSION_TOML_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_toml_path)
return live_session_url
def get_message_channel_url(self):
live_session_channel_path = self.get_live_session_folder_path() + "/" + self.OMNIVERSE_CHANNEL_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_channel_path)
return live_session_url
g_live_session_channel_manager = None
def list_session_users():
global g_live_session_channel_manager
# users are cm.PeerUser types
if g_live_session_channel_manager is None:
return ["Live session not initialized"]
users: set(cm.PeerUser)
users = g_live_session_channel_manager.get_users()
txtlst = ["Listing session users: "]
if len(users) == 0:
txtlst.append("No other users in session")
for user in users:
txtlst.append(f" - {user.user_name}[{user.from_app}")
return txtlst
class SfcTabSessionInfo(BaseTab):
sfw: SfWindow
sfc: SfControls
def __init__(self, sfw: SfWindow):
super().__init__("Session")
self.sfw = sfw
self.sfc = sfw.sfc
# print("SfcTabOptions.build_fn {sfc}")
def GetInfoText(self):
txt = "Session Info 1\nSession Info 2\nSession Info 3\n"
txt += "Session Info 4\nSession Info 5\nSession Info 6\n"
txt += "Session Info 7\nSession Info 8\nSession Info 9\n"
return txt
def build_fn(self):
# print("SfcTabOptions.build_fn (trc)")
sfw = self.sfw
sfc = self.sfc # noqa : F841
with ui.VStack(style={"margin": sfw.marg}, height=250):
with ui.ScrollingFrame():
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
txtlst = list_session_users()
txt = "/n".join(txtlst)
ui.Label(txt, word_wrap=True)
sfw.optstartupframe = ui.CollapsableFrame("Startup", collapsed=sfw.docollapse_optremoteframe)
with sfw.optstartupframe:
with ui.VStack(style={"margin": sfw.marg}):
with ui.HStack():
ui.Label("Load USD File on Startup: ")
sfw.doloadusd_checkbox = ui.CheckBox(model=sfw.doloadusd_checkbox_model,
width=40, height=10, name="loadusd", visible=True)
with ui.HStack():
ui.Label("USD URL:")
sfw.doloadusd_checkbox = ui.StringField(model=sfw.doloadusd_url_model,
width=400, height=20, visible=True)
with ui.HStack():
ui.Label("Start USD Session on Startup: ")
sfw.doloadusd_session_checkbox = ui.CheckBox(model=sfw.doloadusd_session_checkbox_model,
width=40, height=10, name="loadusd", visible=True)
with ui.HStack():
ui.Label("Session Name:")
sfw.doloadusd_sessionname = ui.StringField(model=sfw.doloadusd_sessionname_model,
width=400, height=20, visible=True)
| 6,879 | Python | 45.802721 | 170 | 0.616223 |
MikeWise2718/sphereflake22/exts/wise.sphereflake22/wise/sphereflake22/sfgen/sfsession.py | # import omni.kit.commands as okc
# import omni.usd
import os
import omni.client
class LiveSessionInfo:
""" Live Session Info class
This class attempts to collect all of the logic around the live session file paths and URLs.
It should be first instantiated with the stage URL (omniverse://server/folder/stage.usd), then
get_session_folder_path_for_stage() can be used to list the available sessions.
Once a session is selected, set_session_name() will finish the initialization of all of the paths
and the other methods can be used.
In the folder that contains the USD to be live-edited, there exists this folder structure:
<.live> / < my_usd_file.live> / <session_name> / root.live
get_session_folder_path_for_stage: <stage_folder> / <.live> / < my_usd_file.live>
get_live_session_folder_path: <stage_folder> / <.live> / < my_usd_file.live> / <session_name>
get_live_session_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / root.live
get_live_session_toml_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.toml
get_message_channel_url: <stage_folder> / <.live> / < my_usd_file.live> / <session_name> / __session__.channel
"""
def __init__(self, stage_url: str):
self.OMNIVERSE_CHANNEL_FILE_NAME = "__session__.channel"
self.LIVE_SUBFOLDER = "/.live"
self.LIVE_SUBFOLDER_SUFFIX = ".live"
self.DEFAULT_LIVE_FILE_NAME = "root.live"
self.SESSION_TOML_FILE_NAME = "__session__.toml"
self.stage_url = stage_url
self.live_file_url = None
self.channel_url = None
self.toml_url = None
self.session_name = None
self.omni_url = omni.client.break_url(self.stage_url)
# construct the folder that would contain sessions - <.live> / < my_usd_file.live> / <session_name> / root.live
self.omni_session_folder_path = os.path.dirname(self.omni_url.path) + self.LIVE_SUBFOLDER + "/" + self.get_stage_file_name() + self.LIVE_SUBFOLDER_SUFFIX
self.session_folder_string = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, self.omni_session_folder_path)
def get_session_folder_path_for_stage(self):
return self.session_folder_string
def set_session_name(self, session_name):
self.session_name = session_name
def get_live_session_folder_path(self):
return self.omni_session_folder_path + "/" + self.session_name + self.LIVE_SUBFOLDER_SUFFIX
def get_stage_file_name(self):
# find the stage file's root name
usd_file_root = os.path.splitext(os.path.basename(self.omni_url.path))[0]
return usd_file_root
def get_live_session_url(self):
live_session_path = self.get_live_session_folder_path() + "/" + self.DEFAULT_LIVE_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_path)
return live_session_url
def get_live_session_toml_url(self):
live_session_toml_path = self.get_live_session_folder_path() + "/" + self.SESSION_TOML_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_toml_path)
return live_session_url
def get_message_channel_url(self):
live_session_channel_path = self.get_live_session_folder_path() + "/" + self.OMNIVERSE_CHANNEL_FILE_NAME
live_session_url = omni.client.make_url(self.omni_url.scheme, self.omni_url.user, self.omni_url.host, self.omni_url.port, live_session_channel_path)
return live_session_url
def fish_out_session_name(stage):
slayer = stage.GetSessionLayer()
slayersubs = slayer.GetLoadedLayers()
for sl in slayersubs:
if sl.identifier.endswith(".live"):
chunks = sl.identifier.split("/")
session_name = chunks[-2].split(".")[0]
return session_name
return None
| 4,097 | Python | 49.592592 | 170 | 0.662436 |
MikeWise2718/sfapp/repo.toml | ########################################################################################################################
# Repo tool base settings
########################################################################################################################
[repo]
# Use the Kit Template repo configuration as a base. Only override things specific to the repo.
import_configs = [
"${root}/_repo/deps/repo_kit_tools/kit-template/repo.toml",
"${root}/_repo/deps/repo_kit_tools/kit-template/repo-app.toml"
]
# Repository Name
name = "sfapp"
[repo_kit_link_app]
app_name = "code" # App name.
app_version = "" # App version. Empty means latest. Specify to lock version, e.g. "2022.2.0-rc.3"
########################################################################################################################
# Documentation building
########################################################################################################################
[repo_docs]
#name = "SfApp"
# kit-manual doc
[[repo_docs.kit.custom_project]]
name = "sfapp"
root = "${root}"
config_path = "${root}/docs/docs.toml"
[repo_docs.kit]
extensions = [
]
| 1,169 | TOML | 28.999999 | 120 | 0.39521 |
MikeWise2718/sfapp/README.md | # Omniverse Kit App Template
[Omniverse Kit App Template](https://github.com/NVIDIA-Omniverse/kit-app-template) - is the place to start learning about developing Omniverse Apps.
This project contains everything necessary to develop and package an Omniverse App.
## Links
* [Repository](https://github.com/NVIDIA-Omniverse/kit-app-template)
* [Full Documentation](https://docs.omniverse.nvidia.com/kit/docs/kit-app-template)
## What Is an App?
Ultimately, an Omniverse Kit app is a `.kit` file. It is a single file extension. You can think of it as the tip of a dependencies pyramid, a final extension that pulls in everything.
Extensive documentation detailing what extensions are and how they work can be found [here](https://docs.omniverse.nvidia.com/py/kit/docs/guide/extensions.html).
## Getting Started
### Install Omniverse and some Apps
1. Install *Omniverse Launcher*: [download](https://www.nvidia.com/en-us/omniverse/download)
2. Install and launch one of *Omniverse* apps in the Launcher. This repo requires the latest *Create* installed.
### Build
1. Clone [this repo](https://github.com/NVIDIA-Omniverse/kit-app-template) to your local machine.
2. Open a command prompt and navigate to the root of your cloned repo.
3. Run `build.bat` to bootstrap your dev environment and build an example app.
4. Run `_build\windows-x86_64\release\my_name.my_app.bat` (or other apps) to open an example kit application.
You should have now launched your simple kit-based application!
### Package
To package, run `package.bat`. The package will be created in the `_build/packages` folder.
To use the package, unzip and run `link_app.bat` inside the package once before running.
Packaging just zips everything in the `_build/[platform]/release` folder, using it as a root. Linked app (`baseapp`) and kit (`kit`) folders are skipped.
### Changing a Base App
When building 2 folder links are created:
* `_build/[platform]/release/baseapp` link to Omniverse App (e.g. Create)
* `_build/[platform]/release/kit` links to kit inside of the app above (same as `_build/[platform]/release/baseapp/kit`)
In `repo.toml`, the baseapp name and version are specified and can be changed:
```toml
[repo_kit_link_app]
app_name = "create" # App name.
app_version = "" # App version. Empty means latest. Specify to lock version, e.g. "2022.2.0-rc.3"
```
After editing `repo.toml`, run `build.bat` again to create new app links.
## Keep Learning: Launching Apps
If you look inside the `bat`/`sh` app script runner file it just launches kit and passes a kit file (`my_name.my_app.kit`).
Application kit files define app configuration. *Omniverse Kit* is the core application runtime for Omniverse Applications. Think of it as `python.exe`. It is a small runtime, that enables all the basics like settings, python, logging and searches for extensions. **Everything else is an extension.** You can run only this new extension without running any big *App* like *Create*:
There are 2 other app examples: `my_name.my_app.viewport.kit` and `my_name.my_app.editor.kit`. Try running them.
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 3,213 | Markdown | 47.696969 | 381 | 0.752879 |
MikeWise2718/sfapp/deps/repo-deps.packman.xml | <project toolsVersion="5.0">
<dependency name="repo_man" linkPath="../_repo/deps/repo_man">
<package name="repo_man" version="1.10.1"/>
</dependency>
<dependency name="repo_build" linkPath="../_repo/deps/repo_build">
<package name="repo_build" version="0.27.1"/>
</dependency>
<dependency name="repo_changelog" linkPath="../_repo/deps/repo_changelog">
<package name="repo_changelog" version="0.2.20"/>
</dependency>
<dependency name="repo_docs" linkPath="../_repo/deps/repo_docs">
<package name="repo_docs" version="0.9.17"/>
</dependency>
<dependency name="repo_kit_tools" linkPath="../_repo/deps/repo_kit_tools">
<package name="repo_kit_tools" version="0.8.13"/>
</dependency>
<dependency name="repo_source" linkPath="../_repo/deps/repo_source">
<package name="repo_source" version="0.3.0" />
</dependency>
<dependency name="repo_package" linkPath="../_repo/deps/repo_package">
<package name="repo_package" version="5.6.8" />
</dependency>
<dependency name="repo_docs" linkPath="../_repo/deps/repo_docs">
<package name="repo_docs" version="0.10.1" />
</dependency>
</project>
| 1,143 | XML | 41.370369 | 76 | 0.661417 |
MikeWise2718/sfapp/deps/ext-deps.packman.xml | <project toolsVersion="5.0">
<!-- Use this file to include any dependencies for your extension beyond those in `kit-sdk-deps.packman.xml`. -->
</project>
| 157 | XML | 30.599994 | 115 | 0.713376 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/my_name/my_app/setup/setup.py | import asyncio
from pathlib import Path
import carb.imgui as _imgui
import carb.settings
import carb.tokens
import omni.ext
import omni.kit.menu.utils
from omni.kit.menu.utils import MenuLayout
from omni.kit.quicklayout import QuickLayout
from omni.kit.window.title import get_main_window_title
async def _load_layout(layout_file: str):
"""this private methods just help loading layout, you can use it in the Layout Menu"""
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file)
# This extension is mostly loading the Layout updating menu
class SetupExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
# get the settings
self._settings = carb.settings.get_settings()
self._await_layout = asyncio.ensure_future(self._delayed_layout())
# setup the menu and their layout
self._setup_menu()
# setup the Application Title
window_title = get_main_window_title()
window_title.set_app_version(self._settings.get("/app/titleVersion"))
async def _delayed_layout(self):
# few frame delay to allow automatic Layout of window that want their own positions
for i in range(4):
await omni.kit.app.get_app().next_update_async()
settings = carb.settings.get_settings()
# setup the Layout for your app
layouts_path = carb.tokens.get_tokens_interface().resolve("${my_name.my_app.setup}/layouts")
layout_file = Path(layouts_path).joinpath(f"{settings.get('/app/layout/name')}.json")
asyncio.ensure_future(_load_layout(f"{layout_file}"))
# using imgui directly to adjust some color and Variable
imgui = _imgui.acquire_imgui()
# DockSplitterSize is the variable that drive the size of the Dock Split connection
imgui.push_style_var_float(_imgui.StyleVar.DockSplitterSize, 2)
def _setup_menu(self):
editor_menu = omni.kit.ui.get_editor_menu()
# you can have some file Menu
self._file_open = editor_menu.add_item("File/Open", self._open_file)
# some Menu Item
self._help_menu = editor_menu.add_item("Help/Show", self._show_help)
# from omni.kit.menu.utils import MenuLayout
# self._menu_layout = [
# MenuLayout.Menu("Window", [
# MenuLayout.Item("MyWindow"),
# ]),
# ]
# omni.kit.menu.utils.add_layout(self._menu_layout)
def _show_help(self, menu, toggled):
print("Help is Coming")
def _open_file(self, menu, toggled):
print("Open the File you want")
def on_shutdown(self):
pass
| 2,821 | Python | 34.721519 | 119 | 0.659341 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.setup/docs/README.md | # Application Setup Extension Template
This extension simply sets up the Application | 85 | Markdown | 27.666657 | 45 | 0.847059 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/my_name/my_app/window/extension.py | import asyncio
import omni.ext
import omni.kit.ui
import carb
from .window import MyWindow
async def _load_layout(layout_file: str, keep_windows_open=True):
try:
from omni.kit.quicklayout import QuickLayout
# few frames delay to avoid the conflict with the layout of omni.kit.mainwindow
for i in range(3):
await omni.kit.app.get_app().next_update_async()
QuickLayout.load_file(layout_file, keep_windows_open)
print(f"Loaded layout: {layout_file}")
except Exception as exc:
pass
QuickLayout.load_file(layout_file)
class WindowExtension(omni.ext.IExt):
MENU_PATH = "Window/MyWindow"
def on_startup(self, ext_id):
editor_menu = omni.kit.ui.get_editor_menu()
# Most application have an Window Menu, See MenuLayout to re-organize it
self._window = None
self._menu = editor_menu.add_item(WindowExtension.MENU_PATH, self._on_menu_click, toggle=True, value=True)
self.show_window(True)
layout_file = carb.tokens.get_tokens_interface().resolve("${my_name.my_app.setup}/layouts/viewport1.json")
asyncio.ensure_future(_load_layout(layout_file))
def _on_menu_click(self, menu, toggled):
self.show_window(toggled)
def show_window(self, toggled):
if toggled:
if self._window is None:
self._window = MyWindow()
self._window.set_visibility_changed_fn(self._visiblity_changed_fn)
else:
self._window.show()
else:
if self._window is not None:
self._window.hide()
def _visiblity_changed_fn(self, visible):
if self._menu:
omni.kit.ui.get_editor_menu().set_value(WindowExtension.MENU_PATH, visible)
self.show_window(visible)
def on_shutdown(self):
if self._window is not None:
self._window.destroy()
self._window = None
if self._menu is not None:
editor_menu = omni.kit.ui.get_editor_menu()
editor_menu.remove_item(self._menu)
self._menu = None
| 2,127 | Python | 30.761194 | 114 | 0.618242 |
MikeWise2718/sfapp/source/extensions/my_name.my_app.window/my_name/my_app/window/window.py | __all__ = ["MyWindow"]
import omni.ui as ui
class MyWindow(ui.Window):
"""Sfapp Window"""
title = "My Window"
def __init__(self, **kwargs):
super().__init__(MyWindow.title, **kwargs)
# here you build the content of the window
with self.frame:
with ui.VStack():
ui.Label("Generic Label 1", height=0, style={"font_size": 48, "alignment": ui.Alignment.CENTER})
ui.Spacer()
ui.Label(
"Generic Label 2",
height=0,
style={"font_size": 32, "alignment": ui.Alignment.CENTER},
)
ui.Spacer()
with ui.HStack(height=50, style={"font_size": 24}):
ui.Button("Add")
ui.Button("Reset")
def show(self):
self.visible = True
def hide(self):
self.visible = False
| 922 | Python | 23.945945 | 112 | 0.476139 |
MikeWise2718/sfapp/docs/apps.md | # Example Apps
## Simple App Window: `my_name.my_app.kit`

The simple application showcases how to create a very basic Kit-based application showing a simple window.
It leverages the kit compatibility mode for the UI that enables it to run on virtually any computer with a GPU.
It uses the window extension example that shows how you can create an extension that shows the window in your application.
## Editor App: `my_name.my_app.editor.kit`

The simple Editor application showcases how you can start leveraging more of the Omniverse Shared Extensions around USD editing to create an application that has the basic features of an app like Create.
It will require an RTX compatible GPU, Turing or above.
You can see how it uses the kit.QuickLayout to setup the example Window at the bottom next to the Content Browser, of course you can choose your own layout and add more functionality and Windows.
## Simple Viewport App: `my_name.my_app.viewport.kit`

This simple viewport application showcases how to create an application that leverages the RTX Renderer and the Kit Viewport to visualize USD files.
It will require an RTX compatible GPU, Turing or above.
The functionality is very limited to mostly viewing the data, and is just a starting point for something you might want to build from.
You can see how it uses the kit.QuickLayout to setup the example Window on the right of the Viewport but you can setup any layout that you need.
| 1,604 | Markdown | 44.857142 | 203 | 0.786783 |
MikeWise2718/sfapp/docs/names.md | # Choosing Names
In this repository we use the `my_name` and `my_app` token for our app and extensions naming, the purpose is to outline where you should use `your company/name id` and `name for your app`
## Brand (Company/Person) Name: `my_name`
For example, for extensions or applications created by the Omniverse team `my_name` is `omni` like `omni.kit.window.extensions` for an extension or `omni.create` for an application.
We recommend that you use a clear and unique name for that and use it for all your apps and extensions.
### A few rules to follow when selecting it
1. Don't use a generic name like `bob` or `cloud`
2. Don't use `omni` as this is reserved for NVIDIA Applications or Extensions
3. Be consistent. Select one and stick to it
## App Name: `my_app`
When building applications you might want to *namespace* the extension within the app name they belong to like `omni.code` for an application where we have then `omni.code.setup` etc.
For that name you have more freedom as it is already in your `my_name` namespace so it should not clash with someone else's "editor" or "viewer".
It would then be acceptable to have `my_name.editor` or `my_name.player` but you still want to think about giving your application some good identity.
## Shared Extensions
Aside from the extension you build specifically for your App there might be some that you want to make more generic and reuse across applications.
That is very possible and even recommended. That is how Omniverse Shared Extensions are built. We have them in namespaces like `omni.kit.widget.` or `omni.kit.window.`
Similarly, you can have `<my_name>.widget.` and use that namespace to have your great ComboBox or advanced List selection widget. Those names will be very useful when other developers or users want to start using your extensions, it will make it clear those come from you (`<my_name>`) and your can outline in the `extension.toml` repository field where they are coming from.
| 1,979 | Markdown | 60.874998 | 375 | 0.769075 |
MikeWise2718/sfapp/docs/docs.toml | # this config makes kit kernel pretend to be an extension for the purpose of building docs.
# format is exactly like extension.toml, but only what is required to build docs
[package]
version = "104.0"
keywords = ["omniverse", "kit", "manual", "developer", "start"]
[documentation]
title = "Omniverse Kit App Template"
[documentation.pages]
"Getting Started" = "docs/overview.md"
"Example Apps" = "docs/apps.md"
"Shared Extensions" = "docs/extensions.md"
"Choosing Names" = "docs/names.md"
| 491 | TOML | 31.799998 | 91 | 0.731161 |
MikeWise2718/sfapp/docs/extensions.md | # Shared Extensions
The repository contains a few extensions that are shared amongst the sample applications that we showcase.
## Setup Extension: `my_name.my_app.setup`
It is standard practice when building applications to have a setup extension that enables you to set up the layout of the relevant windows and configure the menu and various things that happen on startup.
Look at the documentation for **my_name.my_app.setup** to see more details. Its code is also deeply documented so you can review what each part is doing.
## Window Extension: `my_name.my_app.window`
This example extension creates a window for your application.
The Window content itself is just for demonstration purposes and doesn't do anything but it is used in the various applications to show how it can be added to a collection of other Extensions coming from Kit or Code.
Similar to the setup extension, check the window extension's included documentation and review the code for more details
| 981 | Markdown | 56.764703 | 216 | 0.800204 |
MikeWise2718/sfapp/docs/overview.md |
```{include} ../../../../README.md
```
| 40 | Markdown | 9.249998 | 34 | 0.375 |
MarqRazz/c3pzero/CONTRIBUTING.md | Any contribution that you make to this repository will
be under the 3-Clause BSD License, as dictated by that
[license](https://opensource.org/licenses/BSD-3-Clause).
| 167 | Markdown | 40.99999 | 56 | 0.790419 |
MarqRazz/c3pzero/README.md | # c3pzero mobile manipulator
[](https://github.com/MarqRazz/c3pzero/actions/workflows/format.yaml)
Description: This is a ROS 2 package for the C3pzero robot which consists of a Permobile C300 diff drive base and Kinova Gen3 manipulator. This Package support the physical hardware, Ignition Gazebo and Nvidia Isaac simulation.
<img src="doc/c3pzero.png" width="50%" >
<img src="doc/c300_isaac.png" width="60%" >
https://github.com/MarqRazz/c3pzero/assets/25058794/35301ba1-e443-44ff-b6ba-0fabae138205
## Documentation
- [Installation](doc/installation.md)
- [User Guide](doc/user.md)
- [Developers Guide](doc/developer.md)
- [c3pzero Simulation hand hardware Bringup Guide](c3pzero_bringup/README.md)
- [C300 Mobile Base Guide](c300/README.md)
| 846 | Markdown | 41.349998 | 227 | 0.77305 |
MarqRazz/c3pzero/docker-compose.yaml | # Docker Compose file for the C3pzero Robot
#
# Usage:
#
# To build the images:
# docker compose build cpu
# or
# docker compose build gpu
#
# To start up a specific service by name [cpu or gpu]:
# docker compose up <name>
#
# To open an interactive shell to a running container:
# (You can tab complete to get the container name)
# docker exec -it c3pzero bash
services:
cpu:
image: c3pzero:latest
container_name: c3pzero
build:
context: .
dockerfile: .docker/Dockerfile
# Interactive shell
stdin_open: true
tty: true
# Networking and IPC for ROS 2
network_mode: host
ipc: host
privileged: true
command: /bin/bash
device_cgroup_rules:
- "c 81:* rmw"
- "c 189:* rmw"
environment:
# Default the ROS_DOMAIN_ID to zero if not set on the host
- ROS_DOMAIN_ID=${ROS_DOMAIN_ID:-0}
# Allows graphical programs in the container
- DISPLAY=${DISPLAY}
- QT_X11_NO_MITSHM=1
volumes:
# Mount the colcon workspace containing the source code
- ../../:/root/c3pzero_ws/:rw
# Allow access to host hardware e.g. joystick & sensors
- /dev:/dev
# Allows graphical programs in the container
- /tmp/.X11-unix:/tmp/.X11-unix:rw
- ${XAUTHORITY:-$HOME/.Xauthority}:/root/.Xauthority
gpu:
extends: cpu
container_name: c3pzero
command: /bin/bash
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
environment:
QT_X11_NO_MITSHM: 1
NVIDIA_VISIBLE_DEVICES: all
NVIDIA_DRIVER_CAPABILITIES: all
| 1,669 | YAML | 25.09375 | 64 | 0.618933 |
MarqRazz/c3pzero/c300/README.md | # c300 Mobile Base
## To visualize this robot's URDF run:
``` bash
ros2 launch c300_description view_base_urdf.launch.py
```
## To start the `c300` mobile base in Gazebo run the following command:
``` bash
ros2 launch c300_bringup gazebo_c300.launch.py
```
## To teleoperate the robot with a Logitech F710 joystick run:
``` bash
ros2 launch c300_driver teleop.launch.py
```
> NOTE: in simulation the `cmd_vel` topic is on `/diff_drive_base_controller/cmd_vel_unstamped`
| 473 | Markdown | 25.333332 | 95 | 0.733615 |
MarqRazz/c3pzero/c300/c300_bringup/launch/gazebo_c300.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
ExecuteProcess,
IncludeLaunchDescription,
RegisterEventHandler,
)
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.conditions import IfCondition
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
declared_arguments = []
# Simulation specific arguments
declared_arguments.append(
DeclareLaunchArgument(
"sim_ignition",
default_value="true",
description="Use Ignition for simulation",
)
)
# General arguments
declared_arguments.append(
DeclareLaunchArgument(
"runtime_config_package",
default_value="c300_bringup",
description='Package with the controller\'s configuration in "config" folder. \
Usually the argument is not set, it enables use of a custom setup.',
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_package",
default_value="c300_description",
description="Description package with robot URDF/XACRO files. Usually the argument \
is not set, it enables use of a custom description.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_file",
default_value="c300_base.urdf",
description="URDF/XACRO description file with the robot.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"robot_name",
default_value="c300",
description="Robot name.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"diff_drive_controller",
default_value="diff_drive_base_controller",
description="Diff drive base controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="true", description="Launch RViz?"
)
)
declared_arguments.append(
DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Gazebo) clock if true",
)
)
# Initialize Arguments
sim_ignition = LaunchConfiguration("sim_ignition")
# General arguments
runtime_config_package = LaunchConfiguration("runtime_config_package")
description_package = LaunchConfiguration("description_package")
description_file = LaunchConfiguration("description_file")
robot_name = LaunchConfiguration("robot_name")
prefix = LaunchConfiguration("prefix")
diff_drive_controller = LaunchConfiguration("diff_drive_controller")
launch_rviz = LaunchConfiguration("launch_rviz")
use_sim_time = LaunchConfiguration("use_sim_time")
rviz_config_file = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "rviz", "bringup_config.rviz"]
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name="xacro")]),
" ",
PathJoinSubstitution(
[FindPackageShare(description_package), "urdf", description_file]
),
" ",
"sim_ignition:=",
sim_ignition,
" ",
]
)
robot_state_publisher_node = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="both",
parameters=[
{
"use_sim_time": use_sim_time,
"robot_description": robot_description_content,
}
],
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
arguments=["-d", rviz_config_file],
condition=IfCondition(launch_rviz),
)
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"joint_state_broadcaster",
"--controller-manager",
"/controller_manager",
],
)
# Delay rviz start after `joint_state_broadcaster`
delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[rviz_node],
)
)
diff_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[diff_drive_controller, "-c", "/controller_manager"],
)
ignition_spawn_entity = Node(
package="ros_gz_sim",
executable="create",
output="screen",
arguments=[
"-string",
robot_description_content,
"-name",
robot_name,
"-allow_renaming",
"true",
"-x",
"0.0",
"-y",
"0.0",
"-z",
"0.3",
"-R",
"0.0",
"-P",
"0.0",
"-Y",
"0.0",
],
condition=IfCondition(sim_ignition),
)
ignition_launch_description = IncludeLaunchDescription(
PythonLaunchDescriptionSource(
[FindPackageShare("ros_gz_sim"), "/launch/gz_sim.launch.py"]
),
# TODO (marqrazz): fix the hardcoded path to the gazebo world
# -v is the verbose level
# 0: No output, 1: Error, 2: Error and warning, 3: Error, warning, and info, 4: Error, warning, info, and debug.
# -s launches Gazebo headless
launch_arguments={
"gz_args": " -r -v 3 -s /root/c3pzero_ws/src/c3pzero/c300/c300_bringup/worlds/depot.sdf"
}.items(),
condition=IfCondition(sim_ignition),
)
# Bridge
gazebo_bridge = Node(
package="ros_gz_bridge",
executable="parameter_bridge",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"/scan@sensor_msgs/msg/LaserScan[ignition.msgs.LaserScan",
"/clock@rosgraph_msgs/msg/Clock[ignition.msgs.Clock",
],
output="screen",
)
nodes_to_start = [
robot_state_publisher_node,
joint_state_broadcaster_spawner,
delay_rviz_after_joint_state_broadcaster_spawner,
diff_drive_controller_spawner,
ignition_launch_description,
ignition_spawn_entity,
gazebo_bridge,
]
return LaunchDescription(declared_arguments + nodes_to_start)
| 6,925 | Python | 29.782222 | 121 | 0.591625 |
MarqRazz/c3pzero/c300/c300_bringup/launch/isaac_c300.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
ExecuteProcess,
IncludeLaunchDescription,
RegisterEventHandler,
)
from launch.event_handlers import OnProcessExit
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.conditions import IfCondition
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import Node
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
declared_arguments = []
# Simulation specific arguments
declared_arguments.append(
DeclareLaunchArgument(
"sim_isaac",
default_value="true",
description="Use Ignition for simulation",
)
)
# General arguments
declared_arguments.append(
DeclareLaunchArgument(
"runtime_config_package",
default_value="c300_bringup",
description='Package with the controller\'s configuration in "config" folder. \
Usually the argument is not set, it enables use of a custom setup.',
)
)
declared_arguments.append(
DeclareLaunchArgument(
"controllers_file",
default_value="c300_isaac_controllers.yaml",
description="YAML file with the controllers configuration.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_package",
default_value="c300_description",
description="Description package with robot URDF/XACRO files. Usually the argument \
is not set, it enables use of a custom description.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_file",
default_value="c300_base.urdf",
description="URDF/XACRO description file with the robot.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"robot_name",
default_value="c300",
description="Robot name.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"prefix",
default_value='""',
description="Prefix of the joint names, useful for \
multi-robot setup. If changed than also joint names in the controllers' configuration \
have to be updated.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"diff_drive_controller",
default_value="diff_drive_base_controller",
description="Diff drive base controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="true", description="Launch RViz?"
)
)
declared_arguments.append(
DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Isaac) clock if true",
)
)
# General arguments
runtime_config_package = LaunchConfiguration("runtime_config_package")
controllers_file = LaunchConfiguration("controllers_file")
description_package = LaunchConfiguration("description_package")
description_file = LaunchConfiguration("description_file")
robot_name = LaunchConfiguration("robot_name")
prefix = LaunchConfiguration("prefix")
diff_drive_controller = LaunchConfiguration("diff_drive_controller")
launch_rviz = LaunchConfiguration("launch_rviz")
sim_isaac = LaunchConfiguration("sim_isaac")
use_sim_time = LaunchConfiguration("use_sim_time")
robot_controllers = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "config", controllers_file]
)
rviz_config_file = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "rviz", "bringup_config.rviz"]
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name="xacro")]),
" ",
PathJoinSubstitution(
[FindPackageShare(description_package), "urdf", description_file]
),
" ",
"prefix:=",
prefix,
" ",
"sim_isaac:=",
sim_isaac,
" ",
]
)
robot_description = {"robot_description": robot_description_content}
control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[
{"use_sim_time": use_sim_time},
robot_description,
robot_controllers,
],
remappings=[
("/diff_drive_base_controller/cmd_vel_unstamped", "/cmd_vel"),
("/diff_drive_base_controller/odom", "/odom"),
],
output="both",
)
robot_state_publisher_node = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="both",
parameters=[
{
"use_sim_time": use_sim_time,
"robot_description": robot_description_content,
}
],
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
parameters=[{"use_sim_time": use_sim_time}],
arguments=["-d", rviz_config_file],
condition=IfCondition(launch_rviz),
)
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"joint_state_broadcaster",
"--controller-manager",
"/controller_manager",
],
)
# Delay rviz start after `joint_state_broadcaster`
delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[rviz_node],
)
)
diff_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[diff_drive_controller, "-c", "/controller_manager"],
)
nodes_to_start = [
control_node,
robot_state_publisher_node,
joint_state_broadcaster_spawner,
delay_rviz_after_joint_state_broadcaster_spawner,
diff_drive_controller_spawner,
]
return LaunchDescription(declared_arguments + nodes_to_start)
| 6,604 | Python | 30.452381 | 96 | 0.609479 |
MarqRazz/c3pzero/c300/c300_bringup/config/c300_gz_controllers.yaml | controller_manager:
ros__parameters:
update_rate: 500 # Hz (this should match the gazebo rate)
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
diff_drive_base_controller:
type: diff_drive_controller/DiffDriveController
diff_drive_base_controller:
ros__parameters:
left_wheel_names: ["drivewhl_l_joint"]
right_wheel_names: ["drivewhl_r_joint"]
wheels_per_side: 1
wheel_separation: 0.61 # outside distance between the wheels
wheel_radius: 0.1715
wheel_separation_multiplier: 1.0
left_wheel_radius_multiplier: 1.0
right_wheel_radius_multiplier: 1.0
publish_rate: 50.0
odom_frame_id: odom
base_frame_id: base_link
pose_covariance_diagonal : [0.001, 0.001, 0.0, 0.0, 0.0, 0.01]
twist_covariance_diagonal: [0.001, 0.0, 0.0, 0.0, 0.0, 0.01]
open_loop: false
position_feedback: true
enable_odom_tf: true
cmd_vel_timeout: 0.5
#publish_limited_velocity: true
use_stamped_vel: false
#velocity_rolling_window_size: 10
# Velocity and acceleration limits
# Whenever a min_* is unspecified, default to -max_*
linear.x.has_velocity_limits: true
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 0.5
linear.x.max_jerk: 0.0
linear.x.min_jerk: 0.0
angular.z.has_velocity_limits: true
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 2.0
angular.z.min_velocity: -2.0
angular.z.max_acceleration: 1.0
angular.z.min_acceleration: -1.0
angular.z.max_jerk: 0.0
angular.z.min_jerk: 0.0
| 1,735 | YAML | 28.423728 | 66 | 0.680115 |
MarqRazz/c3pzero/c300/c300_navigation/README.md | # c300_navigation
This package contains the Nav2 parameters to be used with the Permobile c300 mobile base.
To test out this navigation package first start the robot in Gazebo and then run the included navigation launch file.
https://github.com/MarqRazz/c3pzero/assets/25058794/35301ba1-e443-44ff-b6ba-0fabae138205
# Nav2 with Gazebo simulated robot
To start the `c300` mobile base in Gazebo run the following command:
``` bash
ros2 launch c300_bringup gazebo_c300.launch.py launch_rviz:=false
```
To start Nav2 with the included Depot map run:
``` bash
ros2 launch c300_navigation navigation.launch.py
```
# Nav2 with Isaac simulated robot
To start Isaac with the `c300` mobile base in an industrial warehouse run the following command on the host PC where Isaac is installed:
``` bash
cd <path_to_workspace>/c3pzero_ws/src/c3pzero/c300/c300_description/usd
./python.sh isaac_c300.py
```
In the Docker container start the `c300` controllers to command the base and report state:
``` bash
ros2 launch c300_bringup isaac_c300.launch.py launch_rviz:=false
```
In the Docker container start Nav2 with the included Isaac Warehouse map run:
``` bash
ros2 launch c300_navigation navigation.launch.py map:=isaac_warehouse.yaml
```
## Initialize the location of the robot
Currently the [nav2_parameters.yaml](https://github.com/MarqRazz/c3pzero/blob/main/c300/c300_navigation/params/nav2_params.yaml) is setup to automatically set the initial pose of the robot for simulation environments.
If running on hardware change `set_initial_pose: false` under the `amcl` parameters and use the Rviz tool to set the initial pose on startup.
You can also set the initial pose through cli with the following command:
```bash
ros2 topic pub -1 /initialpose geometry_msgs/PoseWithCovarianceStamped '{ header: {stamp: {sec: 0, nanosec: 0}, frame_id: "map"}, pose: { pose: {position: {x: 0.0, y: 0.0, z: 0.0}, orientation: {w: 1.0}}, } }'
```
## Running SLAM
To create a new map with SLAM Toolbox start the robot and then run:
``` bash
ros2 launch c300_navigation navigation.launch.py slam:=True
```
After you have created a new map you can save it with the following command:
```bash
ros2 run nav2_map_server map_saver_cli -f ~/c3pzero_ws/<name of the new map>
```
| 2,259 | Markdown | 36.666666 | 217 | 0.760956 |
MarqRazz/c3pzero/c300/c300_navigation/launch/navigation.launch.py | # -*- coding: utf-8 -*-
# Copyright (c) 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""This is all-in-one launch script intended for use by nav2 developers."""
import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
ExecuteProcess,
IncludeLaunchDescription,
)
from launch.conditions import IfCondition
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration, PythonExpression
from launch_ros.actions import Node
def generate_launch_description():
# Get the launch directory
bringup_dir = get_package_share_directory("nav2_bringup")
c300_nav_dir = get_package_share_directory("c300_navigation")
launch_dir = os.path.join(bringup_dir, "launch")
# Create the launch configuration variables
slam = LaunchConfiguration("slam")
namespace = LaunchConfiguration("namespace")
use_namespace = LaunchConfiguration("use_namespace")
map_yaml_file = LaunchConfiguration("map")
use_sim_time = LaunchConfiguration("use_sim_time")
params_file = LaunchConfiguration("params_file")
autostart = LaunchConfiguration("autostart")
use_composition = LaunchConfiguration("use_composition")
use_respawn = LaunchConfiguration("use_respawn")
# Launch configuration variables specific to simulation
rviz_config_file = LaunchConfiguration("rviz_config_file")
use_rviz = LaunchConfiguration("use_rviz")
# Declare the launch arguments
declare_namespace_cmd = DeclareLaunchArgument(
"namespace", default_value="", description="Top-level namespace"
)
declare_use_namespace_cmd = DeclareLaunchArgument(
"use_namespace",
default_value="False",
description="Whether to apply a namespace to the navigation stack",
)
declare_slam_cmd = DeclareLaunchArgument(
"slam", default_value="False", description="Whether run a SLAM"
)
declare_map_yaml_cmd = DeclareLaunchArgument(
"map",
default_value=os.path.join(c300_nav_dir, "map", "depot.yaml"),
description="Full path to map file to load",
)
declare_use_sim_time_cmd = DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Gazebo) clock if True",
)
declare_params_file_cmd = DeclareLaunchArgument(
"params_file",
default_value=os.path.join(c300_nav_dir, "params", "nav2_params_mppi.yaml"),
description="Full path to the ROS2 parameters file to use for all launched nodes",
)
declare_autostart_cmd = DeclareLaunchArgument(
"autostart",
default_value="True",
description="Automatically startup the nav2 stack",
)
declare_use_composition_cmd = DeclareLaunchArgument(
"use_composition",
default_value="True",
description="Whether to use composed bringup",
)
declare_use_respawn_cmd = DeclareLaunchArgument(
"use_respawn",
default_value="False",
description="Whether to respawn if a node crashes. Applied when composition is disabled.",
)
declare_rviz_config_file_cmd = DeclareLaunchArgument(
"rviz_config_file",
default_value=os.path.join(c300_nav_dir, "rviz", "navigation.rviz"),
description="Full path to the RVIZ config file to use",
)
declare_use_rviz_cmd = DeclareLaunchArgument(
"use_rviz", default_value="True", description="Whether to start RVIZ"
)
rviz_cmd = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, "rviz_launch.py")),
condition=IfCondition(use_rviz),
launch_arguments={
"namespace": namespace,
"use_namespace": use_namespace,
"rviz_config": rviz_config_file,
}.items(),
)
bringup_cmd = IncludeLaunchDescription(
PythonLaunchDescriptionSource(os.path.join(launch_dir, "bringup_launch.py")),
launch_arguments={
"namespace": namespace,
"use_namespace": use_namespace,
"slam": slam,
"map": map_yaml_file,
"use_sim_time": use_sim_time,
"params_file": params_file,
"autostart": autostart,
"use_composition": use_composition,
"use_respawn": use_respawn,
}.items(),
)
# Create the launch description and populate
ld = LaunchDescription()
# Declare the launch options
ld.add_action(declare_namespace_cmd)
ld.add_action(declare_use_namespace_cmd)
ld.add_action(declare_slam_cmd)
ld.add_action(declare_map_yaml_cmd)
ld.add_action(declare_use_sim_time_cmd)
ld.add_action(declare_params_file_cmd)
ld.add_action(declare_autostart_cmd)
ld.add_action(declare_use_composition_cmd)
ld.add_action(declare_rviz_config_file_cmd)
ld.add_action(declare_use_rviz_cmd)
ld.add_action(declare_use_respawn_cmd)
ld.add_action(rviz_cmd)
ld.add_action(bringup_cmd)
return ld
| 5,641 | Python | 33.82716 | 98 | 0.683744 |
MarqRazz/c3pzero/c300/c300_navigation/map/isaac_warehouse.yaml | image: isaac_warehouse.pgm
mode: trinary
resolution: 0.05
origin: [-12.3, -8.46, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25
| 134 | YAML | 15.874998 | 26 | 0.716418 |
MarqRazz/c3pzero/c300/c300_navigation/map/depot.yaml | image: depot.pgm
mode: trinary
resolution: 0.05
origin: [-15.2, -7.72, 0]
negate: 0
occupied_thresh: 0.65
free_thresh: 0.25
| 124 | YAML | 14.624998 | 25 | 0.701613 |
MarqRazz/c3pzero/c300/c300_driver/setup.py | # -*- coding: utf-8 -*-
import os
from glob import glob
from setuptools import setup
package_name = "c300_driver"
setup(
name=package_name,
version="0.0.1",
packages=[package_name],
data_files=[
("share/ament_index/resource_index/packages", ["resource/" + package_name]),
("share/" + package_name, ["package.xml"]),
(os.path.join("share", package_name, "launch"), glob("launch/*.launch.py")),
(os.path.join("share", package_name, "config"), glob("config/*.yaml")),
],
install_requires=["setuptools"],
zip_safe=True,
maintainer="marq",
maintainer_email="[email protected]",
description="Driver package to control the c300 mobile base",
license="MIT",
tests_require=["pytest"],
entry_points={
"console_scripts": [
"twist2roboclaw = c300_driver.twist2roboclaw:main",
],
},
)
| 892 | Python | 27.806451 | 84 | 0.608744 |
MarqRazz/c3pzero/c300/c300_driver/launch/teleop.launch.py | # -*- coding: utf-8 -*-
import os
from ament_index_python.packages import get_package_share_directory
import launch
import launch_ros.actions
def generate_launch_description():
joy_config = launch.substitutions.LaunchConfiguration("joy_config")
joy_dev = launch.substitutions.LaunchConfiguration("joy_dev")
config_filepath = launch.substitutions.LaunchConfiguration("config_filepath")
return launch.LaunchDescription(
[
launch.actions.DeclareLaunchArgument("joy_vel", default_value="/cmd_vel"),
launch.actions.DeclareLaunchArgument("joy_config", default_value="f710"),
launch.actions.DeclareLaunchArgument(
"joy_dev", default_value="/dev/input/js0"
),
launch.actions.DeclareLaunchArgument(
"config_filepath",
default_value=[
launch.substitutions.TextSubstitution(
text=os.path.join(
get_package_share_directory("c300_driver"), "config", ""
)
),
joy_config,
launch.substitutions.TextSubstitution(text=".config.yaml"),
],
),
launch_ros.actions.Node(
package="joy",
executable="joy_node",
name="joy_node",
parameters=[
{
"dev": joy_dev,
"deadzone": 0.3,
"autorepeat_rate": 20.0,
}
],
),
launch_ros.actions.Node(
package="teleop_twist_joy",
executable="teleop_node",
name="teleop_twist_joy_node",
parameters=[config_filepath],
remappings={
("/cmd_vel", launch.substitutions.LaunchConfiguration("joy_vel"))
},
),
]
)
| 2,001 | Python | 34.122806 | 86 | 0.498251 |
MarqRazz/c3pzero/c300/c300_driver/c300_driver/diff_drive_odom.py | # -*- coding: utf-8 -*-
from nav_msgs.msg import Odometry
from tf_transformations import quaternion_from_euler
from math import cos, sin
class DiffDriveOdom:
def __init__(self, clock, separation, radius):
self._clock = clock
self._frame_id = "odom"
self._child_frame_id = "base_id"
self._separation = separation
self._radius = radius
self._last_position = (0, 0)
self._last_time = self._clock.now()
self._robot_pose = (0, 0, 0)
self._first = True
def _get_diff(self, position):
if self._first:
self._first = False
self._last_position = position
diff = (
position[0] - self._last_position[0],
position[1] - self._last_position[1],
)
self._last_position = position
return diff
def step(self, position, velocity):
# position is radians tuple (l, r)
# velocity is m/s tuple (l, r)
now = self._clock.now()
time_step = now - self._last_time
wheel_l, wheel_r = self._get_diff(position)
delta_s = self._radius * (wheel_r + wheel_l) / 2.0
theta = self._radius * (wheel_r - wheel_l) / self._separation
self._robot_pose = (
self._robot_pose[0] + delta_s * cos(self._robot_pose[2] + (theta / 2.0)),
self._robot_pose[1] + delta_s * sin(self._robot_pose[2] + (theta / 2.0)),
self._robot_pose[2] + theta,
)
q = quaternion_from_euler(0.0, 0.0, self._robot_pose[2])
self._last_time = now
msg = Odometry()
msg.header.frame_id = self._frame_id
msg.header.stamp = now.to_msg()
msg.child_frame_id = self._child_frame_id
msg.pose.pose.position.x = self._robot_pose[0]
msg.pose.pose.position.y = self._robot_pose[1]
msg.pose.pose.position.z = 0.0
msg.pose.pose.orientation.x = q[0]
msg.pose.pose.orientation.y = q[1]
msg.pose.pose.orientation.z = q[2]
msg.pose.pose.orientation.w = q[3]
msg.twist.twist.linear.x = delta_s / (time_step.nanoseconds * 1e9)
msg.twist.twist.angular.z = theta / (time_step.nanoseconds * 1e9)
return msg
| 2,223 | Python | 34.870967 | 85 | 0.560504 |
MarqRazz/c3pzero/c300/c300_driver/c300_driver/roboclaw_3.py | # -*- coding: utf-8 -*-
import random
import serial
import struct
import time
class Roboclaw:
"Roboclaw Interface Class"
def __init__(self, comport, rate, timeout=0.01, retries=3):
self.comport = comport
self.rate = rate
self.timeout = timeout
self._trystimeout = retries
self._crc = 0
# Command Enums
class Cmd:
M1FORWARD = 0
M1BACKWARD = 1
SETMINMB = 2
SETMAXMB = 3
M2FORWARD = 4
M2BACKWARD = 5
M17BIT = 6
M27BIT = 7
MIXEDFORWARD = 8
MIXEDBACKWARD = 9
MIXEDRIGHT = 10
MIXEDLEFT = 11
MIXEDFB = 12
MIXEDLR = 13
GETM1ENC = 16
GETM2ENC = 17
GETM1SPEED = 18
GETM2SPEED = 19
RESETENC = 20
GETVERSION = 21
SETM1ENCCOUNT = 22
SETM2ENCCOUNT = 23
GETMBATT = 24
GETLBATT = 25
SETMINLB = 26
SETMAXLB = 27
SETM1PID = 28
SETM2PID = 29
GETM1ISPEED = 30
GETM2ISPEED = 31
M1DUTY = 32
M2DUTY = 33
MIXEDDUTY = 34
M1SPEED = 35
M2SPEED = 36
MIXEDSPEED = 37
M1SPEEDACCEL = 38
M2SPEEDACCEL = 39
MIXEDSPEEDACCEL = 40
M1SPEEDDIST = 41
M2SPEEDDIST = 42
MIXEDSPEEDDIST = 43
M1SPEEDACCELDIST = 44
M2SPEEDACCELDIST = 45
MIXEDSPEEDACCELDIST = 46
GETBUFFERS = 47
GETPWMS = 48
GETCURRENTS = 49
MIXEDSPEED2ACCEL = 50
MIXEDSPEED2ACCELDIST = 51
M1DUTYACCEL = 52
M2DUTYACCEL = 53
MIXEDDUTYACCEL = 54
READM1PID = 55
READM2PID = 56
SETMAINVOLTAGES = 57
SETLOGICVOLTAGES = 58
GETMINMAXMAINVOLTAGES = 59
GETMINMAXLOGICVOLTAGES = 60
SETM1POSPID = 61
SETM2POSPID = 62
READM1POSPID = 63
READM2POSPID = 64
M1SPEEDACCELDECCELPOS = 65
M2SPEEDACCELDECCELPOS = 66
MIXEDSPEEDACCELDECCELPOS = 67
SETM1DEFAULTACCEL = 68
SETM2DEFAULTACCEL = 69
SETPINFUNCTIONS = 74
GETPINFUNCTIONS = 75
SETDEADBAND = 76
GETDEADBAND = 77
RESTOREDEFAULTS = 80
GETTEMP = 82
GETTEMP2 = 83
GETERROR = 90
GETENCODERMODE = 91
SETM1ENCODERMODE = 92
SETM2ENCODERMODE = 93
WRITENVM = 94
READNVM = 95
SETCONFIG = 98
GETCONFIG = 99
SETM1MAXCURRENT = 133
SETM2MAXCURRENT = 134
GETM1MAXCURRENT = 135
GETM2MAXCURRENT = 136
SETPWMMODE = 148
GETPWMMODE = 149
READEEPROM = 252
WRITEEEPROM = 253
FLAGBOOTLOADER = 255
# Private Functions
def crc_clear(self):
self._crc = 0
return
def crc_update(self, data):
self._crc = self._crc ^ (data << 8)
for bit in range(0, 8):
if (self._crc & 0x8000) == 0x8000:
self._crc = (self._crc << 1) ^ 0x1021
else:
self._crc = self._crc << 1
return
def _sendcommand(self, address, command):
self.crc_clear()
self.crc_update(address)
# self._port.write(chr(address))
self._port.write(address.to_bytes(1, "big"))
self.crc_update(command)
# self._port.write(chr(command))
self._port.write(command.to_bytes(1, "big"))
return
def _readchecksumword(self):
data = self._port.read(2)
if len(data) == 2:
# crc = (ord(data[0])<<8) | ord(data[1])
crc = (data[0] << 8) | data[1]
return (1, crc)
return (0, 0)
def _readbyte(self):
data = self._port.read(1)
if len(data):
val = ord(data)
self.crc_update(val)
return (1, val)
return (0, 0)
def _readword(self):
val1 = self._readbyte()
if val1[0]:
val2 = self._readbyte()
if val2[0]:
return (1, val1[1] << 8 | val2[1])
return (0, 0)
def _readlong(self):
val1 = self._readbyte()
if val1[0]:
val2 = self._readbyte()
if val2[0]:
val3 = self._readbyte()
if val3[0]:
val4 = self._readbyte()
if val4[0]:
return (
1,
val1[1] << 24 | val2[1] << 16 | val3[1] << 8 | val4[1],
)
return (0, 0)
def _readslong(self):
val = self._readlong()
if val[0]:
if val[1] & 0x80000000:
return (val[0], val[1] - 0x100000000)
return (val[0], val[1])
return (0, 0)
def _writebyte(self, val):
self.crc_update(val & 0xFF)
# self._port.write(chr(val&0xFF))
self._port.write(val.to_bytes(1, "big"))
def _writesbyte(self, val):
self._writebyte(val)
def _writeword(self, val):
self._writebyte((val >> 8) & 0xFF)
self._writebyte(val & 0xFF)
def _writesword(self, val):
self._writeword(val)
def _writelong(self, val):
self._writebyte((val >> 24) & 0xFF)
self._writebyte((val >> 16) & 0xFF)
self._writebyte((val >> 8) & 0xFF)
self._writebyte(val & 0xFF)
def _writeslong(self, val):
self._writelong(val)
def _read1(self, address, cmd):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, cmd)
val1 = self._readbyte()
if val1[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def _read2(self, address, cmd):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, cmd)
val1 = self._readword()
if val1[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def _read4(self, address, cmd):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, cmd)
val1 = self._readlong()
if val1[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def _read4_1(self, address, cmd):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, cmd)
val1 = self._readslong()
if val1[0]:
val2 = self._readbyte()
if val2[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1], val2[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def _read_n(self, address, cmd, args):
tries = self._trystimeout
while 1:
self._port.flushInput()
tries -= 1
if tries == 0:
break
failed = False
self._sendcommand(address, cmd)
data = [
1,
]
for i in range(0, args):
val = self._readlong()
if val[0] == 0:
failed = True
break
data.append(val[1])
if failed:
continue
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF == crc[1] & 0xFFFF:
return data
return (0, 0, 0, 0, 0)
def _writechecksum(self):
self._writeword(self._crc & 0xFFFF)
val = self._readbyte()
if len(val) > 0:
if val[0]:
return True
return False
def _write0(self, address, cmd):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write1(self, address, cmd, val):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writebyte(val)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write11(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writebyte(val1)
self._writebyte(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write111(self, address, cmd, val1, val2, val3):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writebyte(val1)
self._writebyte(val2)
self._writebyte(val3)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write2(self, address, cmd, val):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeword(val)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS2(self, address, cmd, val):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writesword(val)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write22(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeword(val1)
self._writeword(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS22(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writesword(val1)
self._writeword(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS2S2(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writesword(val1)
self._writesword(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS24(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writesword(val1)
self._writelong(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS24S24(self, address, cmd, val1, val2, val3, val4):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writesword(val1)
self._writelong(val2)
self._writesword(val3)
self._writelong(val4)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4(self, address, cmd, val):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS4(self, address, cmd, val):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeslong(val)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write44(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S4(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writeslong(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS4S4(self, address, cmd, val1, val2):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeslong(val1)
self._writeslong(val2)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write441(self, address, cmd, val1, val2, val3):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
self._writebyte(val3)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS441(self, address, cmd, val1, val2, val3):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeslong(val1)
self._writelong(val2)
self._writebyte(val3)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S4S4(self, address, cmd, val1, val2, val3):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writeslong(val2)
self._writeslong(val3)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S441(self, address, cmd, val1, val2, val3, val4):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writeslong(val2)
self._writelong(val3)
self._writebyte(val4)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4444(self, address, cmd, val1, val2, val3, val4):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
self._writelong(val3)
self._writelong(val4)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S44S4(self, address, cmd, val1, val2, val3, val4):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writeslong(val2)
self._writelong(val3)
self._writeslong(val4)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write44441(self, address, cmd, val1, val2, val3, val4, val5):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
self._writelong(val3)
self._writelong(val4)
self._writebyte(val5)
if self._writechecksum():
return True
tries = tries - 1
return False
def _writeS44S441(self, address, cmd, val1, val2, val3, val4, val5):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writeslong(val1)
self._writelong(val2)
self._writeslong(val3)
self._writelong(val4)
self._writebyte(val5)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S44S441(self, address, cmd, val1, val2, val3, val4, val5, val6):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writeslong(val2)
self._writelong(val3)
self._writeslong(val4)
self._writelong(val5)
self._writebyte(val6)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4S444S441(self, address, cmd, val1, val2, val3, val4, val5, val6, val7):
tries = self._trystimeout
while tries:
self._sendcommand(self, address, cmd)
self._writelong(val1)
self._writeslong(val2)
self._writelong(val3)
self._writelong(val4)
self._writeslong(val5)
self._writelong(val6)
self._writebyte(val7)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write4444444(self, address, cmd, val1, val2, val3, val4, val5, val6, val7):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
self._writelong(val3)
self._writelong(val4)
self._writelong(val5)
self._writelong(val6)
self._writelong(val7)
if self._writechecksum():
return True
tries = tries - 1
return False
def _write444444441(
self, address, cmd, val1, val2, val3, val4, val5, val6, val7, val8, val9
):
tries = self._trystimeout
while tries:
self._sendcommand(address, cmd)
self._writelong(val1)
self._writelong(val2)
self._writelong(val3)
self._writelong(val4)
self._writelong(val5)
self._writelong(val6)
self._writelong(val7)
self._writelong(val8)
self._writebyte(val9)
if self._writechecksum():
return True
tries = tries - 1
return False
# User accessible functions
def SendRandomData(self, cnt):
for i in range(0, cnt):
byte = random.getrandbits(8)
# self._port.write(chr(byte))
self._port.write(byte.to_bytes(1, "big"))
return
def ForwardM1(self, address, val):
return self._write1(address, self.Cmd.M1FORWARD, val)
def BackwardM1(self, address, val):
return self._write1(address, self.Cmd.M1BACKWARD, val)
def SetMinVoltageMainBattery(self, address, val):
return self._write1(address, self.Cmd.SETMINMB, val)
def SetMaxVoltageMainBattery(self, address, val):
return self._write1(address, self.Cmd.SETMAXMB, val)
def ForwardM2(self, address, val):
return self._write1(address, self.Cmd.M2FORWARD, val)
def BackwardM2(self, address, val):
return self._write1(address, self.Cmd.M2BACKWARD, val)
def ForwardBackwardM1(self, address, val):
return self._write1(address, self.Cmd.M17BIT, val)
def ForwardBackwardM2(self, address, val):
return self._write1(address, self.Cmd.M27BIT, val)
def ForwardMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDFORWARD, val)
def BackwardMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDBACKWARD, val)
def TurnRightMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDRIGHT, val)
def TurnLeftMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDLEFT, val)
def ForwardBackwardMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDFB, val)
def LeftRightMixed(self, address, val):
return self._write1(address, self.Cmd.MIXEDLR, val)
def ReadEncM1(self, address):
return self._read4_1(address, self.Cmd.GETM1ENC)
def ReadEncM2(self, address):
return self._read4_1(address, self.Cmd.GETM2ENC)
def ReadSpeedM1(self, address):
return self._read4_1(address, self.Cmd.GETM1SPEED)
def ReadSpeedM2(self, address):
return self._read4_1(address, self.Cmd.GETM2SPEED)
def ResetEncoders(self, address):
return self._write0(address, self.Cmd.RESETENC)
def ReadVersion(self, address):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, self.Cmd.GETVERSION)
str = ""
passed = True
for i in range(0, 48):
data = self._port.read(1)
if len(data):
val = ord(data)
self.crc_update(val)
if val == 0:
break
# str+=data[0]
str += chr(data[0])
else:
passed = False
break
if passed:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF == crc[1] & 0xFFFF:
return (1, str)
else:
time.sleep(0.01)
tries -= 1
if tries == 0:
break
return (0, 0)
def SetEncM1(self, address, cnt):
return self._write4(address, self.Cmd.SETM1ENCCOUNT, cnt)
def SetEncM2(self, address, cnt):
return self._write4(address, self.Cmd.SETM2ENCCOUNT, cnt)
def ReadMainBatteryVoltage(self, address):
return self._read2(address, self.Cmd.GETMBATT)
def ReadLogicBatteryVoltage(
self,
address,
):
return self._read2(address, self.Cmd.GETLBATT)
def SetMinVoltageLogicBattery(self, address, val):
return self._write1(address, self.Cmd.SETMINLB, val)
def SetMaxVoltageLogicBattery(self, address, val):
return self._write1(address, self.Cmd.SETMAXLB, val)
def SetM1VelocityPID(self, address, p, i, d, qpps):
# return self._write4444(address,self.Cmd.SETM1PID,long(d*65536),long(p*65536),long(i*65536),qpps)
return self._write4444(
address, self.Cmd.SETM1PID, d * 65536, p * 65536, i * 65536, qpps
)
def SetM2VelocityPID(self, address, p, i, d, qpps):
# return self._write4444(address,self.Cmd.SETM2PID,long(d*65536),long(p*65536),long(i*65536),qpps)
return self._write4444(
address, self.Cmd.SETM2PID, d * 65536, p * 65536, i * 65536, qpps
)
def ReadISpeedM1(self, address):
return self._read4_1(address, self.Cmd.GETM1ISPEED)
def ReadISpeedM2(self, address):
return self._read4_1(address, self.Cmd.GETM2ISPEED)
def DutyM1(self, address, val):
return self._writeS2(address, self.Cmd.M1DUTY, val)
def DutyM2(self, address, val):
return self._writeS2(address, self.Cmd.M2DUTY, val)
def DutyM1M2(self, address, m1, m2):
return self._writeS2S2(address, self.Cmd.MIXEDDUTY, m1, m2)
def SpeedM1(self, address, val):
return self._writeS4(address, self.Cmd.M1SPEED, val)
def SpeedM2(self, address, val):
return self._writeS4(address, self.Cmd.M2SPEED, val)
def SpeedM1M2(self, address, m1, m2):
return self._writeS4S4(address, self.Cmd.MIXEDSPEED, m1, m2)
def SpeedAccelM1(self, address, accel, speed):
return self._write4S4(address, self.Cmd.M1SPEEDACCEL, accel, speed)
def SpeedAccelM2(self, address, accel, speed):
return self._write4S4(address, self.Cmd.M2SPEEDACCEL, accel, speed)
def SpeedAccelM1M2(self, address, accel, speed1, speed2):
return self._write4S4S4(
address, self.Cmd.MIXEDSPEEDACCEL, accel, speed1, speed2
)
def SpeedDistanceM1(self, address, speed, distance, buffer):
return self._writeS441(address, self.Cmd.M1SPEEDDIST, speed, distance, buffer)
def SpeedDistanceM2(self, address, speed, distance, buffer):
return self._writeS441(address, self.Cmd.M2SPEEDDIST, speed, distance, buffer)
def SpeedDistanceM1M2(self, address, speed1, distance1, speed2, distance2, buffer):
return self._writeS44S441(
address,
self.Cmd.MIXEDSPEEDDIST,
speed1,
distance1,
speed2,
distance2,
buffer,
)
def SpeedAccelDistanceM1(self, address, accel, speed, distance, buffer):
return self._write4S441(
address, self.Cmd.M1SPEEDACCELDIST, accel, speed, distance, buffer
)
def SpeedAccelDistanceM2(self, address, accel, speed, distance, buffer):
return self._write4S441(
address, self.Cmd.M2SPEEDACCELDIST, accel, speed, distance, buffer
)
def SpeedAccelDistanceM1M2(
self, address, accel, speed1, distance1, speed2, distance2, buffer
):
return self._write4S44S441(
address,
self.Cmd.MIXEDSPEEDACCELDIST,
accel,
speed1,
distance1,
speed2,
distance2,
buffer,
)
def ReadBuffers(self, address):
val = self._read2(address, self.Cmd.GETBUFFERS)
if val[0]:
return (1, val[1] >> 8, val[1] & 0xFF)
return (0, 0, 0)
def ReadPWMs(self, address):
val = self._read4(address, self.Cmd.GETPWMS)
if val[0]:
pwm1 = val[1] >> 16
pwm2 = val[1] & 0xFFFF
if pwm1 & 0x8000:
pwm1 -= 0x10000
if pwm2 & 0x8000:
pwm2 -= 0x10000
return (1, pwm1, pwm2)
return (0, 0, 0)
def ReadCurrents(self, address):
val = self._read4(address, self.Cmd.GETCURRENTS)
if val[0]:
cur1 = val[1] >> 16
cur2 = val[1] & 0xFFFF
if cur1 & 0x8000:
cur1 -= 0x10000
if cur2 & 0x8000:
cur2 -= 0x10000
return (1, cur1, cur2)
return (0, 0, 0)
def SpeedAccelM1M2_2(self, address, accel1, speed1, accel2, speed2):
return self._write4S44S4(
address, self.Cmd.MIXEDSPEED2ACCEL, accel, speed1, accel2, speed2
)
def SpeedAccelDistanceM1M2_2(
self, address, accel1, speed1, distance1, accel2, speed2, distance2, buffer
):
return self._write4S444S441(
address,
self.Cmd.MIXEDSPEED2ACCELDIST,
accel1,
speed1,
distance1,
accel2,
speed2,
distance2,
buffer,
)
def DutyAccelM1(self, address, accel, duty):
return self._writeS24(address, self.Cmd.M1DUTYACCEL, duty, accel)
def DutyAccelM2(self, address, accel, duty):
return self._writeS24(address, self.Cmd.M2DUTYACCEL, duty, accel)
def DutyAccelM1M2(self, address, accel1, duty1, accel2, duty2):
return self._writeS24S24(
address, self.Cmd.MIXEDDUTYACCEL, duty1, accel1, duty2, accel2
)
def ReadM1VelocityPID(self, address):
data = self._read_n(address, self.Cmd.READM1PID, 4)
if data[0]:
data[1] /= 65536.0
data[2] /= 65536.0
data[3] /= 65536.0
return data
return (0, 0, 0, 0, 0)
def ReadM2VelocityPID(self, address):
data = self._read_n(address, self.Cmd.READM2PID, 4)
if data[0]:
data[1] /= 65536.0
data[2] /= 65536.0
data[3] /= 65536.0
return data
return (0, 0, 0, 0, 0)
def SetMainVoltages(self, address, min, max):
return self._write22(address, self.Cmd.SETMAINVOLTAGES, min, max)
def SetLogicVoltages(self, address, min, max):
return self._write22(address, self.Cmd.SETLOGICVOLTAGES, min, max)
def ReadMinMaxMainVoltages(self, address):
val = self._read4(address, self.Cmd.GETMINMAXMAINVOLTAGES)
if val[0]:
min = val[1] >> 16
max = val[1] & 0xFFFF
return (1, min, max)
return (0, 0, 0)
def ReadMinMaxLogicVoltages(self, address):
val = self._read4(address, self.Cmd.GETMINMAXLOGICVOLTAGES)
if val[0]:
min = val[1] >> 16
max = val[1] & 0xFFFF
return (1, min, max)
return (0, 0, 0)
def SetM1PositionPID(self, address, kp, ki, kd, kimax, deadzone, min, max):
# return self._write4444444(address,self.Cmd.SETM1POSPID,long(kd*1024),long(kp*1024),long(ki*1024),kimax,deadzone,min,max)
return self._write4444444(
address,
self.Cmd.SETM1POSPID,
kd * 1024,
kp * 1024,
ki * 1024,
kimax,
deadzone,
min,
max,
)
def SetM2PositionPID(self, address, kp, ki, kd, kimax, deadzone, min, max):
# return self._write4444444(address,self.Cmd.SETM2POSPID,long(kd*1024),long(kp*1024),long(ki*1024),kimax,deadzone,min,max)
return self._write4444444(
address,
self.Cmd.SETM2POSPID,
kd * 1024,
kp * 1024,
ki * 1024,
kimax,
deadzone,
min,
max,
)
def ReadM1PositionPID(self, address):
data = self._read_n(address, self.Cmd.READM1POSPID, 7)
if data[0]:
data[1] /= 1024.0
data[2] /= 1024.0
data[3] /= 1024.0
return data
return (0, 0, 0, 0, 0, 0, 0, 0)
def ReadM2PositionPID(self, address):
data = self._read_n(address, self.Cmd.READM2POSPID, 7)
if data[0]:
data[1] /= 1024.0
data[2] /= 1024.0
data[3] /= 1024.0
return data
return (0, 0, 0, 0, 0, 0, 0, 0)
def SpeedAccelDeccelPositionM1(
self, address, accel, speed, deccel, position, buffer
):
return self._write44441(
address,
self.Cmd.M1SPEEDACCELDECCELPOS,
accel,
speed,
deccel,
position,
buffer,
)
def SpeedAccelDeccelPositionM2(
self, address, accel, speed, deccel, position, buffer
):
return self._write44441(
address,
self.Cmd.M2SPEEDACCELDECCELPOS,
accel,
speed,
deccel,
position,
buffer,
)
def SpeedAccelDeccelPositionM1M2(
self,
address,
accel1,
speed1,
deccel1,
position1,
accel2,
speed2,
deccel2,
position2,
buffer,
):
return self._write444444441(
address,
self.Cmd.MIXEDSPEEDACCELDECCELPOS,
accel1,
speed1,
deccel1,
position1,
accel2,
speed2,
deccel2,
position2,
buffer,
)
def SetM1DefaultAccel(self, address, accel):
return self._write4(address, self.Cmd.SETM1DEFAULTACCEL, accel)
def SetM2DefaultAccel(self, address, accel):
return self._write4(address, self.Cmd.SETM2DEFAULTACCEL, accel)
def SetPinFunctions(self, address, S3mode, S4mode, S5mode):
return self._write111(address, self.Cmd.SETPINFUNCTIONS, S3mode, S4mode, S5mode)
def ReadPinFunctions(self, address):
tries = self._trystimeout
while 1:
self._sendcommand(address, self.Cmd.GETPINFUNCTIONS)
val1 = self._readbyte()
if val1[0]:
val2 = self._readbyte()
if val1[0]:
val3 = self._readbyte()
if val1[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1], val2[1], val3[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def SetDeadBand(self, address, min, max):
return self._write11(address, self.Cmd.SETDEADBAND, min, max)
def GetDeadBand(self, address):
val = self._read2(address, self.Cmd.GETDEADBAND)
if val[0]:
return (1, val[1] >> 8, val[1] & 0xFF)
return (0, 0, 0)
# Warning(TTL Serial): Baudrate will change if not already set to 38400. Communications will be lost
def RestoreDefaults(self, address):
return self._write0(address, self.Cmd.RESTOREDEFAULTS)
def ReadTemp(self, address):
return self._read2(address, self.Cmd.GETTEMP)
def ReadTemp2(self, address):
return self._read2(address, self.Cmd.GETTEMP2)
def ReadError(self, address):
return self._read4(address, self.Cmd.GETERROR)
def ReadEncoderModes(self, address):
val = self._read2(address, self.Cmd.GETENCODERMODE)
if val[0]:
return (1, val[1] >> 8, val[1] & 0xFF)
return (0, 0, 0)
def SetM1EncoderMode(self, address, mode):
return self._write1(address, self.Cmd.SETM1ENCODERMODE, mode)
def SetM2EncoderMode(self, address, mode):
return self._write1(address, self.Cmd.SETM2ENCODERMODE, mode)
# saves active settings to NVM
def WriteNVM(self, address):
return self._write4(address, self.Cmd.WRITENVM, 0xE22EAB7A)
# restores settings from NVM
# Warning(TTL Serial): If baudrate changes or the control mode changes communications will be lost
def ReadNVM(self, address):
return self._write0(address, self.Cmd.READNVM)
# Warning(TTL Serial): If control mode is changed from packet serial mode when setting config communications will be lost!
# Warning(TTL Serial): If baudrate of packet serial mode is changed communications will be lost!
def SetConfig(self, address, config):
return self._write2(address, self.Cmd.SETCONFIG, config)
def GetConfig(self, address):
return self._read2(address, self.Cmd.GETCONFIG)
def SetM1MaxCurrent(self, address, max):
return self._write44(address, self.Cmd.SETM1MAXCURRENT, max, 0)
def SetM2MaxCurrent(self, address, max):
return self._write44(address, self.Cmd.SETM2MAXCURRENT, max, 0)
def ReadM1MaxCurrent(self, address):
data = self._read_n(address, self.Cmd.GETM1MAXCURRENT, 2)
if data[0]:
return (1, data[1])
return (0, 0)
def ReadM2MaxCurrent(self, address):
data = self._read_n(address, self.Cmd.GETM2MAXCURRENT, 2)
if data[0]:
return (1, data[1])
return (0, 0)
def SetPWMMode(self, address, mode):
return self._write1(address, self.Cmd.SETPWMMODE, mode)
def ReadPWMMode(self, address):
return self._read1(address, self.Cmd.GETPWMMODE)
def ReadEeprom(self, address, ee_address):
tries = self._trystimeout
while 1:
self._port.flushInput()
self._sendcommand(address, self.Cmd.READEEPROM)
self.crc_update(ee_address)
self._port.write(chr(ee_address))
val1 = self._readword()
if val1[0]:
crc = self._readchecksumword()
if crc[0]:
if self._crc & 0xFFFF != crc[1] & 0xFFFF:
return (0, 0)
return (1, val1[1])
tries -= 1
if tries == 0:
break
return (0, 0)
def WriteEeprom(self, address, ee_address, ee_word):
retval = self._write111(
address, self.Cmd.WRITEEEPROM, ee_address, ee_word >> 8, ee_word & 0xFF
)
if retval == True:
tries = self._trystimeout
while 1:
self._port.flushInput()
val1 = self._readbyte()
if val1[0]:
if val1[1] == 0xAA:
return True
tries -= 1
if tries == 0:
break
return False
def Open(self):
try:
self._port = serial.Serial(
port=self.comport,
baudrate=self.rate,
timeout=1,
interCharTimeout=self.timeout,
)
except:
return 0
return 1
| 37,787 | Python | 30.229752 | 132 | 0.526689 |
MarqRazz/c3pzero/c300/c300_driver/c300_driver/twist2roboclaw.py | # -*- coding: utf-8 -*-
# Copyright 2016 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import rclpy
from rclpy.node import Node
from . import roboclaw_3
from . import diff_drive_odom
from geometry_msgs.msg import Twist
import math
from pprint import pprint
class RoboclawTwistSubscriber(Node):
def __init__(self):
super().__init__("roboclaw_twist_subscriber")
cmd_vel_topic = "cmd_vel"
self.wheel_radius = 0.1715 # meters
self.wheel_circumference = 2 * math.pi * self.wheel_radius # meters
self.ppr = 11600 # pulses per wheel revolution
self.wheel_track = 0.54 # y distance between left and righ wheel
self.subscription = self.create_subscription(
Twist, cmd_vel_topic, self.twist_listener_callback, 10
)
self.subscription # prevent unused variable warning
self.rc = roboclaw_3.Roboclaw("/dev/ttyACM0", 115200)
if not self.rc.Open():
self.get_logger().error("failed to open port")
self.rc_address = 0x80
version = self.rc.ReadVersion(self.rc_address)
if version[0] == False:
self.get_logger().error("Retrieving the Roboclaw version failed")
else:
self.get_logger().info("Roboclaw version: %s" % repr(version[1]))
self.rc.ResetEncoders(self.rc_address)
self.diff_drive_odom = diff_drive_odom.DiffDriveOdom(
self.get_clock(), self.wheel_track, self.wheel_radius
)
self.create_timer(0.02, self.odom_callback)
self.get_logger().info(
"Init complete, listening for twist commands on topic: %s" % cmd_vel_topic
)
def twist_listener_callback(self, msg):
# self.get_logger().info('X_vel: %f, Z_rot: %f' % (0.4*msg.linear.x, msg.angular.z))
right_wheel = (
0.2 * msg.linear.x + (0.3 * msg.angular.z * self.wheel_track) / 2
) # meters / sec
left_wheel = 0.2 * msg.linear.x - (0.3 * msg.angular.z * self.wheel_track) / 2
wheel_cmds = self.mps_to_pps((right_wheel, left_wheel))
self.rc.SpeedM1(self.rc_address, wheel_cmds[0])
self.rc.SpeedM2(self.rc_address, wheel_cmds[1])
def odom_callback(self):
"""
the roboclaw returns the encoder position and velocity in a tuple
the first value is if the read was successful
the second value is the result (position pulses or rate)
the third value is ???
"""
right_wheel_enc = self.rc.ReadEncM1(self.rc_address)
left_wheel_enc = self.rc.ReadEncM2(self.rc_address)
# if reading the wheel velocities was unsuccessful return
if right_wheel_enc[0] == 0 | right_wheel_enc[0] == 0:
self.get_logger().error("Failed retrieving the Roboclaw wheel positions")
return
right_wheel_pps = self.rc.ReadSpeedM1(self.rc_address) # pulses per second.
left_wheel_pps = self.rc.ReadSpeedM2(self.rc_address)
# if reading the wheel velocities was unsuccessful return
if right_wheel_pps[0] == 0 | left_wheel_pps[0] == 0:
self.get_logger().error("Failed retrieving the Roboclaw wheel velocities")
return
# convert the wheel positions to radians
wheel_pos = self.enc_to_rad((right_wheel_enc[1], left_wheel_enc[1]))
# convert the wheel speeds to meters / sec
wheel_speed = self.pps_to_mps((right_wheel_pps[1], left_wheel_pps[1]))
odom_msg = self.diff_drive_odom.step(wheel_pos, wheel_speed)
# pprint(odom_msg.pose.pose.position)
self.get_logger().info(
"Pose: x=%f, y=%f theta=%f"
% (
odom_msg.pose.pose.position.x,
odom_msg.pose.pose.position.y,
odom_msg.pose.pose.orientation.z,
)
)
def mps_to_pps(self, wheel_speed):
right_wheel_pluses = int(wheel_speed[0] / self.wheel_circumference * self.ppr)
left_wheel_pluses = int(wheel_speed[1] / self.wheel_circumference * self.ppr)
return (right_wheel_pluses, left_wheel_pluses)
def enc_to_rad(self, wheel_pulses):
right_wheel_pos = wheel_pulses[0] / self.ppr * 2 * math.pi
left_wheel_pos = wheel_pulses[1] / self.ppr * 2 * math.pi
# self.get_logger().info('right=%f, left=%f' % (right_wheel_pos, left_wheel_pos))
return (right_wheel_pos, left_wheel_pos)
def pps_to_mps(self, wheel_pulses_per_sec):
right_wheel_speed = (
wheel_pulses_per_sec[0] / self.ppr * self.wheel_circumference
)
left_wheel_speed = wheel_pulses_per_sec[1] / self.ppr * self.wheel_circumference
return (right_wheel_speed, left_wheel_speed)
def main(args=None):
rclpy.init(args=args)
minimal_subscriber = RoboclawTwistSubscriber()
rclpy.spin(minimal_subscriber)
# Destroy the node explicitly
# (optional - otherwise it will be done automatically
# when the garbage collector destroys the node object)
minimal_subscriber.destroy_node()
rclpy.shutdown()
if __name__ == "__main__":
main()
| 5,658 | Python | 35.986928 | 92 | 0.631142 |
MarqRazz/c3pzero/c300/c300_driver/config/f710.config.yaml | # Logitech F710
teleop_twist_joy_node:
ros__parameters:
axis_linear: # Forward/Back
x: 1
scale_linear:
x: 1.0
scale_linear_turbo:
x: 2.0
axis_angular: # Twist
yaw: 3
scale_angular:
yaw: 0.8
scale_angular_turbo:
yaw: 2.0
enable_button: 5 # Trigger
enable_turbo_button: 4 # Button 2 aka thumb button
| 374 | YAML | 17.749999 | 55 | 0.580214 |
MarqRazz/c3pzero/c300/c300_description/launch/view_base_urdf.launch.py | # -*- coding: utf-8 -*-
# Copyright 2021 PickNik Inc.
# All rights reserved.
#
# Unauthorized copying of this code base via any medium is strictly prohibited.
# Proprietary and confidential.
import launch
from launch.substitutions import Command, LaunchConfiguration
import launch_ros
import os
def generate_launch_description():
pkg_share = launch_ros.substitutions.FindPackageShare(
package="c300_description"
).find("c300_description")
default_model_path = os.path.join(pkg_share, "urdf/c300_base.urdf")
default_rviz_config_path = os.path.join(pkg_share, "rviz/view_urdf.rviz")
robot_state_publisher_node = launch_ros.actions.Node(
package="robot_state_publisher",
executable="robot_state_publisher",
parameters=[
{"robot_description": Command(["xacro ", LaunchConfiguration("model")])}
],
)
joint_state_publisher_node = launch_ros.actions.Node(
package="joint_state_publisher_gui",
executable="joint_state_publisher_gui",
)
rviz_node = launch_ros.actions.Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="screen",
arguments=["-d", LaunchConfiguration("rvizconfig")],
)
return launch.LaunchDescription(
[
launch.actions.DeclareLaunchArgument(
name="model",
default_value=default_model_path,
description="Absolute path to robot urdf file",
),
launch.actions.DeclareLaunchArgument(
name="rvizconfig",
default_value=default_rviz_config_path,
description="Absolute path to rviz config file",
),
robot_state_publisher_node,
joint_state_publisher_node,
rviz_node,
]
)
| 1,837 | Python | 31.245613 | 84 | 0.621666 |
MarqRazz/c3pzero/c300/c300_description/usd/isaac_c300.py | # -*- coding: utf-8 -*-
import argparse
import os
import sys
import carb
import numpy as np
from omni.isaac.kit import SimulationApp
C300_STAGE_PATH = "/c300"
BACKGROUND_STAGE_PATH = "/background"
BACKGROUND_USD_PATH = (
"/Isaac/Environments/Simple_Warehouse/warehouse_multiple_shelves.usd"
)
# Initialize the parser
parser = argparse.ArgumentParser(
description="Process the path to the robot's folder containing its UDS file"
)
# Add the arguments
parser.add_argument(
"Path", metavar="path", type=str, help="the path to the robot's folder"
)
# Parse the arguments
args = parser.parse_args()
# Check if the path argument was provided
if args.Path:
GEN3_USD_PATH = args.Path + "/c300.usd"
else:
print(
"[ERROR] This script requires an argument with the absolute path to the robot's folder containing it's UDS file"
)
sys.exit()
CONFIG = {"renderer": "RayTracedLighting", "headless": False}
# Example ROS2 bridge sample demonstrating the manual loading of stages
# and creation of ROS components
simulation_app = SimulationApp(CONFIG)
import omni.graph.core as og # noqa E402
from omni.isaac.core import SimulationContext # noqa E402
from omni.isaac.core.utils import ( # noqa E402
extensions,
nucleus,
prims,
rotations,
stage,
viewports,
)
from omni.isaac.core_nodes.scripts.utils import set_target_prims # noqa E402
from pxr import Gf # noqa E402
# enable ROS2 bridge extension
extensions.enable_extension("omni.isaac.ros2_bridge")
simulation_context = SimulationContext(stage_units_in_meters=1.0)
# Locate Isaac Sim assets folder to load environment and robot stages
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
# Preparing stage
viewports.set_camera_view(eye=np.array([3, 0.5, 0.8]), target=np.array([0, 0, 0.5]))
# Loading the simple_room environment
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
# Loading the gen3 robot USD
prims.create_prim(
C300_STAGE_PATH,
"Xform",
position=np.array([1, 0, 0.17]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)),
usd_path=GEN3_USD_PATH,
)
simulation_app.update()
# Creating a action graph with ROS component nodes
try:
og.Controller.edit(
{"graph_path": "/ActionGraph", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
(
"SubscribeJointState",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ArticulationController",
"omni.isaac.core_nodes.IsaacArticulationController",
),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
("IsaacReadLidarBeams", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
("PublishLidarScan", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
# Nodes to subtract some time of the lidar message so it's timestamps match the tf tree in ROS
("ConstantFloat", "omni.graph.nodes.ConstantFloat"),
("Subtract", "omni.graph.nodes.Subtract"),
],
og.Controller.Keys.CONNECT: [
("OnImpulseEvent.outputs:execOut", "PublishJointState.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "SubscribeJointState.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "PublishClock.inputs:execIn"),
(
"OnImpulseEvent.outputs:execOut",
"ArticulationController.inputs:execIn",
),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "SubscribeJointState.inputs:context"),
("Context.outputs:context", "PublishClock.inputs:context"),
(
"ReadSimTime.outputs:simulationTime",
"PublishJointState.inputs:timeStamp",
),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
(
"SubscribeJointState.outputs:jointNames",
"ArticulationController.inputs:jointNames",
),
(
"SubscribeJointState.outputs:positionCommand",
"ArticulationController.inputs:positionCommand",
),
(
"SubscribeJointState.outputs:velocityCommand",
"ArticulationController.inputs:velocityCommand",
),
(
"SubscribeJointState.outputs:effortCommand",
"ArticulationController.inputs:effortCommand",
),
# Hack time offset for lidar messages
("ReadSimTime.outputs:simulationTime", "Subtract.inputs:a"),
("ConstantFloat.inputs:value", "Subtract.inputs:b"),
# Lidar nodes
(
"OnImpulseEvent.outputs:execOut",
"IsaacReadLidarBeams.inputs:execIn",
),
(
"IsaacReadLidarBeams.outputs:execOut",
"PublishLidarScan.inputs:execIn",
),
(
"IsaacReadLidarBeams.outputs:azimuthRange",
"PublishLidarScan.inputs:azimuthRange",
),
(
"IsaacReadLidarBeams.outputs:depthRange",
"PublishLidarScan.inputs:depthRange",
),
(
"IsaacReadLidarBeams.outputs:horizontalFov",
"PublishLidarScan.inputs:horizontalFov",
),
(
"IsaacReadLidarBeams.outputs:horizontalResolution",
"PublishLidarScan.inputs:horizontalResolution",
),
(
"IsaacReadLidarBeams.outputs:intensitiesData",
"PublishLidarScan.inputs:intensitiesData",
),
(
"IsaacReadLidarBeams.outputs:linearDepthData",
"PublishLidarScan.inputs:linearDepthData",
),
(
"IsaacReadLidarBeams.outputs:numCols",
"PublishLidarScan.inputs:numCols",
),
(
"IsaacReadLidarBeams.outputs:numRows",
"PublishLidarScan.inputs:numRows",
),
(
"IsaacReadLidarBeams.outputs:rotationRate",
"PublishLidarScan.inputs:rotationRate",
),
(
"Subtract.outputs:difference",
"PublishLidarScan.inputs:timeStamp",
),
("Context.outputs:context", "PublishLidarScan.inputs:context"),
],
og.Controller.Keys.SET_VALUES: [
("Context.inputs:domain_id", int(os.environ["ROS_DOMAIN_ID"])),
# Setting the /c300 target prim to Articulation Controller node
("ArticulationController.inputs:usePath", True),
("ArticulationController.inputs:robotPath", C300_STAGE_PATH),
("PublishJointState.inputs:topicName", "isaac_joint_states"),
("SubscribeJointState.inputs:topicName", "isaac_joint_commands"),
(
"PublishLidarScan.inputs:frameId",
"base_laser",
), # c300's laser frame_id
("PublishLidarScan.inputs:topicName", "scan"),
# Hack time offset for lidar messages
("ConstantFloat.inputs:value", 0.1),
],
},
)
except Exception as e:
print(e)
# Setting the /c300 target prim to Publish JointState node
set_target_prims(
primPath="/ActionGraph/PublishJointState", targetPrimPaths=[C300_STAGE_PATH]
)
# Setting the /c300's Lidar target prim to read scan data in the simulation
set_target_prims(
primPath="/ActionGraph/IsaacReadLidarBeams",
inputName="inputs:lidarPrim",
targetPrimPaths=[C300_STAGE_PATH + "/Chassis/Laser/UAM_05LP/UAM_05LP/Scan/Lidar"],
)
simulation_app.update()
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
simulation_context.play()
while simulation_app.is_running():
# Run with a fixed step size
simulation_context.step(render=True)
# Tick the Publish/Subscribe JointState, Publish TF and Publish Clock nodes each frame
og.Controller.set(
og.Controller.attribute("/ActionGraph/OnImpulseEvent.state:enableImpulse"), True
)
simulation_context.stop()
simulation_app.close()
| 9,341 | Python | 36.368 | 120 | 0.58741 |
MarqRazz/c3pzero/c300/c300_description/usd/README.md | # Known issues with simulating c300 in Isaac
- Currently the wheel friction is set to a value of `10.0` but for rubber it should only require around `0.8`. It was increased to make the odometry match what is observed on the real robot with concrete floors.
- In the omnigraph for c300 a negative time offset is required for the LIDAR messages published by Isaac.
This is because the data's timestamp is ahead of all values available in the tf buffer.
Isaac (and Gazebo) require a `wheel radius multiplier` of less than 1.0 to get the odometry to report correctly.
When navigating the odometry is still not perfect and the localization system needs to compensate more than expected when the base it rotating.
| 711 | Markdown | 70.199993 | 211 | 0.791842 |
MarqRazz/c3pzero/doc/developer.md | # Developers Guide
## Quickly update code repositories
To make sure you have the latest repos:
cd $COLCON_WS/src/c3pzero
git checkout main
git pull origin main
cd $COLCON_WS/src
rosdep install --from-paths . --ignore-src -y
## Setup pre-commit
pre-commit is a tool to automatically run formatting checks on each commit, which saves you from manually running clang-format (or, crucially, from forgetting to run them!).
Install pre-commit like this:
```
pip3 install pre-commit
```
Run this in the top directory of the repo to set up the git hooks:
```
pre-commit install
```
## Using ccache
> *Note*: This is already setup in the Docker container
ccache is a useful tool to speed up compilation times with GCC or any other sufficiently similar compiler.
To install ccache on Linux:
sudo apt-get install ccache
For other OS, search the package manager or software store for ccache, or refer to the [ccache website](https://ccache.dev/)
### Setup
To use ccache after installing it there are two methods. you can add it to your PATH or you can configure it for more specific uses.
ccache must be in front of your regular compiler or it won't be called. It is recommended that you add this line to your `.bashrc`:
export PATH=/usr/lib/ccache:$PATH
To configure ccache for more particular uses, set the CC and CXX environment variables before invoking make, cmake, catkin_make or catkin build.
For more information visit the [ccache website](https://ccache.dev/).
| 1,516 | Markdown | 28.745097 | 173 | 0.742744 |
MarqRazz/c3pzero/doc/installation.md | # Installation
These instructions assume you are utilizing Docker to build the robot's workspace.
# Setup the C3pzero workspace
1. On the host PC create a workspace that we can share with the docker container (*Note:* Currently the docker container expects this exact workspace `COLCON_WS` name)
``` bash
export COLCON_WS=~/c3pzero_ws/
mkdir -p $COLCON_WS/src
```
2. Get the repo and install any dependencies:
``` bash
cd $COLCON_WS/src
git clone https://github.com/MarqRazz/c3pzero.git
vcs import < c3pzero/c3pzero.repos
```
# Build and run the Docker container
1. Move into the `c3pzero` package where the `docker-compose.yaml` is located and build the docker container with:
``` bash
cd $COLCON_WS/src/c3pzero
docker compose build gpu
```
> *NOTE:* If your machine does not have an Nvidia GPU, run `docker compose build cpu` to build a container without GPU support.
2. Run the Docker container:
``` bash
docker compose run gpu # or cpu
```
3. In a second terminal attach to the container with:
``` bash
docker exec -it c3pzero bash
```
4. Build the colcon workspace with:
``` bash
colcon build --symlink-install --event-handlers log-
```
| 1,151 | Markdown | 25.790697 | 167 | 0.742832 |
MarqRazz/c3pzero/doc/user.md | # User Guide
These instructions assume you have followed the [Installation](doc/installation.md) guide and have a terminal running inside the Docker container.
## To start the `c300` mobile base in Gazebo run the following command:
``` bash
ros2 launch c300_bringup c300_sim.launch.py
```
# To teleoperate the robot with a Logitech F710 joystick run:
``` bash
ros2 launch c300_driver teleop.launch.py
```
> NOTE: in simulation the `cmd_vel` topic is on `/diff_drive_base_controller/cmd_vel_unstamped`
| 504 | Markdown | 32.666664 | 146 | 0.761905 |
MarqRazz/c3pzero/c3pzero/README.md | # c3pzero Mobile Robot
## To view the robots URDF in Rviz you can use the following launch file:
``` bash
ros2 launch c3pzero_description view_robot_urdf.launch.py
```
<img src="../doc/c3pzero_urdf.png" width="50%" >
## To start the `c3pzero` mobile robot in Gazebo run the following command:
``` bash
ros2 launch c3pzero_bringup gazebo_c3pzero.launch.py launch _rviz:=false
```
## To start the `c3pzero` mobile robot in Isaac run the following commands:
From the `c3pzero_description/usd` folder on the host start the robot in Isaac Sim
``` bash
./python.sh isaac_c3pzero.py
```
Inside the `c3pzero` Docker container start the robot controllers
``` bash
ros2 launch c3pzero_bringup gazebo_c3pzero.launch.py launch _rviz:=false
```
## To start MoveIt to control the simulated robot run the following command:
``` bash
ros2 launch c3pzero_moveit_config move_group.launch.py
```
## To test out the controllers in simulation you can run the following commands:
- Arm home pose
``` bash
ros2 topic pub /joint_trajectory_controller/joint_trajectory trajectory_msgs/JointTrajectory "{
joint_names: [gen3_joint_1, gen3_joint_2, gen3_joint_3, gen3_joint_4, gen3_joint_5, gen3_joint_6, gen3_joint_7],
points: [
{ positions: [0.0, 0.26, 3.14, -2.27, 0.0, 0.96, 1.57], time_from_start: { sec: 2 } },
]
}" -1
```
- Arm retracted pose
``` bash
ros2 topic pub /joint_trajectory_controller/joint_trajectory trajectory_msgs/JointTrajectory "{
joint_names: [gen3_joint_1, gen3_joint_2, gen3_joint_3, gen3_joint_4, gen3_joint_5, gen3_joint_6, gen3_joint_7],
points: [
{ positions: [0.0, -0.35, 3.14, -2.54, 0.0, -0.87, 1.57], time_from_start: { sec: 2 } },
]
}" -1
```
- GripperActionController (Open position: 0, Closed: 0.8)
``` bash
ros2 action send_goal /robotiq_gripper_controller/gripper_cmd control_msgs/action/GripperCommand "{command: {position: 0.0}}"
```
## To test sending commands directly to Isaac Sim you can run the following commands:
> NOTE: sending command that are far away from the robots current pose can cause the simulation to go unstable and be thrown around in the world.
- Arm home pose
``` bash
ros2 topic pub /isaac_joint_commands sensor_msgs/JointState "{
name: [gen3_joint_1, gen3_joint_2, gen3_joint_3, gen3_joint_4, gen3_joint_5, gen3_joint_6, gen3_joint_7],
position: [0.0, 0.26, 3.14, -2.27, 0.0, 0.96, 1.57]
}" -1
```
- Arm retracted pose
``` bash
ros2 topic pub /isaac_joint_commands sensor_msgs/JointState "{
name: [gen3_joint_1, gen3_joint_2, gen3_joint_3, gen3_joint_4, gen3_joint_5, gen3_joint_6, gen3_joint_7],
position: [0.0, -0.35, 3.14, -2.54, 0.0, -0.87, 1.57]
}" -1
```
| 2,640 | Markdown | 34.213333 | 145 | 0.702652 |
MarqRazz/c3pzero/c3pzero/c3pzero_description/usd/README.md | # Known issues with simulating c300 in Isaac
- Currently the wheel friction is set to a value of `10.0` but for rubber it should only require around `0.8`. It was increased to make the odometry match what is observed on the real robot with concrete floors.
- In the omnigraph for c300 a negative time offset is required for the LIDAR messages published by Isaac.
This is because the data's timestamp is ahead of all values available in the tf buffer.
Isaac (and Gazebo) require a `wheel radius multiplier` of less than 1.0 to get the odometry to report correctly.
When navigating the odometry is still not perfect and the localization system needs to compensate more than expected when the base it rotating.
Running each ros2_control hardware interface as if it were real hardware causes the joint commands to come in separately.
This causes jerky execution and can cause the simulation to go unstable.
I am keeping 3 usd files for the arm; as imported, manually tuned gains, and inverting joint angles to make rotation directions match values reported on ROS topic.
Inverting the joint angles looks to be an Isaac bug because the values reported in the UI do not match.
| 1,176 | Markdown | 72.562495 | 211 | 0.798469 |
MarqRazz/c3pzero/c3pzero/c3pzero_description/usd/isaac_c3pzero.py | # -*- coding: utf-8 -*-
import argparse
import os
import sys
import carb
import numpy as np
from omni.isaac.kit import SimulationApp
C3PZERO_STAGE_PATH = "/c3pzero"
CAMERA_PRIM_PATH = (
f"{C3PZERO_STAGE_PATH}/kbot/wrist_mounted_camera_color_frame/RealsenseCamera"
)
BACKGROUND_STAGE_PATH = "/background"
BACKGROUND_USD_PATH = (
"/Isaac/Environments/Simple_Warehouse/warehouse_multiple_shelves.usd"
)
REALSENSE_VIEWPORT_NAME = "realsense_viewport"
# Initialize the parser
parser = argparse.ArgumentParser(
description="Process the path to the robot's folder containing its UDS file"
)
# Add the arguments
parser.add_argument(
"Path", metavar="path", type=str, help="the path to the robot's folder"
)
# Parse the arguments
args = parser.parse_args()
# Check if the path argument was provided
if args.Path:
GEN3_USD_PATH = args.Path + "/c3pzero_composite.usd"
else:
print(
"[ERROR] This script requires an argument with the absolute path to the robot's folder containing it's UDS file"
)
sys.exit()
CONFIG = {"renderer": "RayTracedLighting", "headless": False}
# Example ROS2 bridge sample demonstrating the manual loading of stages
# and creation of ROS components
simulation_app = SimulationApp(CONFIG)
import omni.graph.core as og # noqa E402
from omni.isaac.core import SimulationContext # noqa E402
from omni.isaac.core.utils import ( # noqa E402
extensions,
nucleus,
prims,
rotations,
stage,
viewports,
)
from omni.isaac.core.utils.prims import set_targets
from omni.isaac.core_nodes.scripts.utils import set_target_prims # noqa E402
from pxr import Gf, UsdGeom # noqa E402
from pxr import Gf # noqa E402
import omni.ui # to dock realsense viewport automatically
# enable ROS2 bridge extension
extensions.enable_extension("omni.isaac.ros2_bridge")
simulation_context = SimulationContext(stage_units_in_meters=1.0)
# Locate Isaac Sim assets folder to load environment and robot stages
assets_root_path = nucleus.get_assets_root_path()
if assets_root_path is None:
carb.log_error("Could not find Isaac Sim assets folder")
simulation_app.close()
sys.exit()
# Preparing stage
viewports.set_camera_view(eye=np.array([3, 0.5, 0.8]), target=np.array([0, 0, 0.5]))
# Loading the simple_room environment
stage.add_reference_to_stage(
assets_root_path + BACKGROUND_USD_PATH, BACKGROUND_STAGE_PATH
)
# Loading the gen3 robot USD
prims.create_prim(
C3PZERO_STAGE_PATH,
"Xform",
position=np.array([1, 0, 0.17]),
orientation=rotations.gf_rotation_to_np_array(Gf.Rotation(Gf.Vec3d(0, 0, 1), 90)),
usd_path=GEN3_USD_PATH,
)
simulation_app.update()
# Creating a action graph with ROS component nodes
# TODO: Creating the omnigraph here is getting ridiculous!
# Move them into the USD files or refactor to use helper functions to build the graph.
try:
og.Controller.edit(
{"graph_path": "/ActionGraph", "evaluator_name": "execution"},
{
og.Controller.Keys.CREATE_NODES: [
("OnImpulseEvent", "omni.graph.action.OnImpulseEvent"),
("ReadSimTime", "omni.isaac.core_nodes.IsaacReadSimulationTime"),
("Context", "omni.isaac.ros2_bridge.ROS2Context"),
("PublishJointState", "omni.isaac.ros2_bridge.ROS2PublishJointState"),
(
"MobileBaseSubscribeJointState",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"MobileBaseArticulationController",
"omni.isaac.core_nodes.IsaacArticulationController",
),
(
"ManipulatorSubscribeJointState",
"omni.isaac.ros2_bridge.ROS2SubscribeJointState",
),
(
"ManipulatorArticulationController",
"omni.isaac.core_nodes.IsaacArticulationController",
),
("PublishClock", "omni.isaac.ros2_bridge.ROS2PublishClock"),
("IsaacReadLidarBeams", "omni.isaac.range_sensor.IsaacReadLidarBeams"),
("PublishLidarScan", "omni.isaac.ros2_bridge.ROS2PublishLaserScan"),
# Nodes to subtract some time of the lidar message so it's timestamps match the tf tree in ROS
("ConstantFloat", "omni.graph.nodes.ConstantFloat"),
("Subtract", "omni.graph.nodes.Subtract"),
# Wrist camera
("OnTick", "omni.graph.action.OnTick"),
("createViewport", "omni.isaac.core_nodes.IsaacCreateViewport"),
(
"getRenderProduct",
"omni.isaac.core_nodes.IsaacGetViewportRenderProduct",
),
("setCamera", "omni.isaac.core_nodes.IsaacSetCameraOnRenderProduct"),
("cameraHelperRgb", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("cameraHelperInfo", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
("cameraHelperDepth", "omni.isaac.ros2_bridge.ROS2CameraHelper"),
],
og.Controller.Keys.CONNECT: [
("OnImpulseEvent.outputs:execOut", "PublishJointState.inputs:execIn"),
("OnImpulseEvent.outputs:execOut", "PublishClock.inputs:execIn"),
(
"OnImpulseEvent.outputs:execOut",
"MobileBaseSubscribeJointState.inputs:execIn",
),
(
"Context.outputs:context",
"MobileBaseSubscribeJointState.inputs:context",
),
(
"OnImpulseEvent.outputs:execOut",
"MobileBaseArticulationController.inputs:execIn",
),
(
"MobileBaseSubscribeJointState.outputs:jointNames",
"MobileBaseArticulationController.inputs:jointNames",
),
(
"MobileBaseSubscribeJointState.outputs:positionCommand",
"MobileBaseArticulationController.inputs:positionCommand",
),
(
"MobileBaseSubscribeJointState.outputs:velocityCommand",
"MobileBaseArticulationController.inputs:velocityCommand",
),
(
"MobileBaseSubscribeJointState.outputs:effortCommand",
"MobileBaseArticulationController.inputs:effortCommand",
),
(
"OnImpulseEvent.outputs:execOut",
"ManipulatorSubscribeJointState.inputs:execIn",
),
(
"Context.outputs:context",
"ManipulatorSubscribeJointState.inputs:context",
),
(
"OnImpulseEvent.outputs:execOut",
"ManipulatorArticulationController.inputs:execIn",
),
(
"ManipulatorSubscribeJointState.outputs:jointNames",
"ManipulatorArticulationController.inputs:jointNames",
),
(
"ManipulatorSubscribeJointState.outputs:positionCommand",
"ManipulatorArticulationController.inputs:positionCommand",
),
(
"ManipulatorSubscribeJointState.outputs:velocityCommand",
"ManipulatorArticulationController.inputs:velocityCommand",
),
(
"ManipulatorSubscribeJointState.outputs:effortCommand",
"ManipulatorArticulationController.inputs:effortCommand",
),
("Context.outputs:context", "PublishJointState.inputs:context"),
("Context.outputs:context", "PublishClock.inputs:context"),
(
"ReadSimTime.outputs:simulationTime",
"PublishJointState.inputs:timeStamp",
),
("ReadSimTime.outputs:simulationTime", "PublishClock.inputs:timeStamp"),
# Hack time offset for lidar messages
("ReadSimTime.outputs:simulationTime", "Subtract.inputs:a"),
("ConstantFloat.inputs:value", "Subtract.inputs:b"),
# Lidar nodes
(
"OnImpulseEvent.outputs:execOut",
"IsaacReadLidarBeams.inputs:execIn",
),
(
"IsaacReadLidarBeams.outputs:execOut",
"PublishLidarScan.inputs:execIn",
),
(
"IsaacReadLidarBeams.outputs:azimuthRange",
"PublishLidarScan.inputs:azimuthRange",
),
(
"IsaacReadLidarBeams.outputs:depthRange",
"PublishLidarScan.inputs:depthRange",
),
(
"IsaacReadLidarBeams.outputs:horizontalFov",
"PublishLidarScan.inputs:horizontalFov",
),
(
"IsaacReadLidarBeams.outputs:horizontalResolution",
"PublishLidarScan.inputs:horizontalResolution",
),
(
"IsaacReadLidarBeams.outputs:intensitiesData",
"PublishLidarScan.inputs:intensitiesData",
),
(
"IsaacReadLidarBeams.outputs:linearDepthData",
"PublishLidarScan.inputs:linearDepthData",
),
(
"IsaacReadLidarBeams.outputs:numCols",
"PublishLidarScan.inputs:numCols",
),
(
"IsaacReadLidarBeams.outputs:numRows",
"PublishLidarScan.inputs:numRows",
),
(
"IsaacReadLidarBeams.outputs:rotationRate",
"PublishLidarScan.inputs:rotationRate",
),
(
"Subtract.outputs:difference",
"PublishLidarScan.inputs:timeStamp",
),
("Context.outputs:context", "PublishLidarScan.inputs:context"),
# wrist camera
("OnTick.outputs:tick", "createViewport.inputs:execIn"),
("createViewport.outputs:execOut", "getRenderProduct.inputs:execIn"),
("createViewport.outputs:viewport", "getRenderProduct.inputs:viewport"),
("getRenderProduct.outputs:execOut", "setCamera.inputs:execIn"),
(
"getRenderProduct.outputs:renderProductPath",
"setCamera.inputs:renderProductPath",
),
("setCamera.outputs:execOut", "cameraHelperRgb.inputs:execIn"),
("setCamera.outputs:execOut", "cameraHelperInfo.inputs:execIn"),
("setCamera.outputs:execOut", "cameraHelperDepth.inputs:execIn"),
("Context.outputs:context", "cameraHelperRgb.inputs:context"),
("Context.outputs:context", "cameraHelperInfo.inputs:context"),
("Context.outputs:context", "cameraHelperDepth.inputs:context"),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperRgb.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperInfo.inputs:renderProductPath",
),
(
"getRenderProduct.outputs:renderProductPath",
"cameraHelperDepth.inputs:renderProductPath",
),
],
og.Controller.Keys.SET_VALUES: [
("Context.inputs:domain_id", int(os.environ["ROS_DOMAIN_ID"])),
# Setting the /c3pzero target prim to Articulation Controller node
("MobileBaseArticulationController.inputs:usePath", True),
(
"MobileBaseArticulationController.inputs:robotPath",
C3PZERO_STAGE_PATH,
),
(
"MobileBaseSubscribeJointState.inputs:topicName",
"mobile_base_joint_commands",
),
("ManipulatorArticulationController.inputs:usePath", True),
(
"ManipulatorArticulationController.inputs:robotPath",
C3PZERO_STAGE_PATH,
),
(
"ManipulatorSubscribeJointState.inputs:topicName",
"manipulator_joint_commands",
),
("PublishJointState.inputs:topicName", "isaac_joint_states"),
(
"PublishLidarScan.inputs:frameId",
"base_laser",
), # c300's laser frame_id
("PublishLidarScan.inputs:topicName", "scan"),
# Hack time offset for lidar messages
("ConstantFloat.inputs:value", 0.1),
# Wrist camera
("createViewport.inputs:name", REALSENSE_VIEWPORT_NAME),
("createViewport.inputs:viewportId", 1),
(
"cameraHelperRgb.inputs:frameId",
"wrist_mounted_camera_color_optical_frame",
),
(
"cameraHelperRgb.inputs:topicName",
"/wrist_mounted_camera/color/image_raw",
),
("cameraHelperRgb.inputs:type", "rgb"),
(
"cameraHelperInfo.inputs:frameId",
"wrist_mounted_camera_color_optical_frame",
),
(
"cameraHelperInfo.inputs:topicName",
"/wrist_mounted_camera/color/camera_info",
),
("cameraHelperInfo.inputs:type", "camera_info"),
(
"cameraHelperDepth.inputs:frameId",
"wrist_mounted_camera_color_optical_frame",
),
(
"cameraHelperDepth.inputs:topicName",
"/wrist_mounted_camera/depth/image_rect_raw",
),
("cameraHelperDepth.inputs:type", "depth"),
],
},
)
except Exception as e:
print(e)
# Setting the /c300 target prim to Publish JointState node
set_target_prims(
primPath="/ActionGraph/PublishJointState", targetPrimPaths=[C3PZERO_STAGE_PATH]
)
# Setting the /c300's Lidar target prim to read scan data in the simulation
set_target_prims(
primPath="/ActionGraph/IsaacReadLidarBeams",
inputName="inputs:lidarPrim",
targetPrimPaths=[
C3PZERO_STAGE_PATH + "/c300/Chassis/Laser/UAM_05LP/UAM_05LP/Scan/Lidar"
],
)
# Fix camera settings since the defaults in the realsense model are inaccurate
realsense_prim = UsdGeom.Camera(
stage.get_current_stage().GetPrimAtPath(CAMERA_PRIM_PATH)
)
realsense_prim.GetHorizontalApertureAttr().Set(20.955)
realsense_prim.GetVerticalApertureAttr().Set(11.7)
realsense_prim.GetFocalLengthAttr().Set(18.8)
realsense_prim.GetFocusDistanceAttr().Set(400)
realsense_prim.GetClippingRangeAttr().Set(Gf.Vec2f(0.01, 1000000.0))
set_targets(
prim=stage.get_current_stage().GetPrimAtPath("/ActionGraph/setCamera"),
attribute="inputs:cameraPrim",
target_prim_paths=[CAMERA_PRIM_PATH],
)
simulation_app.update()
# need to initialize physics getting any articulation..etc
simulation_context.initialize_physics()
simulation_context.play()
# Dock the second camera window
viewport = omni.ui.Workspace.get_window("Viewport")
rs_viewport = omni.ui.Workspace.get_window(REALSENSE_VIEWPORT_NAME)
rs_viewport.dock_in(viewport, omni.ui.DockPosition.RIGHT)
while simulation_app.is_running():
# Run with a fixed step size
simulation_context.step(render=True)
# Tick the Publish/Subscribe JointState, Publish TF and Publish Clock nodes each frame
og.Controller.set(
og.Controller.attribute("/ActionGraph/OnImpulseEvent.state:enableImpulse"), True
)
simulation_context.stop()
simulation_app.close()
| 16,470 | Python | 39.370098 | 120 | 0.570431 |
MarqRazz/c3pzero/c3pzero/c3pzero_bringup/launch/isaac_c3pzero.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
import shlex
from launch import LaunchDescription
from launch.actions import (
DeclareLaunchArgument,
RegisterEventHandler,
)
from launch.event_handlers import OnProcessExit
from launch.conditions import IfCondition
from launch.substitutions import (
Command,
FindExecutable,
LaunchConfiguration,
PathJoinSubstitution,
)
from launch_ros.actions import ComposableNodeContainer, Node
import launch_ros.descriptions
from launch_ros.substitutions import FindPackageShare
def generate_launch_description():
declared_arguments = []
# Simulation specific arguments
declared_arguments.append(
DeclareLaunchArgument(
"sim_isaac",
default_value="True",
description="Use Nvidia Isaac for simulation",
)
)
# General arguments
declared_arguments.append(
DeclareLaunchArgument(
"runtime_config_package",
default_value="c3pzero_bringup",
description='Package with the controller\'s configuration in "config" folder. \
Usually the argument is not set, it enables use of a custom setup.',
)
)
declared_arguments.append(
DeclareLaunchArgument(
"controllers_file",
default_value="c3pzero_isaac_controllers.yaml",
description="YAML file with the controllers configuration.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_package",
default_value="c3pzero_description",
description="Description package with robot URDF/XACRO files. Usually the argument \
is not set, it enables use of a custom description.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"description_file",
default_value="c3pzero_kinova_gen3.xacro",
description="URDF/XACRO description file with the robot.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"diff_drive_controller",
default_value="diff_drive_base_controller",
description="Diff drive base controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"jtc_controller",
default_value="joint_trajectory_controller",
description="Robot controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"robot_hand_controller",
default_value="robotiq_gripper_controller",
description="Robot hand controller to start.",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="True", description="Launch RViz?"
)
)
declared_arguments.append(
DeclareLaunchArgument(
"use_sim_time",
default_value="True",
description="Use simulation (Gazebo) clock if true",
)
)
# Initialize Arguments
sim_isaac = LaunchConfiguration("sim_isaac")
# General arguments
runtime_config_package = LaunchConfiguration("runtime_config_package")
controllers_file = LaunchConfiguration("controllers_file")
description_package = LaunchConfiguration("description_package")
description_file = LaunchConfiguration("description_file")
diff_drive_controller = LaunchConfiguration("diff_drive_controller")
robot_traj_controller = LaunchConfiguration("jtc_controller")
robot_hand_controller = LaunchConfiguration("robot_hand_controller")
launch_rviz = LaunchConfiguration("launch_rviz")
use_sim_time = LaunchConfiguration("use_sim_time")
robot_controllers = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "config", controllers_file]
)
rviz_config_file = PathJoinSubstitution(
[FindPackageShare(runtime_config_package), "rviz", "bringup_config.rviz"]
)
robot_description_content = Command(
[
PathJoinSubstitution([FindExecutable(name="xacro")]),
" ",
PathJoinSubstitution(
[FindPackageShare(description_package), "urdf", description_file]
),
" ",
"sim_isaac:=",
sim_isaac,
" ",
"sim_ignition:=False",
" ",
]
)
robot_description = {"robot_description": robot_description_content}
control_node = Node(
package="controller_manager",
executable="ros2_control_node",
parameters=[
{"use_sim_time": use_sim_time},
robot_description,
robot_controllers,
],
remappings=[
("/diff_drive_base_controller/cmd_vel_unstamped", "/cmd_vel"),
("/diff_drive_base_controller/odom", "/odom"),
],
output="both",
)
robot_state_publisher_node = Node(
package="robot_state_publisher",
executable="robot_state_publisher",
output="both",
parameters=[
{
"use_sim_time": use_sim_time,
"robot_description": robot_description_content,
}
],
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
arguments=["-d", rviz_config_file],
condition=IfCondition(launch_rviz),
)
joint_state_broadcaster_spawner = Node(
package="controller_manager",
executable="spawner",
parameters=[{"use_sim_time": use_sim_time}],
arguments=[
"joint_state_broadcaster",
"--controller-manager",
"/controller_manager",
],
)
# Delay rviz start after `joint_state_broadcaster`
delay_rviz_after_joint_state_broadcaster_spawner = RegisterEventHandler(
event_handler=OnProcessExit(
target_action=joint_state_broadcaster_spawner,
on_exit=[rviz_node],
)
)
robot_traj_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[robot_traj_controller, "-c", "/controller_manager"],
)
diff_drive_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[diff_drive_controller, "-c", "/controller_manager"],
)
robot_hand_controller_spawner = Node(
package="controller_manager",
executable="spawner",
arguments=[robot_hand_controller, "-c", "/controller_manager"],
)
# launch point cloud plugin through rclcpp_components container
# see https://github.com/ros-perception/image_pipeline/blob/humble/depth_image_proc/launch/point_cloud_xyz.launch.py
point_cloud_node = ComposableNodeContainer(
name="container",
namespace="",
package="rclcpp_components",
executable="component_container",
composable_node_descriptions=[
# Driver itself
launch_ros.descriptions.ComposableNode(
package="depth_image_proc",
plugin="depth_image_proc::PointCloudXyzrgbNode",
name="point_cloud_xyz_node",
remappings=[
("rgb/image_rect_color", "/wrist_mounted_camera/color/image_raw"),
("rgb/camera_info", "/wrist_mounted_camera/color/camera_info"),
(
"depth_registered/image_rect",
"/wrist_mounted_camera/depth/image_rect_raw",
),
("points", "/wrist_mounted_camera/depth/color/points"),
],
),
],
output="screen",
)
nodes_to_start = [
control_node,
robot_state_publisher_node,
joint_state_broadcaster_spawner,
delay_rviz_after_joint_state_broadcaster_spawner,
diff_drive_controller_spawner,
robot_traj_controller_spawner,
robot_hand_controller_spawner,
point_cloud_node,
]
return LaunchDescription(declared_arguments + nodes_to_start)
| 8,173 | Python | 31.959677 | 120 | 0.605408 |
MarqRazz/c3pzero/c3pzero/c3pzero_bringup/config/c3pzero_gz_controllers.yaml | controller_manager:
ros__parameters:
update_rate: 500 # Hz
joint_state_broadcaster:
type: joint_state_broadcaster/JointStateBroadcaster
diff_drive_base_controller:
type: diff_drive_controller/DiffDriveController
joint_trajectory_controller:
type: joint_trajectory_controller/JointTrajectoryController
robotiq_gripper_controller:
type: position_controllers/GripperActionController
diff_drive_base_controller:
ros__parameters:
left_wheel_names: ["drivewhl_l_joint"]
right_wheel_names: ["drivewhl_r_joint"]
wheels_per_side: 1
wheel_separation: 0.61 # outside distance between the wheels
wheel_radius: 0.1715
wheel_separation_multiplier: 1.0
left_wheel_radius_multiplier: 1.0
right_wheel_radius_multiplier: 1.0
publish_rate: 50.0
odom_frame_id: odom
base_frame_id: base_link
pose_covariance_diagonal : [0.001, 0.001, 0.0, 0.0, 0.0, 0.01]
twist_covariance_diagonal: [0.001, 0.0, 0.0, 0.0, 0.0, 0.01]
open_loop: false
position_feedback: true
enable_odom_tf: true
cmd_vel_timeout: 0.5
#publish_limited_velocity: true
use_stamped_vel: false
#velocity_rolling_window_size: 10
# Velocity and acceleration limits
# Whenever a min_* is unspecified, default to -max_*
linear.x.has_velocity_limits: true
linear.x.has_acceleration_limits: true
linear.x.has_jerk_limits: false
linear.x.max_velocity: 2.0
linear.x.min_velocity: -2.0
linear.x.max_acceleration: 0.5
linear.x.max_jerk: 0.0
linear.x.min_jerk: 0.0
angular.z.has_velocity_limits: true
angular.z.has_acceleration_limits: true
angular.z.has_jerk_limits: false
angular.z.max_velocity: 2.0
angular.z.min_velocity: -2.0
angular.z.max_acceleration: 1.0
angular.z.min_acceleration: -1.0
angular.z.max_jerk: 0.0
angular.z.min_jerk: 0.0
joint_trajectory_controller:
ros__parameters:
joints:
- gen3_joint_1
- gen3_joint_2
- gen3_joint_3
- gen3_joint_4
- gen3_joint_5
- gen3_joint_6
- gen3_joint_7
command_interfaces:
- position
state_interfaces:
- position
- velocity
state_publish_rate: 100.0
action_monitor_rate: 20.0
allow_partial_joints_goal: false
constraints:
stopped_velocity_tolerance: 0.0
goal_time: 0.0
robotiq_gripper_controller:
ros__parameters:
default: true
joint: gen3_robotiq_85_left_knuckle_joint
interface_name: position
| 2,508 | YAML | 25.978494 | 66 | 0.673046 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/launch/spawn_controllers.launch.py | # -*- coding: utf-8 -*-
from moveit_configs_utils import MoveItConfigsBuilder
from moveit_configs_utils.launches import generate_spawn_controllers_launch
def generate_launch_description():
moveit_config = MoveItConfigsBuilder(
"c3pzero_kinova_gen3", package_name="c3pzero_moveit_config"
).to_moveit_configs()
return generate_spawn_controllers_launch(moveit_config)
| 387 | Python | 34.272724 | 75 | 0.75969 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/launch/move_group.launch.py | # -*- coding: utf-8 -*-
# Author: Marq Rasmussen
import os
from launch import LaunchDescription
from launch.actions import DeclareLaunchArgument
from launch.substitutions import LaunchConfiguration
from launch_ros.actions import Node
from launch.conditions import IfCondition
from ament_index_python.packages import get_package_share_directory
from moveit_configs_utils import MoveItConfigsBuilder
def generate_launch_description():
declared_arguments = []
declared_arguments.append(
DeclareLaunchArgument(
"sim",
default_value="true",
description="Use simulated clock",
)
)
declared_arguments.append(
DeclareLaunchArgument(
"launch_rviz", default_value="true", description="Launch RViz?"
)
)
# Initialize Arguments
launch_rviz = LaunchConfiguration("launch_rviz")
use_sim_time = LaunchConfiguration("sim")
# This launch file assumes the robot is already running so we don't need to
# pass any special arguments to the URDF.xacro like sim_ignition or sim_isaac
# because the controllers should already be running.
description_arguments = {
"robot_ip": "xxx.yyy.zzz.www",
"use_fake_hardware": "false",
}
moveit_config = (
MoveItConfigsBuilder("gen3", package_name="c3pzero_moveit_config")
.robot_description(mappings=description_arguments)
.planning_pipelines(pipelines=["ompl", "pilz_industrial_motion_planner"])
.to_moveit_configs()
)
# Start the actual move_group node/action server
move_group_node = Node(
package="moveit_ros_move_group",
executable="move_group",
output="log",
parameters=[moveit_config.to_dict(), {"use_sim_time": use_sim_time}],
arguments=[
"--ros-args",
"--log-level",
"fatal",
], # MoveIt is spamming the log because of unknown '*_mimic' joints
condition=IfCondition(launch_rviz),
)
rviz_config_path = os.path.join(
get_package_share_directory("c3pzero_moveit_config"),
"config",
"moveit.rviz",
)
rviz_node = Node(
package="rviz2",
executable="rviz2",
name="rviz2",
output="log",
arguments=["-d", rviz_config_path],
parameters=[
moveit_config.robot_description,
moveit_config.robot_description_semantic,
moveit_config.planning_pipelines,
moveit_config.robot_description_kinematics,
moveit_config.joint_limits,
{"use_sim_time": use_sim_time},
],
condition=IfCondition(launch_rviz),
)
return LaunchDescription(declared_arguments + [move_group_node, rviz_node])
| 2,769 | Python | 30.123595 | 81 | 0.63597 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/initial_positions.yaml | # Default initial positions for c3pzero_kinova_gen3's ros2_control fake system
initial_positions:
gen3_joint_1: 0
gen3_joint_2: 0
gen3_joint_3: 0
gen3_joint_4: 0
gen3_joint_5: 0
gen3_joint_6: 0
gen3_joint_7: 0
gen3_robotiq_85_left_knuckle_joint: 0
| 265 | YAML | 21.166665 | 78 | 0.709434 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/pilz_cartesian_limits.yaml | # Limits for the Pilz planner
cartesian_limits:
max_trans_vel: 1.0
max_trans_acc: 2.25
max_trans_dec: -5.0
max_rot_vel: 1.57
| 133 | YAML | 18.142855 | 29 | 0.676692 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/kinematics.yaml | manipulator:
kinematics_solver: kdl_kinematics_plugin/KDLKinematicsPlugin
kinematics_solver_search_resolution: 0.0050000000000000001
kinematics_solver_timeout: 0.0050000000000000001
| 188 | YAML | 36.799993 | 62 | 0.851064 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/moveit_controllers.yaml | # MoveIt uses this configuration for controller management
moveit_controller_manager: moveit_simple_controller_manager/MoveItSimpleControllerManager
moveit_simple_controller_manager:
controller_names:
- joint_trajectory_controller
- robotiq_gripper_controller
joint_trajectory_controller:
type: FollowJointTrajectory
action_ns: follow_joint_trajectory
default: true
joints:
- gen3_joint_1
- gen3_joint_2
- gen3_joint_3
- gen3_joint_4
- gen3_joint_5
- gen3_joint_6
- gen3_joint_7
robotiq_gripper_controller:
type: GripperCommand
joints:
- gen3_robotiq_85_left_knuckle_joint
action_ns: gripper_cmd
default: true
| 707 | YAML | 24.285713 | 89 | 0.701556 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/joint_limits.yaml | # joint_limits.yaml allows the dynamics properties specified in the URDF to be overwritten or augmented as needed
# For beginners, we downscale velocity and acceleration limits.
# You can always specify higher scaling factors (<= 1.0) in your motion requests. # Increase the values below to 1.0 to always move at maximum speed.
default_velocity_scaling_factor: 1.0
default_acceleration_scaling_factor: 1.0
# Specific joint properties can be changed with the keys [max_position, min_position, max_velocity, max_acceleration]
# Joint limits can be turned off with [has_velocity_limits, has_acceleration_limits]
joint_limits:
gen3_joint_1:
has_velocity_limits: true
max_velocity: 1.3963000000000001
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_2:
has_velocity_limits: true
max_velocity: 1.3963000000000001
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_3:
has_velocity_limits: true
max_velocity: 1.3963000000000001
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_4:
has_velocity_limits: true
max_velocity: 1.3963000000000001
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_5:
has_velocity_limits: true
max_velocity: 1.2218
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_6:
has_velocity_limits: true
max_velocity: 1.2218
has_acceleration_limits: true
max_acceleration: 8.6
gen3_joint_7:
has_velocity_limits: true
max_velocity: 1.2218
has_acceleration_limits: true
max_acceleration: 8.6
gen3_robotiq_85_left_knuckle_joint:
has_velocity_limits: true
max_velocity: 0.5
has_acceleration_limits: true
max_acceleration: 1.0
| 1,741 | YAML | 33.156862 | 150 | 0.73004 |
MarqRazz/c3pzero/c3pzero/c3pzero_moveit_config/config/ompl_planning.yaml | planning_plugin: ompl_interface/OMPLPlanner
start_state_max_bounds_error: 0.1
jiggle_fraction: 0.05
request_adapters: >-
default_planner_request_adapters/AddTimeOptimalParameterization
default_planner_request_adapters/ResolveConstraintFrames
default_planner_request_adapters/FixWorkspaceBounds
default_planner_request_adapters/FixStartStateBounds
default_planner_request_adapters/FixStartStateCollision
default_planner_request_adapters/FixStartStatePathConstraints
| 489 | YAML | 43.545451 | 67 | 0.838446 |
True-VFX/kit-ext-cube_array/README.md | # Cube Array Sample Extension

## Adding This Extension
To add a this extension to your Omniverse app:
1. Go into: Extension Manager -> Gear Icon -> Extension Search Path
2. Add this as a search path: `git://github.com/True-VFX/kit-ext-cube_array.git?branch=main&dir=exts`
## Using This Extension
1. Click the large 'Create Array' button. This will add an xform object to your stage
2. Mess with the X, Y, and Z values to determine how many cubes in each axis to create
3. Play with the Space Between to add more or less space between each cube
| 595 | Markdown | 38.733331 | 101 | 0.754622 |
True-VFX/kit-ext-cube_array/exts/tvfx.tools.cube_array/tvfx/tools/cube_array/extension.py | from functools import partial
from pxr import UsdGeom, Usd, Sdf, Gf
from pxr.Usd import Stage
import omni.ext
import omni.kit.commands
import omni.ui as ui
import omni.usd
# PYTHON 3.7.12
def create_uint_slider(axis:str, min=0, max=50, default=1) -> ui.UIntSlider:
ui.Label(f"{axis.capitalize()}:",width=20)
slider = ui.UIntSlider(
min=min,
max=max,
tooltip=f"The number of boxes to create in the {axis.capitalize()} axis"
)
slider.model.set_value(default)
int_field = ui.IntField(width=30)
int_field.model = slider.model
return slider
def on_slider_change(x_slider:ui.UIntSlider,y_slider:ui.UIntSlider,z_slider:ui.UIntSlider, space_slider:ui.UIntSlider, _b:float, xform:UsdGeom.Xform=None):
global cubes
# Get Active Prim
space = space_slider.model.get_value_as_float()*100
stage:Stage = omni.usd.get_context().get_stage()
selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
if not selection:
return
selected_xform = xform or stage.GetPrimAtPath(selection[0])
# Ensure PointInstancer
if not selected_xform or selected_xform.GetPrim().GetTypeName() != "PointInstancer":
return
# Get XYZ values
x_count = x_slider.model.get_value_as_int()
y_count = y_slider.model.get_value_as_int()
z_count = z_slider.model.get_value_as_int()
ids = []
positions = []
# Create Cube Array
for i in range(x_count):
x = i*100+space*i
for j in range(y_count):
y = j*100+space*j
for k in range(z_count):
b = j*x_count
c = k*y_count*x_count
n = (i+b+c)
positions.append((x, y, k*100+space*k))
ids.append(0)
instancer = UsdGeom.PointInstancer(selected_xform.GetPrim())
instancer.CreateProtoIndicesAttr()
instancer.CreatePositionsAttr()
instancer.GetProtoIndicesAttr().Set(ids)
instancer.GetPositionsAttr().Set(positions)
def on_space_change(x_slider:ui.UIntSlider,y_slider:ui.UIntSlider,z_slider:ui.UIntSlider, space_slider:ui.UIntSlider, _b:float, xform:UsdGeom.Xform=None):
space = space_slider.model.get_value_as_float()*100
stage:Stage = omni.usd.get_context().get_stage()
# Get Active Selection
selection = omni.usd.get_context().get_selection().get_selected_prim_paths()
if not selection:
return
selected_xform = xform or stage.GetPrimAtPath(selection[0])
# Ensure PointInstancer
if not selected_xform or selected_xform.GetPrim().GetTypeName() != "PointInstancer":
return
# Get XYZ Values
x_count = x_slider.model.get_value_as_int()
y_count = y_slider.model.get_value_as_int()
z_count = z_slider.model.get_value_as_int()
ids = []
positions = []
# Translate Cubes
for i in range(x_count):
x = i*100+space*i
for j in range(y_count):
y = j*100+space*j
for k in range(z_count):
b = j*x_count
c = k*y_count*x_count
n = (i+b+c)
positions.append((x, y, k*100+space*k))
ids.append(0)
instancer = UsdGeom.PointInstancer(selected_xform.GetPrim())
instancer.CreateProtoIndicesAttr()
instancer.CreatePositionsAttr()
instancer.GetProtoIndicesAttr().Set(ids)
instancer.GetPositionsAttr().Set(positions)
class MyExtension(omni.ext.IExt):
def on_startup(self, ext_id):
print("[tvfx.tools.cube_array] MyExtension startup")
self._window = ui.Window("My Window", width=300, height=300)
with self._window.frame:
with ui.VStack():
# Create Slider Row
with ui.HStack(height=20):
x_slider = create_uint_slider("X")
y_slider = create_uint_slider("Y")
z_slider = create_uint_slider("Z")
ui.Spacer(height=7)
with ui.HStack(height=20):
ui.Label("Space Between:")
space_slider = ui.FloatSlider(min=0.0,max=10)
space_slider.model.set_value(0.5)
space_field = ui.FloatField(width=30)
space_field.model = space_slider.model
# Add Functions on Change
x_slider.model.add_value_changed_fn(partial(on_slider_change, x_slider,y_slider,z_slider,space_slider))
y_slider.model.add_value_changed_fn(partial(on_slider_change, x_slider,y_slider,z_slider,space_slider))
z_slider.model.add_value_changed_fn(partial(on_slider_change, x_slider,y_slider,z_slider,space_slider))
space_slider.model.add_value_changed_fn(partial(on_space_change, x_slider,y_slider,z_slider,space_slider))
# Create Array Xform Button
def create_array_holder(x_slider:ui.UIntSlider,y_slider:ui.UIntSlider,z_slider:ui.UIntSlider, space_slider:ui.UIntSlider):
C:omni.usd.UsdContext = omni.usd.get_context()
stage:Stage = C.get_stage()
cube_array:UsdGeom.PointInstancer = UsdGeom.PointInstancer.Define(stage, stage.GetDefaultPrim().GetPath().AppendPath("Cube_Array"))
proto_container = stage.OverridePrim(cube_array.GetPath().AppendPath("Prototypes"))
cube = UsdGeom.Cube.Define(stage,proto_container.GetPath().AppendPath("Cube"))
cube.CreateSizeAttr(100)
cube_array.CreatePrototypesRel()
cube_array.GetPrototypesRel().AddTarget(cube.GetPath())
omni.kit.commands.execute(
'SelectPrimsCommand',
old_selected_paths=[],
new_selected_paths=[str(cube_array.GetPath())],
expand_in_stage=True
)
on_slider_change(x_slider, y_slider, z_slider, space_slider,None, xform=cube_array)
create_array_button = ui.Button(text="Create Array")
create_array_button.set_clicked_fn(partial(create_array_holder, x_slider,y_slider,z_slider,space_slider))
def on_shutdown(self):
print("[tvfx.tools.cube_array] MyExtension shutdown")
self._window.destroy()
self._window = None
stage:Stage = omni.usd.get_context().get_stage()
| 6,479 | Python | 39.754717 | 155 | 0.60071 |
True-VFX/kit-ext-cube_array/exts/tvfx.tools.cube_array/config/extension.toml | [package]
version = "1.0.0"
authors = ["True-VFX: Zach Eastin"]
title = "Simple Cube Array Creator"
description="Creates a simple 3D array of cubes"
category = "Tools"
readme = "docs/README.md"
repository = "https://github.com/True-VFX/kit-ext-cube_array"
preview_image = "data/preview.png"
icon = "data/icon.svg"
changelog="docs/CHANGELOG.md"
# Keywords for the extension
keywords = ["kit", "zach", "cube", "array","true-vfx", "tvfx"]
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.hello.world".
[[python.module]]
name = "tvfx.tools.cube_array"
| 672 | TOML | 21.433333 | 105 | 0.703869 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/MeshTools/SliceTool.py | import omni.ext
import omni.ui as ui
from pxr import Usd, UsdGeom, Gf
import numpy as np
import omni.kit.app
import omni.kit.commands
import os
class Slice_Tools:
def sliceMesh(self,PlaneAxis,Plane):
stage = omni.usd.get_context().get_stage()
prim_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if len(prim_paths) > 1:
return
for prim_path in prim_paths:
# Define a new Mesh primitive
prim_mesh = stage.GetPrimAtPath(prim_path)
split_mesh = UsdGeom.Mesh(prim_mesh)
faceVertexIndices1 = np.array(split_mesh.GetFaceVertexIndicesAttr().Get())
faceVertexCounts1 = np.array(split_mesh.GetFaceVertexCountsAttr().Get())
points1 = np.array(split_mesh.GetPointsAttr().Get())
indiBfrPlane = np.where(points1[:,PlaneAxis]<=Plane)
indiAftrPlane = np.where(points1[:,PlaneAxis]>=Plane)
faceVertexIndices1 = faceVertexIndices1.reshape(-1,3)
shape = np.unique(faceVertexCounts1)
if len(shape) > 1 :
print('non-uniform mesh')
return
if not shape[0] == 3:
print('Only works for triangle mesh')
return
bfrPlane = []
aftrPlane = []
others = []
pointsBfrPlane = np.array(points1[indiBfrPlane])
pointsAftrPlane = np.array(points1[indiAftrPlane])
for vertex in faceVertexIndices1:
easy_split = False
if len(np.intersect1d(vertex,indiBfrPlane)) == 3:
bfrPlane.append(vertex)
easy_split = True
if len(np.intersect1d(vertex,indiAftrPlane)) == 3:
aftrPlane.append(vertex)
easy_split = True
if not easy_split:
others.append(vertex)
for vIndi in others:
tri = points1[vIndi]
bfr = np.where(tri[:,PlaneAxis]<Plane)
aftr = np.where(tri[:,PlaneAxis]>Plane)
solo_bfr = (len(bfr[0])== 1)
if solo_bfr:
a = bfr[0][0]
else:
a = aftr[0][0]
b = (a+4)%3
c = (a+5)%3
dir_vector_d = tri[b]-tri[a]
dir_vector_e = tri[c]-tri[a]
cnst_d = (Plane - tri[a][PlaneAxis])/dir_vector_d[PlaneAxis]
cnst_e = (Plane - tri[a][PlaneAxis])/dir_vector_e[PlaneAxis]
point_d = tri[a] + (dir_vector_d*cnst_d)
point_e = tri[a] + (dir_vector_e*cnst_e)
pointsBfrPlane = np.append(pointsBfrPlane, [point_d])
pointsBfrPlane = np.append(pointsBfrPlane, [point_e])
pointsAftrPlane = np.append(pointsAftrPlane, [point_d])
pointsAftrPlane = np.append(pointsAftrPlane, [point_e])
max1 = np.max(np.array(bfrPlane).reshape(1,-1))
max2 = np.max(np.array(aftrPlane).reshape(1,-1))
if solo_bfr:
bfrPlane.append([vIndi[a],max1+1,max1+2])
aftrPlane.append([vIndi[b],vIndi[c],max2+1])
aftrPlane.append([vIndi[c],max2+2,max2+1])
else:
bfrPlane.append([vIndi[b],vIndi[c],max1+1])
bfrPlane.append([vIndi[c],max1+2,max1+1])
aftrPlane.append([vIndi[a],max2+1,max2+2])
uniq_bfr = np.sort(np.unique(np.array(bfrPlane).reshape(1,-1),return_index=False))
uniq_aftr = np.sort(np.unique(np.array(aftrPlane).reshape(1,-1),return_index=False))
nwIndiBfr = np.searchsorted(uniq_bfr,np.array(bfrPlane).reshape(1,-1))[0]
nwIndiAftr = np.searchsorted(uniq_aftr,np.array(aftrPlane).reshape(1,-1))[0]
mesh1 = UsdGeom.Mesh.Define(stage, '/Split_Mesh_1')
pointsBfrPlane = np.array(pointsBfrPlane).reshape(-1,3)
pointsAftrPlane = np.array(pointsAftrPlane).reshape(-1,3)
mesh1.CreatePointsAttr(pointsBfrPlane)
lnCntBfr = len(nwIndiBfr)/3
triCntsBfr = np.zeros(int(lnCntBfr)) + 3
print(len(pointsBfrPlane))
print(np.max(nwIndiBfr))
mesh1.CreateFaceVertexCountsAttr(triCntsBfr)
mesh1.CreateFaceVertexIndicesAttr(nwIndiBfr)
mesh2 = UsdGeom.Mesh.Define(stage, '/Split_Mesh_2')
mesh2.CreatePointsAttr(pointsAftrPlane)
lnCntAftr = len(nwIndiAftr)/3
print(len(pointsAftrPlane))
print(np.max(nwIndiAftr))
triCntsAftr = np.zeros(int(lnCntAftr)) + 3
mesh2.CreateFaceVertexCountsAttr(triCntsAftr)
mesh2.CreateFaceVertexIndicesAttr(nwIndiAftr)
def boundingbox(self):
stage = omni.usd.get_context().get_stage()
prim_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
if len(prim_paths) > 1:
return
if len(prim_paths) == 0:
return
print('fail')
for prim_path in prim_paths:
prim_mesh = stage.GetPrimAtPath(prim_path)
split_mesh = UsdGeom.Mesh(prim_mesh)
UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"]).Clear()
localBBox = UsdGeom.BBoxCache(Usd.TimeCode.Default(), ["default"]).ComputeWorldBound(prim_mesh)
bbox = Gf.BBox3d(localBBox).GetBox()
minbox = bbox.GetMin()
maxbox = bbox.GetMax()
return minbox, maxbox
def createplane(self,plane,planeValue,minbox1,maxbox1):
if plane == 0:
point0 = [planeValue,minbox1[1]-5,minbox1[2]-5]
point1 = [planeValue,minbox1[1]-5,maxbox1[2]+5]
point2 = [planeValue,maxbox1[1]+5,maxbox1[2]+5]
point3 = [planeValue,maxbox1[1]+5,minbox1[2]-5]
elif plane == 1:
point0 = [minbox1[0]-5,planeValue,minbox1[2]-5]
point1 = [minbox1[0]-5,planeValue,maxbox1[2]+5]
point2 = [maxbox1[0]+5,planeValue,maxbox1[2]+5]
point3 = [maxbox1[0]+5,planeValue,minbox1[2]-5]
else:
point0 = [minbox1[0]-5,minbox1[1]-5,planeValue]
point1 = [minbox1[0]-5,maxbox1[1]+5,planeValue]
point2 = [maxbox1[0]+5,maxbox1[1]+5,planeValue]
point3 = [maxbox1[0]+5,minbox1[1]-5,planeValue]
points = [point0,point1,point2,point3]
counts = [4]
indicies = [0,1,2,3]
stage = omni.usd.get_context().get_stage()
mesh_plane = UsdGeom.Mesh.Define(stage, '/temp_plane')
mesh_plane.CreatePointsAttr(points)
mesh_plane.CreateFaceVertexCountsAttr(counts)
mesh_plane.CreateFaceVertexIndicesAttr(indicies)
def modifyplane(self,plane,planeValue):
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath('/temp_plane')
mesh_plane = UsdGeom.Mesh(prim )
points = mesh_plane.GetPointsAttr().Get()
points = np.array(points)
changevalue = np.zeros(4) + planeValue
points[:,plane] = changevalue
counts = [4]
indicies = [0,1,2,3]
mesh_plane.CreatePointsAttr(points)
mesh_plane.CreateFaceVertexCountsAttr(counts)
mesh_plane.CreateFaceVertexIndicesAttr(indicies)
def delPlane(self):
omni.kit.commands.execute('DeletePrims', paths=['/temp_plane'],destructive=False)
| 7,530 | Python | 43.040935 | 107 | 0.563878 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/MeshTools/SplitTool.py | import omni.ext
import omni.ui as ui
from pxr import Usd, UsdGeom, Gf
import numpy as np
import omni.kit.app
import os
class Split_Tools:
def splitMesh(self):
stage = omni.usd.get_context().get_stage()
prim_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
for prim_path in prim_paths:
# Define a new Mesh primitive
prim_mesh = stage.GetPrimAtPath(prim_path)
split_mesh = UsdGeom.Mesh(prim_mesh)
faceVertexIndices1 = split_mesh.GetFaceVertexIndicesAttr().Get()
faceVertexCounts1 = split_mesh.GetFaceVertexCountsAttr().Get()
points1 = split_mesh.GetPointsAttr().Get()
meshshape = np.unique(faceVertexCounts1,return_index= False)
if len(meshshape) > 1:
print('non-uniform mesh')
return
faceVertexIndices1 = np.array(faceVertexIndices1)
faceVertexIndices1 = np.asarray(faceVertexIndices1.reshape(-1,meshshape[0]))
def splitmeshes(groups):
meshes = []
sorted_ref = []
flag = 0
for group in groups:
if not meshes:
meshes.append(group)
else:
notinlist = True
for i in range(0,len(meshes)):
if len(np.intersect1d(group.reshape(1,-1),meshes[i].reshape(1,-1))) > 0:
meshes[i] = np.concatenate([meshes[i],group])
notinlist = False
if notinlist:
meshes.append(group)
if len(meshes) == len(groups):
return [meshes, sorted_ref]
else:
return(splitmeshes(meshes))
meshsoutput , referceoutput = splitmeshes(faceVertexIndices1)
if len(meshsoutput) == 1:
print('Connex mesh: no actin taken')
return
i = 1
for meshoutput in meshsoutput:
uniqIndi = np.unique(meshoutput.reshape(1,-1),return_index=False)
uniqIndi = np.sort(uniqIndi)
points1 = np.asarray(points1)
meshpoints = np.array(points1[uniqIndi])
connexMeshIndi_adjsuted = np.searchsorted(uniqIndi,meshoutput.reshape(1,-1))[0]
counts = np.zeros(int(len(meshoutput)/3)) + meshshape
mesh = UsdGeom.Mesh.Define(stage, f'/NewMesh_{i}')
# Define the points of the mesh
mesh.CreatePointsAttr(meshpoints)
# Define the faces of the mesh
mesh.CreateFaceVertexCountsAttr(counts)
mesh.CreateFaceVertexIndicesAttr(connexMeshIndi_adjsuted)
i = i+1
next
| 2,973 | Python | 37.623376 | 100 | 0.51665 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/MeshTools/extension.py | import omni.ext
import omni.ui as ui
from pxr import Usd, UsdGeom, Gf
import numpy as np
import omni.kit.app
import os
from .MeshTools_Window import MeshToolsWindow
ext_path = os.path.dirname(os.path.realpath(__file__))
# Functions and vars are available to other extension as usual in python: `example.python_ext.some_public_function(x)`
def some_public_function(x: int):
print("[MeshTools] some_public_function was called with x: ", x)
return x ** x
# Any class derived from `omni.ext.IExt` in top level module (defined in `python.modules` of `extension.toml`) will be
# instantiated when extension gets enabled and `on_startup(ext_id)` will be called. Later when extension gets disabled
# on_shutdown() is called.
class MeshtoolsExtension(omni.ext.IExt):
# ext_id is current extension id. It can be used with extension manager to query additional information, like where
# this extension is located on filesystem.
def on_startup(self, ext_id):
print("[MeshTools] MeshTools startup")
self.MeshToolsWindow = MeshToolsWindow()
self.MeshToolsWindow.on_startup(ext_id)
def on_shutdown(self):
print("[MeshTools] MeshTools shutdown")
| 1,229 | Python | 28.999999 | 119 | 0.711147 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/MeshTools/MergeMesh.py | import omni.ext
import omni.ui as ui
from pxr import Usd, UsdGeom, Gf
import numpy as np
import omni.kit.app
import omni.kit.commands
import os
class mergeMesh:
def merge_mesh(self):
stage = omni.usd.get_context().get_stage()
prim_paths = omni.usd.get_context().get_selection().get_selected_prim_paths()
faceVertexCounts2 = np.array([])
faceVertexIndices2 = np.array([])
points2 = np.array([])
for prim_path in prim_paths:
# Define a new Mesh primitive
prim_mesh = stage.GetPrimAtPath(prim_path)
split_mesh = UsdGeom.Mesh(prim_mesh)
faceVertexIndices1 = np.array(split_mesh.GetFaceVertexIndicesAttr().Get())
faceVertexCounts1 = np.array(split_mesh.GetFaceVertexCountsAttr().Get())
points1 = np.array(split_mesh.GetPointsAttr().Get())
if not len(faceVertexIndices2) == 0:
faceVertexIndices1 =faceVertexIndices1 +np.max(faceVertexIndices2) +1
faceVertexIndices2 = np.append(faceVertexIndices2,faceVertexIndices1)
points2 = np.append(points2,points1)
faceVertexCounts2 = np.append(faceVertexCounts2,faceVertexCounts1)
combinedMesh = UsdGeom.Mesh.Define(stage,'/combinedMesh')
combinedMesh.CreatePointsAttr(points2)
combinedMesh.CreateFaceVertexIndicesAttr(faceVertexIndices2)
combinedMesh.CreateFaceVertexCountsAttr(faceVertexCounts2)
| 1,484 | Python | 39.135134 | 86 | 0.66779 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/MeshTools/MeshTools_Window.py | import omni.ext
import omni.ui as ui
from pxr import Usd, UsdGeom, Gf
import numpy as np
import omni.kit.app
import os
ext_path = os.path.dirname(os.path.realpath(__file__))
from .SplitTool import Split_Tools
from .SliceTool import Slice_Tools
from .MergeMesh import mergeMesh
Split_Tools = Split_Tools()
Slice_Tools = Slice_Tools()
mergeMesh = mergeMesh()
class MeshToolsWindow:
def on_startup(self,ext_id):
def button1_clicked():
Split_Tools.splitMesh()
def button2_clicked():
plane = sliderInt.model.as_int
planeValue = fieldFloat.model.as_int
Slice_Tools.sliceMesh(plane,planeValue)
Slice_Tools.delPlane()
def button_merge():
mergeMesh.merge_mesh()
def button3_clicked():
minBBox, maxBBox = Slice_Tools.boundingbox()
plane = sliderInt.model.as_int
sliderFloat.min = minBBox[plane]
sliderFloat.max = maxBBox[plane]
planeValue = fieldFloat.model.as_int
Slice_Tools.createplane(plane,planeValue,minBBox,maxBBox)
def planechange():
plane = sliderInt.model.as_int
planeValue = fieldFloat.model.as_int
Slice_Tools.modifyplane(plane,planeValue)
def deleteplane():
Slice_Tools.delPlane()
self._window = ui.Window("My Window", width=300, height=500)
with self._window.frame:
with ui.VStack(height = 0):
with ui.CollapsableFrame("split and merge mesh"):
with ui.HStack():
ui.Button("Split Mesh",image_url =f'{ext_path}/Imgs/Split_Meshes.PNG', image_height = 140 ,width = 140, clicked_fn = button1_clicked)
ui.Button("Merge Mesh",image_url =f'{ext_path}/Imgs/Merge.PNG', image_height = 140 ,width = 140 , clicked_fn = button_merge)
with ui.CollapsableFrame("Slice mesh with plane"):
with ui.VStack(height = 0):
ui.Label("| YZ : 0 | ZX : 1 | XY : 2 |")
with ui.HStack():
sliderInt = ui.IntSlider(min=0,max = 2)
ui.Button("Start",width = 80, height = 30 , clicked_fn = button3_clicked )
sliderInt.tooltip = "For slicing plane give 0 for YZ plane, 1 for ZX, 2 for XY"
with ui.HStack():
fieldFloat = ui.StringField(width = 50)
sliderFloat = ui.FloatSlider(min=0,max=50)
sliderFloat.model = fieldFloat.model
sliderFloat.model.add_value_changed_fn(lambda m:planechange())
with ui.HStack():
ui.Button("Slice Mesh",image_url =f'{ext_path}/Imgs/Slicing_Mesh.PNG', image_height = 140 ,width = 140,clicked_fn = button2_clicked)
ui.Button('Delete Plane',image_url =f'{ext_path}/Imgs/Delete.PNG', image_height = 140 ,width = 140,clicked_fn = deleteplane)
| 3,079 | Python | 44.970149 | 161 | 0.566742 |
Prudhvi-Tummala/PrudhviTummala.MeshEditor.MeshTools/exts/MeshTools/docs/README.md | # Python Extension [MeshTools]
MeshTools Extension contains tools to split, slice and merge meshes
note: data like normals and other porperites of mesh will lost in output data. If your use case require those data to be considerd you have to modify code
| 256 | Markdown | 41.833326 | 154 | 0.800781 |
fnuabhimanyu8713/orbit/source/extensions/omni.isaac.orbit_assets/omni/isaac/orbit_assets/monaV2.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Configuration for the ANYbotics robots.
The following configuration parameters are available:
* :obj:`ANYMAL_B_CFG`: The ANYmal-B robot with ANYdrives 3.0
* :obj:`ANYMAL_C_CFG`: The ANYmal-C robot with ANYdrives 3.0
* :obj:`ANYMAL_D_CFG`: The ANYmal-D robot with ANYdrives 3.0
Reference:
* https://github.com/ANYbotics/anymal_b_simple_description
* https://github.com/ANYbotics/anymal_c_simple_description
* https://github.com/ANYbotics/anymal_d_simple_description
"""
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.actuators import ActuatorNetLSTMCfg, DCMotorCfg
from omni.isaac.orbit.assets.articulation import ArticulationCfg
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR
##
# Configuration - Actuators.
##
MONAV2_LEG_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["HpR","HpL",
"HrR","HrL",
"HwR","HwL",
"ApR","ApL",
"ArR","ArL",
"KpR","KpL",],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
MONAV2_ARM_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["SpR","SpL",
"SrR","SrL",
"SwR","SwL",
"WpR","WpL",
"WrR","WrL",
"WwR","WwL"],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
MONAV2_TORSO_SIMPLE_ACTUATOR_CFG = DCMotorCfg(
joint_names_expr=["FpC", "FrC", "FwC"],
saturation_effort=120.0,
effort_limit=80.0,
velocity_limit=7.5,
stiffness={".*": 40.0},
damping={".*": 5.0},
)
"""Configuration for ANYdrive 3.x with DC actuator model."""
##
# Configuration - Articulation.
##
MONAV2_CFG = ArticulationCfg(
spawn=sim_utils.UsdFileCfg(
usd_path="/home/fnuabhimanyu/WholeBodyMotion/assets/hoa_full_body1/full_body1/URDF_description/meshes/mona_v2_simple/mona_v2_simple.usd",
activate_contact_sensors=False,
rigid_props=sim_utils.RigidBodyPropertiesCfg(
disable_gravity=False,
retain_accelerations=False,
linear_damping=0.0,
angular_damping=0.0,
max_linear_velocity=10.0,
max_angular_velocity=10.0,
max_depenetration_velocity=1.0,
),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
enabled_self_collisions=True, solver_position_iteration_count=4, solver_velocity_iteration_count=0
),
# collision_props=sim_utils.CollisionPropertiesCfg(contact_offset=0.02, rest_offset=0.0),
),
init_state=ArticulationCfg.InitialStateCfg(
pos=(0.0, 0.0, 0.923),
joint_pos={
"SpR": -0.5,
"SpL": 0.5 # all motors
},
),
actuators={"legs": MONAV2_LEG_SIMPLE_ACTUATOR_CFG,
"arms": MONAV2_ARM_SIMPLE_ACTUATOR_CFG,
"torso": MONAV2_TORSO_SIMPLE_ACTUATOR_CFG,},
soft_joint_pos_limit_factor=0.95,
)
| 3,243 | Python | 30.192307 | 145 | 0.608696 |
fnuabhimanyu8713/orbit/source/standalone/tutorials/03_envs/create_monav2_base_env.py | # Copyright (c) 2022-2024, The ORBIT Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""
This script demonstrates the environment for a quadruped robot with height-scan sensor.
In this example, we use a locomotion policy to control the robot. The robot is commanded to
move forward at a constant velocity. The height-scan sensor is used to detect the height of
the terrain.
.. code-block:: bash
# Run the script
./orbit.sh -p source/standalone/tutorials/04_envs/quadruped_base_env.py --num_envs 32
"""
"""Launch Isaac Sim Simulator first."""
import argparse
from omni.isaac.orbit.app import AppLauncher
# add argparse arguments
parser = argparse.ArgumentParser(description="Tutorial on creating a quadruped base environment.")
parser.add_argument("--num_envs", type=int, default=64, help="Number of environments to spawn.")
# append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
# parse the arguments
args_cli = parser.parse_args()
# launch omniverse app
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
"""Rest everything follows."""
import os
import torch
import omni.isaac.orbit.envs.mdp as mdp
import omni.isaac.orbit.sim as sim_utils
from omni.isaac.orbit.assets import ArticulationCfg, AssetBaseCfg
from omni.isaac.orbit.envs import BaseEnv, BaseEnvCfg
from omni.isaac.orbit.managers import EventTermCfg as EventTerm
from omni.isaac.orbit.managers import ObservationGroupCfg as ObsGroup
from omni.isaac.orbit.managers import ObservationTermCfg as ObsTerm
from omni.isaac.orbit.managers import SceneEntityCfg
from omni.isaac.orbit.scene import InteractiveSceneCfg
from omni.isaac.orbit.sensors import RayCasterCfg, patterns
from omni.isaac.orbit.terrains import TerrainImporterCfg
from omni.isaac.orbit.utils import configclass
from omni.isaac.orbit.utils.assets import ISAAC_ORBIT_NUCLEUS_DIR, check_file_path, read_file
from omni.isaac.orbit.utils.noise import AdditiveUniformNoiseCfg as Unoise
##
# Pre-defined configs
##
from omni.isaac.orbit.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip
# from omni.isaac.orbit_assets.anymal import ANYMAL_C_CFG # isort: skip
from omni.isaac.orbit_assets.monaV2 import MONAV2_CFG # isort: skip
##
# Custom observation terms
##
def constant_commands(env: BaseEnv) -> torch.Tensor:
"""The generated command from the command generator."""
return torch.tensor([[1, 0, 0]], device=env.device).repeat(env.num_envs, 1)
##
# Scene definition
##
@configclass
class MySceneCfg(InteractiveSceneCfg):
"""Example scene configuration."""
# add terrain
# ground plane
terrain = AssetBaseCfg(prim_path="/World/ground", spawn=sim_utils.GroundPlaneCfg())
# add robot
robot: ArticulationCfg = MONAV2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# lights
light = AssetBaseCfg(
prim_path="/World/light",
spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0),
)
##
# MDP settings
##
@configclass
class ActionsCfg:
"""Action specifications for the MDP."""
joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=1.0, use_default_offset=True)
@configclass
class ObservationsCfg:
"""Observation specifications for the MDP."""
@configclass
class PolicyCfg(ObsGroup):
"""Observations for policy group."""
# observation terms (order preserved)
base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1))
base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2))
projected_gravity = ObsTerm(
func=mdp.projected_gravity,
noise=Unoise(n_min=-0.05, n_max=0.05),
)
velocity_commands = ObsTerm(func=constant_commands)
joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01))
joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5))
actions = ObsTerm(func=mdp.last_action)
def __post_init__(self):
self.enable_corruption = True
self.concatenate_terms = True
# observation groups
policy: PolicyCfg = PolicyCfg()
@configclass
class EventCfg:
"""Configuration for events."""
reset_scene = EventTerm(func=mdp.reset_scene_to_default, mode="reset")
##
# Environment configuration
##
@configclass
class MonaV2EnvCfg(BaseEnvCfg):
"""Configuration for the locomotion velocity-tracking environment."""
# Scene settings
scene: MySceneCfg = MySceneCfg(num_envs=args_cli.num_envs, env_spacing=5.0)
# Basic settings
observations: ObservationsCfg = ObservationsCfg()
actions: ActionsCfg = ActionsCfg()
events: EventCfg = EventCfg()
def __post_init__(self):
"""Post initialization."""
# general settings
self.decimation = 4 # env decimation -> 50 Hz control
# simulation settings
self.sim.dt = 0.005 # simulation timestep -> 200 Hz physics
# self.sim.physics_material = self.scene.terrain.physics_material
def PID(obs):
"""PID controller."""
# get current orientation
joint_pos = obs["policy"][0][12:41]
# desired orientation
desired_joint_pos = joint_pos
return 0.1*(desired_joint_pos - joint_pos)
def main():
"""Main function."""
# setup base environment
env_cfg = MonaV2EnvCfg()
env = BaseEnv(cfg=env_cfg)
# simulate physics
count = 0
obs, _ = env.reset()
while simulation_app.is_running():
with torch.inference_mode():
# reset
if count % 300 == 0:
count = 0
env.reset()
print("-" * 80)
print("[INFO]: Resetting environment...")
# sample random actions
# joint_efforts = torch.randn_like(env.action_manager.action)*0
joint_efforts = PID(obs)
joint_efforts = joint_efforts.unsqueeze(0)
# step the environment
obs, _ = env.step(joint_efforts)
print(joint_efforts)
# print current orientation of pole
# update counter
count += 1
if __name__ == "__main__":
# run the main function
main()
# close sim app
simulation_app.close()
| 6,326 | Python | 28.427907 | 118 | 0.680051 |
fnuabhimanyu8713/orbit/assets/hoa_full_body1/full_body1/URDF_description/launch/controller.yaml | URDF_controller:
# Publish all joint states -----------------------------------
joint_state_controller:
type: joint_state_controller/JointStateController
publish_rate: 50
# Position Controllers --------------------------------------
Revolute 2_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 2
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 3_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 3
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 4_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 4
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 5_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 5
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 6_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 6
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 7_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 7
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 8_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 8
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 9_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 9
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 10_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 10
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 11_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 11
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 14_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 14
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 17_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 17
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 20_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 20
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 21_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 21
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 22_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 22
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 23_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 23
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 24_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 24
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 25_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 25
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 26_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 26
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 27_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 27
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 28_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 28
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 29_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 29
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 30_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 30
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 31_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 31
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 32_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 32
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 33_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 33
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 34_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 34
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 35_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 35
pid: {p: 100.0, i: 0.01, d: 10.0}
Revolute 36_position_controller:
type: effort_controllers/JointPositionController
joint: Revolute 36
pid: {p: 100.0, i: 0.01, d: 10.0}
| 4,553 | YAML | 35.725806 | 64 | 0.681309 |
fnuabhimanyu8713/orbit/assets/hoa_full_body1/full_body1/URDF_description/meshes (copy)/mona_v2.xml | <mujoco model="URDF">
<compiler angle="radian"/>
<asset>
<mesh name="base_link" file="base_link.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sp2rR_fork_v6_1" file="shell_Sp2rR_fork_v6_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sr2wR_fork_v14_1" file="shell_Sr2wR_fork_v14_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Humerus_Fork_v8_1" file="shell_Humerus_Fork_v8_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ulna_Fork_v5_1" file="shell_Ulna_Fork_v5_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Radius_gen2_v31_1" file="shell_Radius_gen2_v31_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sp2rR_fork_v6_Mirror__1" file="shell_Sp2rR_fork_v6_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Sr2wR_fork_v14_Mirror__1" file="shell_Sr2wR_fork_v14_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Humerus_Fork_v8_Mirror__1" file="shell_Humerus_Fork_v8_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ulna_Fork_v5_Mirror__1" file="shell_Ulna_Fork_v5_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Radius_gen2_v31_Mirror__1" file="shell_Radius_gen2_v31_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="hand_secondIter_v9_Mirror__1" file="hand_secondIter_v9_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="hand_secondIter_v9_1" file="hand_secondIter_v9_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Fr2w_Fork_v6_1" file="shell_Fr2w_Fork_v6_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Fp2r_Fork_dual_v3_1" file="shell_Fp2r_Fork_dual_v3_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_torso_1" file="shell_torso_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="scaphoid_1" file="scaphoid_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="scaphoid_Mirror__1" file="scaphoid_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hp2r_Fork_v9_1" file="shell_Hp2r_Fork_v9_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hr2w_Fork_v16_1" file="shell_Hr2w_Fork_v16_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Femur_fork_v4_1" file="shell_Femur_fork_v4_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Tibia_Alt_fork_v12_1" file="shell_Tibia_Alt_fork_v12_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ap2r_v5_1" file="shell_Ap2r_v5_1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_foot_v16_Mirror__1" file="shell_foot_v16_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hp2r_Fork_v9_Mirror__1" file="shell_Hp2r_Fork_v9_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Hr2w_Fork_v16_Mirror__1" file="shell_Hr2w_Fork_v16_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Femur_fork_v4_Mirror__1" file="shell_Femur_fork_v4_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Tibia_Alt_fork_v12_Mirror__1" file="shell_Tibia_Alt_fork_v12_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_Ap2r_v5_Mirror__1" file="shell_Ap2r_v5_Mirror__1.stl" scale="0.001 0.001 0.001"/>
<mesh name="shell_foot_v16_1" file="shell_foot_v16_1.stl" scale="0.001 0.001 0.001"/>
</asset>
<worldbody>
<geom type="mesh" rgba="0.7 0.7 0.7 1" mesh="base_link"/>
<body name="shell_Fr2w_Fork_v6_1" pos="0 0 0.08448">
<inertial pos="-0.0134037 -1.28947e-07 0.0897088" quat="0.410834 0.575513 0.575513 0.410834" mass="1.64424" diaginertia="0.011252 0.00887014 0.00594086"/>
<joint name="Revolute 20" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 0 -0.08448" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Fr2w_Fork_v6_1"/>
<body name="shell_Fp2r_Fork_dual_v3_1" pos="0.0305 0 0.1522">
<inertial pos="-0.000954547 -0.00417876 6.73482e-08" quat="0.482905 0.482905 0.516529 0.516529" mass="0.146163" diaginertia="0.000454606 0.000433 0.000320394"/>
<joint name="Revolute 21" pos="0 0 0" axis="1 0 0" range="-0.628319 0.628319" actuatorfrcrange="-100 100"/>
<geom pos="-0.0305 0 -0.23668" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Fp2r_Fork_dual_v3_1"/>
<body name="shell_torso_1" pos="0.000874 0 0">
<inertial pos="-0.0319595 5.80206e-07 0.208297" quat="0.999281 0 -0.0379211 0" mass="5.20486" diaginertia="0.112904 0.094706 0.0563995"/>
<joint name="Revolute 22" pos="0 0 0" axis="0 1 0" range="-0.287979 0.907571" actuatorfrcrange="-100 100"/>
<geom pos="-0.031374 0 -0.23668" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_torso_1"/>
<body name="shell_Sp2rR_fork_v6_1" pos="-0.032 -0.1279 0.3292">
<inertial pos="0.00210198 -0.0643948 6.20677e-07" quat="0.706978 0.706978 0.0134708 0.0134708" mass="0.750073" diaginertia="0.00212818 0.001773 0.00131382"/>
<joint name="Revolute 2" pos="0 0 0" axis="0 1 0" range="-3.14159 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000626 0.1279 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sp2rR_fork_v6_1"/>
<body name="shell_Sr2wR_fork_v14_1" pos="0.00102 -0.08839 0">
<inertial pos="-0.00676748 0.000476725 -0.0637433" quat="0.699228 -0.101201 -0.105312 0.69982" mass="0.978546" diaginertia="0.00437906 0.00352726 0.00260168"/>
<joint name="Revolute 3" pos="0 0 0" axis="1 0 0" range="-2.26893 0.174533" actuatorfrcrange="-100 100"/>
<geom pos="-0.000394 0.21629 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sr2wR_fork_v14_1"/>
<body name="shell_Humerus_Fork_v8_1" pos="-0.00105 0 -0.146483">
<inertial pos="-0.00349646 0.00263963 -0.104404" quat="0.705069 0.00551324 -0.011204 0.709029" mass="0.876673" diaginertia="0.00397843 0.00370214 0.00144144"/>
<joint name="Revolute 4" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21629 -0.419397" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Humerus_Fork_v8_1"/>
<body name="shell_Ulna_Fork_v5_1" pos="0 0.00077 -0.15139">
<inertial pos="9.62901e-06 -0.00344448 -0.0452394" quat="0.913229 0.407446 0 0" mass="0.698159" diaginertia="0.002413 0.00185007 0.00165493"/>
<joint name="Revolute 5" pos="0 0 0" axis="0 1 0" range="-2.26893 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21552 -0.268007" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ulna_Fork_v5_1"/>
<body name="shell_Radius_gen2_v31_1" pos="0 -0.00095 -0.100482">
<inertial pos="9.37117e-06 -0.00117845 -0.124991" quat="0.999951 -0.00993344 0 0" mass="0.876922" diaginertia="0.003786 0.00344577 0.00148223"/>
<joint name="Revolute 6" pos="0 0 0" axis="0 0 1" range="-3.14159 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 0.21647 -0.167525" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Radius_gen2_v31_1"/>
<body name="scaphoid_1" pos="6.5e-05 0 -0.207787">
<inertial pos="-1.58999e-07 -1.3481e-08 4.05809e-07" quat="0.5 0.5 -0.5 0.5" mass="0.0259174" diaginertia="7e-06 4e-06 4e-06"/>
<joint name="Revolute 23" pos="0 0 0" axis="0 1 0" range="-0.523599 0.523599" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 0.21647 0.040262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="scaphoid_1"/>
<body name="hand_secondIter_v9_Mirror__1">
<inertial pos="-0.00343585 0.00506416 -0.0641579" quat="0.978592 -0.031701 0.00787655 0.203201" mass="0.340548" diaginertia="0.00134431 0.00105859 0.0004321"/>
<joint name="Revolute 14" pos="0 0 0" axis="1 0 0" range="-0.698132 0.349066" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 0.21647 0.040262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="hand_secondIter_v9_Mirror__1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Sp2rR_fork_v6_Mirror__1" pos="-0.032 0.1279 0.3292">
<inertial pos="0.00210198 0.0643948 6.20677e-07" quat="0.706978 0.706978 -0.0134708 -0.0134708" mass="0.750073" diaginertia="0.00212818 0.001773 0.00131382"/>
<joint name="Revolute 7" pos="0 0 0" axis="0 1 0" range="-3.14159 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000626 -0.1279 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sp2rR_fork_v6_Mirror__1"/>
<body name="shell_Sr2wR_fork_v14_Mirror__1" pos="0.00102 0.08839 0">
<inertial pos="-0.00676748 -0.000476725 -0.0637433" quat="0.69982 -0.105312 -0.101201 0.699228" mass="0.978546" diaginertia="0.00437906 0.00352726 0.00260168"/>
<joint name="Revolute 8" pos="0 0 0" axis="1 0 0" range="-0.174533 2.26893" actuatorfrcrange="-100 100"/>
<geom pos="-0.000394 -0.21629 -0.56588" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Sr2wR_fork_v14_Mirror__1"/>
<body name="shell_Humerus_Fork_v8_Mirror__1" pos="-0.00105 0 -0.146483">
<inertial pos="-0.00349646 -0.00263963 -0.104404" quat="0.709029 -0.011204 0.00551324 0.705069" mass="0.876673" diaginertia="0.00397843 0.00370214 0.00144144"/>
<joint name="Revolute 9" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21629 -0.419397" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Humerus_Fork_v8_Mirror__1"/>
<body name="shell_Ulna_Fork_v5_Mirror__1" pos="0 -0.00077 -0.15139">
<inertial pos="9.62901e-06 0.00344448 -0.0452394" quat="0.407446 0.913229 0 0" mass="0.698159" diaginertia="0.002413 0.00185007 0.00165493"/>
<joint name="Revolute 10" pos="0 0 0" axis="0 1 0" range="-2.26893 0" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21552 -0.268007" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ulna_Fork_v5_Mirror__1"/>
<body name="shell_Radius_gen2_v31_Mirror__1" pos="0 0.00095 -0.100482">
<inertial pos="9.35442e-06 0.00117859 -0.123991" quat="0.999951 0.00993344 0 0" mass="0.87692" diaginertia="0.003786 0.00344577 0.00148223"/>
<joint name="Revolute 11" pos="0 0 0" axis="0 0 1" range="0 3.14159" actuatorfrcrange="-100 100"/>
<geom pos="0.000656 -0.21647 -0.167525" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Radius_gen2_v31_Mirror__1"/>
<body name="scaphoid_Mirror__1" pos="6.5e-05 0 -0.206787">
<inertial pos="-1.58999e-07 1.3481e-08 4.05809e-07" quat="0.5 0.5 -0.5 0.5" mass="0.0259174" diaginertia="7e-06 4e-06 4e-06"/>
<joint name="Revolute 24" pos="0 0 0" axis="0 1 0" range="-0.523599 0.523599" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 -0.21647 0.039262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="scaphoid_Mirror__1"/>
<body name="hand_secondIter_v9_1">
<inertial pos="-0.00343586 -0.00506416 -0.0641579" quat="0.978592 0.031701 0.00787655 -0.203201" mass="0.340548" diaginertia="0.00134431 0.00105859 0.0004321"/>
<joint name="Revolute 17" pos="0 0 0" axis="1 0 0" range="-0.349066 0.698132" actuatorfrcrange="-100 100"/>
<geom pos="0.000591 -0.21647 0.039262" type="mesh" rgba="0.7 0.7 0.7 1" mesh="hand_secondIter_v9_1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Hp2r_Fork_v9_1" pos="0 -0.07805 0">
<inertial pos="-0.0141996 -0.0485335 3.44054e-05" quat="0.485909 0.487111 0.512789 0.513481" mass="0.966865" diaginertia="0.00338981 0.002866 0.00275019"/>
<joint name="Revolute 25" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 0.07805 0" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hp2r_Fork_v9_1"/>
<body name="shell_Hr2w_Fork_v16_1" pos="-0.006681 -0.063408 0.0001">
<inertial pos="-0.00952234 -0.00116999 -0.1034" quat="0.715613 -0.10037 -0.111741 0.682157" mass="1.46012" diaginertia="0.0123951 0.00880392 0.00647794"/>
<joint name="Revolute 26" pos="0 0 0" axis="1 0 0" range="-1.5708 0.610865" actuatorfrcrange="-100 100"/>
<geom pos="0.006681 0.141458 -0.0001" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hr2w_Fork_v16_1"/>
<body name="shell_Femur_fork_v4_1" pos="0.0059 0 -0.21643">
<inertial pos="0.00550338 0.0121435 -0.147595" quat="0.715678 0.0344328 -0.0145762 0.697428" mass="1.55467" diaginertia="0.0114351 0.0100695 0.0039594"/>
<joint name="Revolute 27" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.141458 0.21633" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Femur_fork_v4_1"/>
<body name="shell_Tibia_Alt_fork_v12_1" pos="0 0.011525 -0.20343">
<inertial pos="0.0049156 -0.0471964 -0.179273" quat="0.996568 -0.0697109 -0.00247143 -0.0445611" mass="2.28598" diaginertia="0.0449954 0.0441979 0.0066517"/>
<joint name="Revolute 28" pos="0 0 0" axis="0 1 0" range="0 2.61799" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.129933 0.41976" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Tibia_Alt_fork_v12_1"/>
<body name="shell_Ap2r_v5_1" pos="0 -0.0554 -0.4101">
<inertial pos="0.01075 0.0488861 7.92256e-07" quat="0.498939 0.498939 0.501059 0.501059" mass="0.854091" diaginertia="0.00330603 0.002482 0.00189097"/>
<joint name="Revolute 29" pos="0 0 0" axis="0 1 0" range="-0.785398 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 0.185333 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ap2r_v5_1"/>
<body name="shell_foot_v16_Mirror__1" pos="0.07781 0.0443 0">
<inertial pos="0.00978994 -0.00464532 -0.0467468" quat="0.739197 0.273168 0.456071 0.413481" mass="0.823883" diaginertia="0.00361388 0.00342654 0.00167958"/>
<joint name="Revolute 30" pos="0 0 0" axis="1 0 0" range="0 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="-0.077029 0.141033 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_foot_v16_Mirror__1"/>
</body>
</body>
</body>
</body>
</body>
</body>
<body name="shell_Hp2r_Fork_v9_Mirror__1" pos="0 0.07805 0">
<inertial pos="-0.0141987 0.0485343 3.38956e-05" quat="0.513481 0.512789 0.487111 0.485909" mass="0.96689" diaginertia="0.00338981 0.002866 0.00275019"/>
<joint name="Revolute 31" pos="0 0 0" axis="0 1 0" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0 -0.07805 0" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hp2r_Fork_v9_Mirror__1"/>
<body name="shell_Hr2w_Fork_v16_Mirror__1" pos="-0.006681 0.063408 0.0001">
<inertial pos="-0.00952234 0.00116999 -0.1034" quat="0.682157 -0.111741 -0.10037 0.715613" mass="1.46012" diaginertia="0.0123951 0.00880392 0.00647794"/>
<joint name="Revolute 32" pos="0 0 0" axis="1 0 0" range="-0.610865 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.006681 -0.141458 -0.0001" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Hr2w_Fork_v16_Mirror__1"/>
<body name="shell_Femur_fork_v4_Mirror__1" pos="0.0059 0 -0.21643">
<inertial pos="0.00550338 -0.0121435 -0.147595" quat="0.697428 -0.0145762 0.0344328 0.715678" mass="1.55467" diaginertia="0.0114351 0.0100695 0.0039594"/>
<joint name="Revolute 33" pos="0 0 0" axis="0 0 1" range="-1.5708 1.5708" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.141458 0.21633" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Femur_fork_v4_Mirror__1"/>
<body name="shell_Tibia_Alt_fork_v12_Mirror__1" pos="0 -0.011525 -0.20343">
<inertial pos="0.0049156 0.0471964 -0.179273" quat="0.996568 0.0697109 -0.00247143 0.0445611" mass="2.28598" diaginertia="0.0449954 0.0441979 0.0066517"/>
<joint name="Revolute 34" pos="0 0 0" axis="0 1 0" range="0 2.61799" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.129933 0.41976" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Tibia_Alt_fork_v12_Mirror__1"/>
<body name="shell_Ap2r_v5_Mirror__1" pos="0 0.0554 -0.4101">
<inertial pos="0.01075 -0.0488861 7.92256e-07" quat="0.501059 0.501059 0.498939 0.498939" mass="0.854091" diaginertia="0.00330603 0.002482 0.00189097"/>
<joint name="Revolute 35" pos="0 0 0" axis="0 1 0" range="-0.785398 0.785398" actuatorfrcrange="-100 100"/>
<geom pos="0.000781 -0.185333 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_Ap2r_v5_Mirror__1"/>
<body name="shell_foot_v16_1" pos="0.07781 -0.0443 0">
<inertial pos="0.0117899 0.00464532 -0.0467468" quat="0.413481 0.456071 0.273168 0.739197" mass="0.823883" diaginertia="0.00361388 0.00342654 0.00167958"/>
<joint name="Revolute 36" pos="0 0 0" axis="1 0 0" range="-0.785398 0" actuatorfrcrange="-100 100"/>
<geom pos="-0.077029 -0.141033 0.82986" type="mesh" rgba="0.7 0.7 0.7 1" mesh="shell_foot_v16_1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</worldbody>
<actuator>
<motor name="Revolute 2" gear="40" joint="Revolute 2"/>
<motor name="Revolute 3" gear="40" joint="Revolute 3"/>
<motor name="Revolute 4" gear="40" joint="Revolute 4"/>
<motor name="Revolute 5" gear="40" joint="Revolute 5"/>
<motor name="Revolute 6" gear="40" joint="Revolute 6"/>
<motor name="Revolute 7" gear="40" joint="Revolute 7"/>
<motor name="Revolute 8" gear="40" joint="Revolute 8"/>
<motor name="Revolute 9" gear="40" joint="Revolute 9"/>
<motor name="Revolute 10" gear="40" joint="Revolute 10"/>
<motor name="Revolute 11" gear="40" joint="Revolute 11"/>
<motor name="Revolute 14" gear="40" joint="Revolute 14"/>
<motor name="Revolute 17" gear="40" joint="Revolute 17"/>
<motor name="Revolute 20" gear="40" joint="Revolute 20"/>
<motor name="Revolute 21" gear="40" joint="Revolute 21"/>
<motor name="Revolute 22" gear="40" joint="Revolute 22"/>
<motor name="Revolute 23" gear="40" joint="Revolute 23"/>
<motor name="Revolute 24" gear="40" joint="Revolute 24"/>
<motor name="Revolute 25" gear="40" joint="Revolute 25"/>
<motor name="Revolute 26" gear="40" joint="Revolute 26"/>
<motor name="Revolute 27" gear="40" joint="Revolute 27"/>
<motor name="Revolute 28" gear="40" joint="Revolute 28"/>
<motor name="Revolute 29" gear="40" joint="Revolute 29"/>
<motor name="Revolute 30" gear="40" joint="Revolute 30"/>
<motor name="Revolute 31" gear="40" joint="Revolute 31"/>
<motor name="Revolute 32" gear="40" joint="Revolute 32"/>
<motor name="Revolute 33" gear="40" joint="Revolute 33"/>
<motor name="Revolute 34" gear="40" joint="Revolute 34"/>
<motor name="Revolute 35" gear="40" joint="Revolute 35"/>
<motor name="Revolute 36" gear="40" joint="Revolute 36"/>
</actuator>
</mujoco>
| 19,658 | XML | 89.178899 | 184 | 0.602452 |
edgeimpulse/edge-impulse-omniverse-ext/README.md | # Edge Impulse Data Ingestion Omniverse Extension
This Omniverse extension allows you to upload your synthetic datasets to your Edge Impulse project for computer vision tasks, validate your trained model locally, and view inferencing results directly in your Omniverse synthetic environment.

# Extension Project Template
This project was automatically generated.
- `app` - It is a folder link to the location of your *Omniverse Kit* based app.
- `exts` - It is a folder where you can add new extensions. It was automatically added to extension search path. (Extension Manager -> Gear Icon -> Extension Search Path).
Open this folder using Visual Studio Code. It will suggest you to install few extensions that will make python experience better.
Look for "edgeimpulse.dataingestion" extension in extension manager and enable it. Try applying changes to any python files, it will hot-reload and you can observe results immediately.
Alternatively, you can launch your app from console with this folder added to search path and your extension enabled, e.g.:
```
> app\omni.code.bat --ext-folder exts --enable edgeimpulse.dataingestion
```
# App Link Setup
If `app` folder link doesn't exist or broken it can be created again. For better developer experience it is recommended to create a folder link named `app` to the *Omniverse Kit* app installed from *Omniverse Launcher*. Convenience script to use is included.
Run:
```
> link_app.bat
```
If successful you should see `app` folder link in the root of this repo.
If multiple Omniverse apps is installed script will select recommended one. Or you can explicitly pass an app:
```
> link_app.bat --app create
```
You can also just pass a path to create link to:
```
> link_app.bat --path "C:/Users/bob/AppData/Local/ov/pkg/create-2021.3.4"
```
# Sharing Your Extensions
This folder is ready to be pushed to any git repository. Once pushed direct link to a git repository can be added to *Omniverse Kit* extension search paths.
Link might look like this: `git://github.com/[user]/[your_repo].git?branch=main&dir=exts`
Notice `exts` is repo subfolder with extensions. More information can be found in "Git URL as Extension Search Paths" section of developers manual.
To add a link to your *Omniverse Kit* based app go into: Extension Manager -> Gear Icon -> Extension Search Path
# Troubleshooting
While working in Composer, add the following snippet:
```
[python.pipapi]
requirements = [
"requests"
]
use_online_index = true
```
## Contributing
The source code for this repository is provided as-is and we are not accepting outside contributions.
| 2,697 | Markdown | 33.589743 | 258 | 0.765666 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/config/extension.toml | [package]
# Semantic Versioning is used: https://semver.org/
version = "1.0.0"
# The title and description fields are primarily for displaying extension info in UI
title = "Edge Impulse Data Ingestion"
description="Edge Impulse Data Ingestion extension for Omniverse."
# Path (relative to the root) or content of readme markdown file for UI.
readme = "docs/README.md"
# URL of the extension source repository.
repository = ""
# One of categories for UI.
category = "Example"
# Keywords for the extension
keywords = ["kit", "example"]
# Icon to show in the extension manager
icon = "data/icon.png"
# Preview to show in the extension manager
preview_image = "data/preview.png"
# Use omni.ui to build simple UI
[dependencies]
"omni.kit.uiapp" = {}
# Main python module this extension provides, it will be publicly available as "import omni.example.apiconnect".
[[python.module]]
name = "edgeimpulse.dataingestion"
[[test]]
# Extra dependencies only to be used during test run
dependencies = [
"omni.kit.ui_test" # UI testing extension
]
[python.pipapi]
requirements = [
"httpx==0.21.1",
"pyyaml",
"webbrowser"
]
use_online_index = true | 1,160 | TOML | 23.702127 | 112 | 0.726724 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/config.py | import os
import json
from .state import State
class Config:
def __init__(self, config_file="config.json"):
self.config_file = config_file
self.config_data = self.load_config()
def load_config(self):
if os.path.exists(self.config_file):
with open(self.config_file, "r") as file:
return json.load(file)
return {}
def print_config_info(self):
"""Prints the path and content of the configuration file."""
print(f"Config file path: {self.config_file}")
print("Config contents:")
print(json.dumps(self.config_data, indent=4))
def save_config(self):
with open(self.config_file, "w") as file:
json.dump(self.config_data, file)
def get(self, key, default=None):
return self.config_data.get(key, default)
def set(self, key, value):
self.config_data[key] = value
self.save_config()
def get_state(self):
"""Retrieve the saved state from the config."""
# Default to NO_PROJECT_CONNECTED if not set
return self.get("state", State.NO_PROJECT_CONNECTED.name)
def set_state(self, state):
"""Save the current state to the config."""
self.set("state", state.name)
| 1,264 | Python | 28.418604 | 68 | 0.607595 |
edgeimpulse/edge-impulse-omniverse-ext/exts/edgeimpulse.dataingestion/edgeimpulse/dataingestion/state.py | from enum import Enum, auto
class State(Enum):
NO_PROJECT_CONNECTED = auto()
PROJECT_CONNECTED = auto()
| 114 | Python | 15.428569 | 33 | 0.684211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.