File size: 7,760 Bytes
0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 8cb339b 0248d13 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | import carb
import math
import torch
import numpy as np
import omni.usd
from omni.kit.scripting import BehaviorScript
from isaacsim.core.prims import Articulation
from omni.isaac.core.prims import XFormPrim
from isaacsim.core.utils.types import ArticulationActions
def find_prim_path_by_name(prim_name: str, root_path: str = "/") -> str:
"""Recursively find the full path by Prim name"""
stage = omni.usd.get_context().get_stage()
prim = stage.GetPrimAtPath(root_path)
def _find_prim(current):
if current.GetName() == prim_name:
return current.GetPath().pathString
for child in current.GetChildren():
result = _find_prim(child)
if result:
return result
return None
found_path = _find_prim(prim)
if not found_path:
raise RuntimeError(f"Prim '{prim_name}' not found under {root_path}")
return found_path
POSSIBLE_ASSET_ROOT_NAMES = ["switch_E_body_28"]
JOINT_NAMES = ["RevoluteJoint_switch"]
LIGHT_PRIM_NAME = "kitchen_all_light"
BUTTON_PRIM_NAME = "switch_E_button_09"
SWITCH_ON_THRESHOLD = math.radians(11)
SWITCH_ON_POSITION = math.radians(13)
SWITCH_OFF_POSITION = math.radians(0)
class RoomLightControl(BehaviorScript):
def on_init(self):
articulation_root_path = None
for root_name in POSSIBLE_ASSET_ROOT_NAMES:
try:
articulation_root_path = find_prim_path_by_name(root_name)
print(f"Found articulation root: {articulation_root_path}")
break
except RuntimeError:
continue
if articulation_root_path is None:
raise RuntimeError(f"Could not find articulation root with names: {POSSIBLE_ASSET_ROOT_NAMES}")
self.articulation_root_path = articulation_root_path
self.art = None
self.initialized = False
self.joint_names = JOINT_NAMES
self.joint_indices = None
self.use_torch = None
self.light_scopes = [XFormPrim(find_prim_path_by_name(LIGHT_PRIM_NAME))]
self.light_scopes[0].set_visibility(False)
self.joint_prim = XFormPrim(find_prim_path_by_name(BUTTON_PRIM_NAME))
print("joint_prim", self.joint_prim.prim_path)
self.local_pose_button, self.local_ort_button_down = self.joint_prim.get_local_pose()
def on_play(self):
self._initialize_articulation()
def on_stop(self):
for light in self.light_scopes:
light.set_visibility(False)
self.joint_prim.set_local_pose(translation=self.local_pose_button)
def on_update(self, current_time: float, delta_time: float):
if delta_time <= 0:
return
if not self.initialized:
self._initialize_articulation()
if not self.initialized:
return
self.apply_behavior()
def apply_behavior(self):
if not self.initialized or self.art is None:
return
self.light_control()
def _initialize_articulation(self):
"""Initialize the articulation object and get joint information"""
if self.initialized:
return
try:
self.art = Articulation(self.articulation_root_path)
if self.art is None:
return
# Get joint indices
self.joint_indices = []
for joint_name in self.joint_names:
idx = self.art.get_dof_index(joint_name)
if idx is not None:
self.joint_indices.append(idx)
else:
print(f"Warning: Could not find joint index for {joint_name}")
if not self.joint_indices:
print("Warning: No valid joint indices found")
return
# Detect if using torch
positions = self.art.get_joint_positions()
self.use_torch = isinstance(positions, torch.Tensor)
print(f"Detected platform: {'Isaac Lab (torch)' if self.use_torch else 'Isaac Sim (numpy/math)'}")
self.initialized = True
except Exception as e:
print(f"Error initializing articulation: {e}")
self.initialized = False
def _get_scalar_value(self, value):
"""Convert a value (potentially a torch.Tensor) to a scalar float"""
if isinstance(value, torch.Tensor):
return value.item()
elif isinstance(value, (list, tuple, np.ndarray)):
return float(value[0] if len(value) > 0 else 0.0)
else:
return float(value)
def light_control(self):
try:
positions = self.art.get_joint_positions()
# Handle both single joint and multiple joints cases
# If positions is a scalar (0-d), use it directly; otherwise index it
if isinstance(positions, torch.Tensor):
if positions.ndim == 0:
# Scalar tensor
joint_state = self._get_scalar_value(positions)
else:
# Array tensor, use index
joint_state = self._get_scalar_value(positions[self.joint_indices[0]])
elif isinstance(positions, np.ndarray):
if positions.ndim == 0:
# Scalar array
joint_state = self._get_scalar_value(positions)
else:
# Array, use index
joint_state = self._get_scalar_value(positions[self.joint_indices[0]])
else:
# List or other iterable, use index
joint_state = self._get_scalar_value(positions[self.joint_indices[0]])
current_visibility = self.light_scopes[0].get_visibility()
if joint_state < SWITCH_ON_THRESHOLD:
# 开关打开状态
if not current_visibility:
# 如果灯是关闭的,则打开所有灯
for light in self.light_scopes:
light.set_visibility(True)
# 设置开关到打开位置
target = SWITCH_OFF_POSITION
else:
target = None
else:
# 开关关闭状态
if current_visibility:
# 如果灯是打开的,则关闭所有灯
for light in self.light_scopes:
light.set_visibility(False)
# 设置开关到关闭位置
target = SWITCH_ON_POSITION
else:
target = None
if target is not None:
if self.use_torch:
# Get device from positions, handling both tensor and scalar cases
if isinstance(positions, torch.Tensor):
device = positions.device
else:
# Fallback: use default device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
targets_tensor = torch.tensor([target], device=device)
indices_tensor = torch.tensor([self.joint_indices[0]], device=device, dtype=torch.long)
action = ArticulationActions(joint_positions=targets_tensor, joint_indices=indices_tensor)
else:
action = ArticulationActions([target], joint_indices=[self.joint_indices[0]])
self.art.apply_action(action)
except Exception as e:
carb.log_error(f"Error in light control: {str(e)}")
# 发生错误时确保灯光关闭
for light in self.light_scopes:
light.set_visibility(False)
|