mxk1998 commited on
Commit
e428337
·
verified ·
1 Parent(s): 07a434a

Publish sealed evaluation sources, batch 25

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. third_party/robocasa/robocasa/models/fixtures/fixture_utils.py +106 -0
  2. third_party/robocasa/robocasa/models/fixtures/handles.py +316 -0
  3. third_party/robocasa/robocasa/models/fixtures/microwave.py +151 -0
  4. third_party/robocasa/robocasa/models/fixtures/others.py +287 -0
  5. third_party/robocasa/robocasa/models/objects/__init__.py +13 -0
  6. third_party/robocasa/robocasa/models/objects/composite/__init__.py +6 -0
  7. third_party/robocasa/robocasa/models/objects/composite/bin.py +211 -0
  8. third_party/robocasa/robocasa/models/objects/composite/box_pattern_object.py +126 -0
  9. third_party/robocasa/robocasa/models/objects/composite/lid.py +136 -0
  10. third_party/robocasa/robocasa/models/objects/composite/needle.py +109 -0
  11. third_party/robocasa/robocasa/models/objects/composite/pot_with_handles.py +404 -0
  12. third_party/robocasa/robocasa/models/objects/composite/ring_tripod.py +200 -0
  13. third_party/robocasa/robocasa/models/objects/composite_body/__init__.py +8 -0
  14. third_party/robocasa/robocasa/models/objects/composite_body/bin_with_handles.py +162 -0
  15. third_party/robocasa/robocasa/models/objects/composite_body/coffee_machine.py +246 -0
  16. third_party/robocasa/robocasa/models/objects/composite_body/cup.py +187 -0
  17. third_party/robocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py +141 -0
  18. third_party/robocasa/robocasa/models/objects/composite_body/lightbulb.py +155 -0
  19. third_party/robocasa/robocasa/models/objects/composite_body/sliding_box.py +132 -0
  20. third_party/robocasa/robocasa/models/objects/composite_body/socket.py +339 -0
  21. third_party/robocasa/robocasa/models/objects/composite_body/spray_bottle.py +213 -0
  22. third_party/robocasa/robocasa/models/objects/composite_body/stacked_box.py +111 -0
  23. third_party/robocasa/robocasa/models/objects/composite_body/stacked_cylinder.py +129 -0
  24. third_party/robocasa/robocasa/models/objects/composite_body/stove_plug.py +400 -0
  25. third_party/robocasa/robocasa/models/objects/kitchen_object_utils.py +551 -0
  26. third_party/robocasa/robocasa/models/objects/kitchen_objects.py +2509 -0
  27. third_party/robocasa/robocasa/models/objects/objects.py +290 -0
  28. third_party/robocasa/robocasa/models/objects/xml_objects.py +271 -0
  29. third_party/robocasa/robocasa/models/robots/__init__.py +748 -0
  30. third_party/robocasa/robocasa/models/robots/manipulators/README.md +40 -0
  31. third_party/robocasa/robocasa/models/robots/manipulators/__init__.py +7 -0
  32. third_party/robocasa/robocasa/models/robots/manipulators/gr1_robot.py +59 -0
  33. third_party/robocasa/robocasa/models/scenes/__init__.py +1 -0
  34. third_party/robocasa/robocasa/models/scenes/scene_builder.py +289 -0
  35. third_party/robocasa/robocasa/models/scenes/scene_registry.py +144 -0
  36. third_party/robocasa/robocasa/models/scenes/scene_utils.py +180 -0
  37. third_party/robocasa/robocasa/models/scenes/tabletop_arena.py +52 -0
  38. third_party/robocasa/robocasa/scripts/demo_task.py +47 -0
  39. third_party/robocasa/robocasa/scripts/download_groot_assets.py +135 -0
  40. third_party/robocasa/robocasa/scripts/download_kitchen_assets.py +218 -0
  41. third_party/robocasa/robocasa/scripts/download_tabletop_assets.py +30 -0
  42. third_party/robocasa/robocasa/scripts/playback_dataset.py +643 -0
  43. third_party/robocasa/robocasa/utils/camera_utils.py +91 -0
  44. third_party/robocasa/robocasa/utils/config_utils.py +63 -0
  45. third_party/robocasa/robocasa/utils/cotrain_utils.py +24 -0
  46. third_party/robocasa/robocasa/utils/dexmg_utils.py +105 -0
  47. third_party/robocasa/robocasa/utils/gym_utils/__init__.py +4 -0
  48. third_party/robocasa/robocasa/utils/gym_utils/gymnasium_basic.py +261 -0
  49. third_party/robocasa/robocasa/utils/gym_utils/gymnasium_gearbc.py +184 -0
  50. third_party/robocasa/robocasa/utils/gym_utils/gymnasium_groot.py +173 -0
third_party/robocasa/robocasa/models/fixtures/fixture_utils.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robocasa.models.fixtures import *
2
+
3
+
4
+ def fixture_is_type(fixture, fixture_type):
5
+ """
6
+ Check if a fixture is of a certain type
7
+
8
+ Args:
9
+ fixture (Fixture): The fixture to check
10
+
11
+ fixture_type (FixtureType): The type to check against
12
+ """
13
+ if fixture_type == FixtureType.COUNTER:
14
+ return isinstance(fixture, Counter)
15
+ elif fixture_type == FixtureType.DINING_COUNTER:
16
+ cls_check = any([isinstance(fixture, cls) for cls in [Counter]])
17
+ if not cls_check:
18
+ return False
19
+ return fixture.width >= 2 or fixture.depth >= 2
20
+ elif fixture_type == FixtureType.CABINET:
21
+ return isinstance(fixture, Cabinet)
22
+ elif fixture_type == FixtureType.DRAWER:
23
+ return isinstance(fixture, Drawer)
24
+ elif fixture_type == FixtureType.SINK:
25
+ return isinstance(fixture, Sink)
26
+ elif fixture_type == FixtureType.STOVE:
27
+ return isinstance(fixture, Stove)
28
+ elif fixture_type == FixtureType.CABINET_TOP:
29
+ cls_check = any(
30
+ [
31
+ isinstance(fixture, cls)
32
+ for cls in [SingleCabinet, HingeCabinet, OpenCabinet]
33
+ ]
34
+ )
35
+ if not cls_check:
36
+ return False
37
+ if "stack" in fixture.name: # wall stack cabinets not valid
38
+ return False
39
+ # check the height of the cabinet to see if it is a top cabinet
40
+ fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2]
41
+ height_check = 1.0 <= fxtr_bottom_z <= 1.60
42
+ return height_check
43
+ elif fixture_type == FixtureType.MICROWAVE:
44
+ return isinstance(fixture, Microwave)
45
+ elif fixture_type in [FixtureType.DOOR_HINGE, FixtureType.DOOR_TOP_HINGE]:
46
+ cls_check = any(
47
+ [
48
+ isinstance(fixture, cls)
49
+ for cls in [SingleCabinet, HingeCabinet, Microwave]
50
+ ]
51
+ )
52
+ if not cls_check:
53
+ return False
54
+ if fixture_type == FixtureType.DOOR_TOP_HINGE:
55
+ if "stack" in fixture.name: # wall stack cabinets not valid
56
+ return False
57
+ fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2]
58
+ height_check = 1.0 <= fxtr_bottom_z <= 1.60
59
+ if not height_check:
60
+ return False
61
+ return True
62
+ elif fixture_type in [
63
+ FixtureType.DOOR_HINGE_SINGLE,
64
+ FixtureType.DOOR_TOP_HINGE_SINGLE,
65
+ ]:
66
+ cls_check = any(
67
+ [isinstance(fixture, cls) for cls in [SingleCabinet, Microwave]]
68
+ )
69
+ if not cls_check:
70
+ return False
71
+ if fixture_type == FixtureType.DOOR_TOP_HINGE_SINGLE:
72
+ if "stack" in fixture.name: # wall stack cabinets not valid
73
+ return False
74
+ fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2]
75
+ height_check = 1.0 <= fxtr_bottom_z <= 1.60
76
+ if not height_check:
77
+ return False
78
+ return True
79
+ elif fixture_type in [
80
+ FixtureType.DOOR_HINGE_DOUBLE,
81
+ FixtureType.DOOR_TOP_HINGE_DOUBLE,
82
+ ]:
83
+ cls_check = any([isinstance(fixture, cls) for cls in [HingeCabinet]])
84
+ if not cls_check:
85
+ return False
86
+ if fixture_type == FixtureType.DOOR_TOP_HINGE_DOUBLE:
87
+ if "stack" in fixture.name: # wall stack cabinets not valid
88
+ return False
89
+ fxtr_bottom_z = fixture.pos[2] + fixture.bottom_offset[2]
90
+ height_check = 1.0 <= fxtr_bottom_z <= 1.60
91
+ if not height_check:
92
+ return False
93
+ return True
94
+ elif fixture_type == FixtureType.TOASTER:
95
+ return isinstance(fixture, Toaster)
96
+ elif fixture_type == FixtureType.TOP_DRAWER:
97
+ height_check = 0.7 <= fixture.pos[2] <= 0.9
98
+ return height_check and isinstance(fixture, Drawer)
99
+ elif fixture_type == FixtureType.STOOL:
100
+ return isinstance(fixture, Stool)
101
+ elif fixture_type == FixtureType.ISLAND:
102
+ return isinstance(fixture, Counter) and "island" in fixture.name
103
+ elif fixture_type == FixtureType.COUNTER_NON_CORNER:
104
+ return isinstance(fixture, Counter) and "corner" not in fixture.name
105
+ else:
106
+ raise ValueError
third_party/robocasa/robocasa/models/fixtures/handles.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import os
3
+ from xml.etree import ElementTree as ET
4
+
5
+ import numpy as np
6
+ from robosuite.utils.mjcf_utils import array_to_string as a2s
7
+ from robosuite.utils.mjcf_utils import find_elements, xml_path_completion
8
+
9
+ import robocasa
10
+ from robocasa.models.objects import MujocoXMLObject
11
+ from robocasa.models.fixtures.fixture import get_texture_name_from_file
12
+
13
+
14
+ class Handle(MujocoXMLObject):
15
+ """
16
+ Base class for all handles attached to cabinet/drawer panels
17
+
18
+ Args:
19
+ name (str): Name of the handle
20
+
21
+ xml (str): Path to the xml file of the handle
22
+
23
+ panel_w (float): Width of the panel to attach the handle to
24
+
25
+ panel_h (float): Height of the panel to attach the handle to
26
+
27
+ texture (str): Path to the texture file of the handle
28
+
29
+ orientation (str): Orientation of the handle. Can be either "horizontal" (for drawers) or "vertical"
30
+
31
+ length (float): Length of the handle
32
+ """
33
+
34
+ def __init__(
35
+ self,
36
+ name,
37
+ xml,
38
+ panel_w,
39
+ panel_h,
40
+ texture="textures/metals/bright_metal.png",
41
+ orientation="vertical",
42
+ length=None,
43
+ ):
44
+ super().__init__(
45
+ xml_path_completion(xml, root=robocasa.models.assets_root),
46
+ name=name,
47
+ joints=None,
48
+ duplicate_collision_geoms=True,
49
+ )
50
+
51
+ self.length = length
52
+ self.orientation = orientation
53
+ self.texture = xml_path_completion(texture, root=robocasa.models.assets_root)
54
+ self.panel_w = panel_w
55
+ self.panel_h = panel_h
56
+
57
+ # for hinge cabinets
58
+ self.side = None
59
+
60
+ self._create_handle()
61
+ self._set_texture()
62
+
63
+ @abc.abstractmethod
64
+ def _get_components(self):
65
+ raise NotImplementedError
66
+
67
+ @abc.abstractmethod
68
+ def _create_handle(self, positions, sizes):
69
+ raise NotImplementedError
70
+
71
+ def exclude_from_prefixing(self, inp):
72
+ """
73
+ Exclude all shared materials and their associated names from being prefixed.
74
+
75
+ Args:
76
+ inp (ET.Element or str): Element or its attribute to check for prefixing.
77
+
78
+ Returns:
79
+ bool: True if we should exclude the associated name(s) with @inp from being prefixed with naming_prefix
80
+ """
81
+ if "tex" in inp:
82
+ return True
83
+
84
+ if isinstance(inp, ET.Element):
85
+ return inp.tag in ["texture"]
86
+
87
+ return False
88
+
89
+ def _set_texture(self):
90
+ """
91
+ Set the texture of the handle
92
+ """
93
+ # set texture
94
+ texture = find_elements(
95
+ self.root, tags="texture", attribs={"name": "tex"}, return_first=True
96
+ )
97
+ tex_name = get_texture_name_from_file(self.texture)
98
+ texture.set("file", self.texture)
99
+ texture.set("name", tex_name)
100
+
101
+ material = find_elements(
102
+ self.root,
103
+ tags="material",
104
+ attribs={"name": "{}_mat".format(self.name)},
105
+ return_first=True,
106
+ )
107
+ material.set("texture", tex_name)
108
+
109
+
110
+ class BarHandle(Handle):
111
+ """
112
+ Creates a bar handle
113
+
114
+ Args:
115
+ length (float): Length of the handle
116
+
117
+ handle_pad (float): A minimum difference between handle length and cabinet panel height
118
+ """
119
+
120
+ def __init__(
121
+ self,
122
+ length=0.24,
123
+ # connector_pad=0.05,
124
+ handle_pad=0.04,
125
+ *args,
126
+ **kwargs
127
+ ):
128
+ # z-direction padding for top and bottom connectors
129
+ # self.connector_pad = connector_pad
130
+ # assert length > connector_pad * 2
131
+ # z-direction padding for handle from sides of cabinet
132
+ self.handle_pad = handle_pad
133
+
134
+ super().__init__(
135
+ xml="fixtures/handles/bar_handle.xml", length=length, *args, **kwargs
136
+ )
137
+
138
+ def _get_components(self):
139
+ """
140
+ Get the geoms of the handle
141
+ """
142
+ geom_names = ["handle", "handle_connector_top", "handle_connector_bottom"]
143
+ body_names = []
144
+ joint_names = []
145
+ return self._get_elements_by_name(geom_names, body_names, joint_names)
146
+
147
+ def _create_handle(self):
148
+ """
149
+ Calculates and sets and positions and sizes of each component of the handles
150
+ Treats the three types of cabinets separately
151
+ """
152
+
153
+ # adjust handle size if necessary
154
+ if self.panel_h < self.length + 2 * self.handle_pad:
155
+ self.length = self.panel_h - 2 * self.handle_pad
156
+ # if self.length < 3 * self.connector_pad:
157
+ # raise ValueError("Cabinet size {:.3f} is too small for " \
158
+ # "bar handles.".format(self.panel_h))
159
+
160
+ offset = self.length / 2 * 0.60 # - self.connector_pad
161
+ # distance between main handle and door
162
+ conn_len = 0.05
163
+
164
+ # calculate positions for each component
165
+ positions = {
166
+ "handle": np.array([0, -conn_len, 0]),
167
+ "handle_connector_top": np.array([0, -conn_len / 2, offset]),
168
+ "handle_connector_bottom": np.array([0, -conn_len / 2, -offset]),
169
+ }
170
+ sizes = {
171
+ "handle": [0.013, self.length / 2],
172
+ "handle_connector_top": [0.008, conn_len / 2],
173
+ "handle_connector_bottom": [0.008, conn_len / 2],
174
+ }
175
+ eulers = {}
176
+
177
+ if self.orientation == "horizontal":
178
+ positions["handle_connector_top"][[0, 2]] = positions[
179
+ "handle_connector_top"
180
+ ][[2, 0]]
181
+ positions["handle_connector_bottom"][[0, 2]] = positions[
182
+ "handle_connector_bottom"
183
+ ][[2, 0]]
184
+ eulers["handle"] = [0, 1.5708, 0]
185
+
186
+ geoms, bodies, joints = self._get_components()
187
+ for side in positions.keys():
188
+ for geom in geoms[side]:
189
+ if geom is None:
190
+ continue
191
+ geom.set("pos", a2s(positions[side]))
192
+ geom.set("size", a2s(sizes[side]))
193
+
194
+ if eulers.get(side) is not None:
195
+ geom.set("euler", a2s(eulers[side]))
196
+
197
+
198
+ class BoxedHandle(Handle):
199
+ """
200
+ Creates a boxed handle
201
+
202
+ Args:
203
+ length (float): Length of the handle
204
+
205
+ handle_pad (float): A minimum difference between handle length and cabinet panel height
206
+ """
207
+
208
+ def __init__(self, length=0.24, handle_pad=0.04, *args, **kwargs):
209
+ self.handle_pad = handle_pad
210
+ super().__init__(
211
+ xml="fixtures/handles/boxed_handle.xml", length=length, *args, **kwargs
212
+ )
213
+
214
+ def _get_components(self):
215
+ """
216
+ Get the geoms of the handle
217
+ """
218
+ geom_names = ["handle", "handle_connector_top", "handle_connector_bottom"]
219
+ body_names = []
220
+ joint_names = []
221
+ return self._get_elements_by_name(geom_names, body_names, joint_names)
222
+
223
+ def _create_handle(self):
224
+ """
225
+ Calculates and sets and positions and sizes of each component of the handles
226
+ Treats the three types of cabinets separately
227
+ """
228
+
229
+ # adjust handle size if necessary
230
+ if self.panel_h < self.length + 2 * self.handle_pad:
231
+ self.length = self.panel_h - 2 * self.handle_pad
232
+
233
+ conn_len = 0.05
234
+ connector_depth = (conn_len / 2) - 0.01
235
+ connector_zpos = (self.length / 2) - 0.01
236
+
237
+ # calculate positions for each component
238
+ positions = {
239
+ "handle": np.array([0, -conn_len, 0]),
240
+ "handle_connector_top": np.array([0, -conn_len / 2, connector_zpos]),
241
+ "handle_connector_bottom": np.array([0, -conn_len / 2, -connector_zpos]),
242
+ }
243
+ sizes = {
244
+ "handle": [0.01, 0.01, self.length / 2],
245
+ "handle_connector_top": [0.01, 0.01, connector_depth],
246
+ "handle_connector_bottom": [0.01, 0.01, connector_depth],
247
+ }
248
+ eulers = {}
249
+
250
+ if self.orientation == "horizontal":
251
+ positions["handle_connector_top"][[0, 2]] = positions[
252
+ "handle_connector_top"
253
+ ][[2, 0]]
254
+ positions["handle_connector_bottom"][[0, 2]] = positions[
255
+ "handle_connector_bottom"
256
+ ][[2, 0]]
257
+ eulers["handle"] = [0, 1.5708, 0]
258
+
259
+ geoms, bodies, joints = self._get_components()
260
+ for side in positions.keys():
261
+ for geom in geoms[side]:
262
+ if geom is None:
263
+ continue
264
+ geom.set("pos", a2s(positions[side]))
265
+ geom.set("size", a2s(sizes[side]))
266
+
267
+ if eulers.get(side) is not None:
268
+ geom.set("euler", a2s(eulers[side]))
269
+
270
+
271
+ class KnobHandle(Handle):
272
+ """
273
+ Creates a knob handle
274
+ """
275
+
276
+ def __init__(self, handle_pad=0.07, *args, **kwargs):
277
+ super().__init__(
278
+ xml="fixtures/handles/knob_handle.xml",
279
+ # length=length,
280
+ *args,
281
+ **kwargs
282
+ )
283
+
284
+ # z-direction padding for handle from sides of cabinet
285
+ self.handle_pad = handle_pad
286
+
287
+ def _get_components(self):
288
+ """
289
+ Get the geoms of the handle
290
+ """
291
+ geom_names = ["handle"]
292
+ body_names = []
293
+ joint_names = []
294
+ return self._get_elements_by_name(geom_names, body_names, joint_names)
295
+
296
+ def _create_handle(self):
297
+ """
298
+ Calculates and sets and positions and sizes of each component of the handles
299
+ """
300
+
301
+ # calculate positions for each component
302
+ positions = {
303
+ "handle": np.array([0, -0.017, 0]),
304
+ }
305
+ # radius, depth
306
+ sizes = {
307
+ "handle": [0.015, 0.017],
308
+ }
309
+
310
+ geoms, bodies, joints = self._get_components()
311
+ for side in positions.keys():
312
+ for geom in geoms[side]:
313
+ if geom is None:
314
+ continue
315
+ geom.set("pos", a2s(positions[side]))
316
+ geom.set("size", a2s(sizes[side]))
third_party/robocasa/robocasa/models/fixtures/microwave.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import robocasa.utils.object_utils as OU
4
+ from robocasa.models.fixtures import Fixture
5
+
6
+
7
+ class Microwave(Fixture):
8
+ """
9
+ Microwave fixture class. Supports turning on and off the microwave, and opening and closing the door
10
+
11
+ Args:
12
+ xml (str): path to mjcf xml file
13
+
14
+ name (str): name of the object
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ xml="fixtures/microwaves/orig_microwave",
20
+ name="microwave",
21
+ *args,
22
+ **kwargs,
23
+ ):
24
+ super().__init__(
25
+ xml=xml, name=name, duplicate_collision_geoms=False, *args, **kwargs
26
+ )
27
+ self._turned_on = False
28
+
29
+ def set_door_state(self, min, max, env, rng):
30
+ """
31
+ Sets how open the door is. Chooses a random amount between min and max.
32
+ Min and max are percentages of how open the door is
33
+
34
+ Args:
35
+ min (float): minimum percentage of how open the door is
36
+
37
+ max (float): maximum percentage of how open the door is
38
+
39
+ env (MujocoEnv): environment
40
+
41
+ rng (np.random.Generator): random number generator
42
+
43
+ """
44
+ assert 0 <= min <= 1 and 0 <= max <= 1 and min <= max
45
+
46
+ joint_min = 0
47
+ joint_max = np.pi / 2
48
+
49
+ desired_min = joint_min + (joint_max - joint_min) * min
50
+ desired_max = joint_min + (joint_max - joint_min) * max
51
+
52
+ sign = -1
53
+
54
+ env.sim.data.set_joint_qpos(
55
+ "{}_microjoint".format(self.name),
56
+ sign * rng.uniform(desired_min, desired_max),
57
+ )
58
+
59
+ def get_door_state(self, env):
60
+ """
61
+ Args:
62
+ env (MujocoEnv): environment
63
+
64
+ Returns:
65
+ dict: maps door name to a percentage of how open the door is
66
+ """
67
+ sim = env.sim
68
+ hinge_qpos = sim.data.qpos[sim.model.joint_name2id(f"{self.name}_microjoint")]
69
+ hinge_qpos = -hinge_qpos # negate as micro joints are left door hinges
70
+
71
+ # convert to percentages
72
+ door = OU.normalize_joint_value(hinge_qpos, joint_min=0, joint_max=np.pi / 2)
73
+
74
+ return {
75
+ "door": door,
76
+ }
77
+
78
+ def get_state(self):
79
+ """
80
+ Returns:
81
+ dict: maps turned_on to whether the microwave is turned on
82
+ """
83
+ state = dict(
84
+ turned_on=self._turned_on,
85
+ )
86
+ return state
87
+
88
+ @property
89
+ def handle_name(self):
90
+ return "{}_door_handle".format(self.name)
91
+
92
+ @property
93
+ def door_name(self):
94
+ return "{}_door".format(self.name)
95
+
96
+ def update_state(self, env):
97
+ """
98
+ If the microwave is open, the state is set to off. Otherwise, if the gripper
99
+ is pressing the start button, the microwave will stay/turn on. If the gripper is
100
+ pressing the stop button, the microwave will stay/turn off.
101
+
102
+ Args:
103
+ env (MujocoEnv): The environment to check the state of the microwave in
104
+
105
+ """
106
+ start_button_pressed = env.check_contact(
107
+ env.robots[0].gripper["right"], "{}_start_button".format(self.name)
108
+ )
109
+ stop_button_pressed = env.check_contact(
110
+ env.robots[0].gripper["right"], "{}_stop_button".format(self.name)
111
+ )
112
+
113
+ door_state = self.get_door_state(env)["door"]
114
+ door_open = door_state > 0.005
115
+
116
+ if door_open:
117
+ self._turned_on = False
118
+ else:
119
+ if self._turned_on is True and stop_button_pressed:
120
+ self._turned_on = False
121
+ elif self._turned_on is False and start_button_pressed:
122
+ self._turned_on = True
123
+
124
+ def gripper_button_far(self, env, button, th=0.15):
125
+ """
126
+ check whether gripper is far from the start button
127
+
128
+ Args:
129
+ env (MujocoEnv): The environment to check the state of the microwave in
130
+
131
+ button (str): button to check
132
+
133
+ th (float): threshold for distance between gripper and button
134
+
135
+ Returns:
136
+ bool: True if gripper is far from the button, False otherwise
137
+ """
138
+ assert button in ["start_button", "stop_button"]
139
+ button_id = env.sim.model.geom_name2id(
140
+ "{}{}".format(self.naming_prefix, button)
141
+ )
142
+ button_pos = env.sim.data.geom_xpos[button_id]
143
+ gripper_site_pos = env.sim.data.site_xpos[env.robots[0].eef_site_id["right"]]
144
+
145
+ gripper_button_far = np.linalg.norm(gripper_site_pos - button_pos) > th
146
+
147
+ return gripper_button_far
148
+
149
+ @property
150
+ def nat_lang(self):
151
+ return "microwave"
third_party/robocasa/robocasa/models/fixtures/others.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import xml.etree.ElementTree as ET
2
+ from copy import deepcopy
3
+
4
+ import numpy as np
5
+ from robosuite.models.objects import BoxObject
6
+ from robosuite.utils.mjcf_utils import CustomMaterial
7
+ from robosuite.utils.mjcf_utils import array_to_string as a2s
8
+ from robosuite.utils.mjcf_utils import string_to_array as s2a
9
+ from robosuite.utils.mjcf_utils import xml_path_completion
10
+
11
+ import robocasa
12
+ from robocasa.models.fixtures import Fixture
13
+
14
+
15
+ class Box(BoxObject):
16
+ """
17
+ Initializes a box object. Mainly used for filling in gaps in the environment like in corners or beneath bottom cabinets
18
+
19
+ Args:
20
+ pos (list): position of the object
21
+
22
+ size (list): size of the object
23
+
24
+ name (str): name of the object
25
+
26
+ texture (str): path to texture file
27
+
28
+ mat_attrib (dict): material attributes
29
+
30
+ tex_attrib (dict): texture attributes
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ pos,
36
+ size,
37
+ name="box",
38
+ texture="textures/wood/dark_wood_parquet.png",
39
+ mat_attrib={"shininess": "0.1"},
40
+ tex_attrib={"type": "cube"},
41
+ rng=None,
42
+ *args,
43
+ **kwargs
44
+ ):
45
+ texture = xml_path_completion(texture, root=robocasa.models.assets_root)
46
+ material = CustomMaterial(
47
+ texture=texture,
48
+ tex_name="box",
49
+ mat_name="box_mat",
50
+ tex_attrib=tex_attrib,
51
+ mat_attrib=mat_attrib,
52
+ shared=True,
53
+ )
54
+
55
+ super().__init__(
56
+ name=name,
57
+ material=material,
58
+ joints=None,
59
+ # divide by 2 per mujoco convention
60
+ size=[x / 2 for x in size],
61
+ )
62
+
63
+ self.size = size
64
+ self.pos = pos
65
+ if pos is not None:
66
+ self._obj.set("pos", a2s(pos))
67
+
68
+ # for relative positioning
69
+ self.origin_offset = np.array([0, 0, 0])
70
+ self.scale = 1
71
+
72
+ if rng is not None:
73
+ self.rng = rng
74
+ else:
75
+ self.rng = np.random.default_rng()
76
+
77
+ def set_pos(self, pos):
78
+ """
79
+ Set the position of the object
80
+
81
+ Args:
82
+ pos (list): position of the object
83
+ """
84
+ self.pos = pos
85
+ self._obj.set("pos", a2s(pos))
86
+
87
+ def update_state(self, env):
88
+ pass
89
+
90
+ @property
91
+ def rot(self):
92
+ """
93
+ Returns the rotation of the object only on the z-axis
94
+
95
+ Returns:
96
+ float: rotation
97
+ """
98
+ rot = s2a(self._obj.get("euler", "0.0 0.0 0.0"))
99
+ return rot[2]
100
+
101
+
102
+ class Wall(BoxObject):
103
+ """
104
+ Initializes a wall object. Used for creating walls in the environment
105
+
106
+ Args:
107
+ name (str): name of the object
108
+
109
+ texture (str): path to texture file
110
+
111
+ pos (list): position of the object
112
+
113
+ quat (list): quaternion of the object
114
+
115
+ size (list): size of the object
116
+
117
+ wall_side (str): which side the wall is on (back, front, left, right, floor)
118
+
119
+ mat_attrib (dict): material attributes
120
+
121
+ tex_attrib (dict): texture attributes
122
+
123
+ backing (bool): whether this is a backing wall
124
+
125
+ backing_extended (list): whether the backing is extended on the left and right
126
+
127
+ default_wall_th (float): default thickness of the wall
128
+
129
+ default_backing_th (float): default thickness of the backing
130
+ """
131
+
132
+ def __init__(
133
+ self,
134
+ name="wall",
135
+ texture="textures/bricks/white_bricks.png",
136
+ pos=None,
137
+ quat=None,
138
+ size=None,
139
+ wall_side="back",
140
+ mat_attrib={
141
+ "texrepeat": "3 3",
142
+ "reflectance": "0.1",
143
+ "shininess": "0.1",
144
+ "texuniform": "true",
145
+ },
146
+ tex_attrib={"type": "2d"},
147
+ # parameters used for alignment
148
+ backing=False,
149
+ backing_extended=[False, False],
150
+ default_wall_th=0.02,
151
+ default_backing_th=0.1,
152
+ rng=None,
153
+ *args,
154
+ **kwargs
155
+ ):
156
+ # change texture if used for backing
157
+ if backing:
158
+ texture = "textures/flat/light_gray.png"
159
+ texture = xml_path_completion(texture, root=robocasa.models.assets_root)
160
+ material = CustomMaterial(
161
+ texture=texture,
162
+ tex_name="wall",
163
+ mat_name="wall_mat",
164
+ tex_attrib=tex_attrib,
165
+ mat_attrib=mat_attrib,
166
+ )
167
+
168
+ self.wall_side = wall_side
169
+ # set the rotation according to which side the wall is on
170
+ if self.wall_side is not None:
171
+ quat = self.get_quat()
172
+
173
+ # align everything to account for thickness & backing
174
+ if self.wall_side == "floor":
175
+ size[0] += default_wall_th * 2
176
+ size[1] += default_wall_th * 2
177
+ pos[2] -= size[2]
178
+ if backing:
179
+ pos[2] -= default_wall_th * 2
180
+ else:
181
+ size[0] += default_wall_th * 2
182
+ shift = size[2] if not backing else size[2] + default_wall_th * 2
183
+ if self.wall_side == "left":
184
+ pos[0] -= shift
185
+ elif self.wall_side == "right":
186
+ pos[0] += shift
187
+ elif self.wall_side == "back":
188
+ pos[1] += shift
189
+ elif self.wall_side == "front":
190
+ pos[1] -= shift
191
+
192
+ if backing:
193
+ size[1] += default_wall_th + default_backing_th
194
+ pos[2] -= default_wall_th + default_backing_th
195
+
196
+ # extend left/right side to form a perfect box
197
+ if backing_extended[0]:
198
+ size[0] += default_backing_th
199
+ if self.wall_side in ["left", "right"]:
200
+ pos[1] += default_backing_th
201
+ else:
202
+ pos[0] -= default_backing_th
203
+ if backing_extended[1]:
204
+ size[0] += default_backing_th
205
+ if self.wall_side in ["left", "right"]:
206
+ pos[1] -= default_backing_th
207
+ else:
208
+ pos[0] += default_backing_th
209
+
210
+ super().__init__(
211
+ name=name, material=material, joints=None, size=size, *args, **kwargs
212
+ )
213
+
214
+ self.pos = pos
215
+ if pos is not None:
216
+ self._obj.set("pos", a2s(pos))
217
+ if quat is not None:
218
+ self._obj.set("quat", a2s(quat))
219
+
220
+ if rng is not None:
221
+ self.rng = rng
222
+ else:
223
+ self.rng = np.random.default_rng()
224
+
225
+ def set_pos(self, pos):
226
+ """
227
+ Set the position of the object
228
+
229
+ Args:
230
+ pos (list): position of the object
231
+ """
232
+ self.pos = pos
233
+ self._obj.set("pos", a2s(pos))
234
+
235
+ def get_quat(self):
236
+ """
237
+ Returns the quaternion of the object based on the wall side
238
+
239
+ Returns:
240
+ list: quaternion
241
+ """
242
+ side_rots = {
243
+ "back": [-0.707, 0.707, 0, 0],
244
+ "front": [0, 0, 0.707, -0.707],
245
+ "left": [0.5, 0.5, -0.5, -0.5],
246
+ "right": [0.5, -0.5, -0.5, 0.5],
247
+ "floor": [0.707, 0, 0, 0.707],
248
+ }
249
+ if self.wall_side not in side_rots:
250
+ raise ValueError()
251
+ return side_rots[self.wall_side]
252
+
253
+ def update_state(self, env):
254
+ pass
255
+
256
+
257
+ class Floor(Wall):
258
+ def __init__(
259
+ self,
260
+ size,
261
+ name="wall",
262
+ texture="textures/bricks/red_bricks.png",
263
+ mat_attrib={
264
+ "texrepeat": "2 2",
265
+ "texuniform": "true",
266
+ "reflectance": "0.1",
267
+ "shininess": "0.1",
268
+ },
269
+ *args,
270
+ **kwargs
271
+ ):
272
+ # swap x, y axes due to rotation
273
+ size = [size[1], size[0], size[2]]
274
+
275
+ texture = xml_path_completion(texture, root=robocasa.models.assets_root)
276
+
277
+ # everything is the same except the plane is rotated to be horizontal
278
+ super().__init__(
279
+ name,
280
+ texture,
281
+ # horizontal plane
282
+ wall_side="floor",
283
+ size=size,
284
+ mat_attrib=mat_attrib,
285
+ *args,
286
+ **kwargs
287
+ )
third_party/robocasa/robocasa/models/objects/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import *
2
+ from robosuite.utils import *
3
+
4
+ from .xml_objects import (
5
+ CoffeeMachinePodObject,
6
+ CoffeeMachineBodyObject,
7
+ CoffeeMachineLidObject,
8
+ CoffeeMachineBaseObject,
9
+ DrawerObject,
10
+ LongDrawerObject,
11
+ )
12
+ from .composite import *
13
+ from .composite_body import *
third_party/robocasa/robocasa/models/objects/composite/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from .box_pattern_object import BoxPatternObject
2
+ from .needle import NeedleObject
3
+ from .ring_tripod import RingTripodObject
4
+ from .bin import Bin
5
+ from .lid import Lid
6
+ from .pot_with_handles import PotWithHandlesObject
third_party/robocasa/robocasa/models/objects/composite/bin.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import robosuite.utils.transform_utils as T
4
+ from robosuite.models.objects import CompositeObject
5
+ from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict
6
+
7
+
8
+ class Bin(CompositeObject):
9
+ """
10
+ Generates a four-walled bin container with an open top.
11
+ Args:
12
+ name (str): Name of this Bin object
13
+ bin_size (3-array): (x,y,z) full size of bin
14
+ wall_thickness (float): How thick to make walls of bin
15
+ transparent_walls (bool): If True, walls will be semi-translucent
16
+ friction (3-array or None): If specified, sets friction values for this bin. None results in default values
17
+ density (float): Density value to use for all geoms. Defaults to 1000
18
+ use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored
19
+ rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values
20
+ material: If specified, use this material
21
+ upside_down (bool): if True, construct and initialize the Bin so the bottom geom is at the top
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ name,
27
+ bin_size=(0.3, 0.3, 0.15),
28
+ wall_thickness=0.01,
29
+ transparent_walls=True,
30
+ friction=None,
31
+ density=1000.0,
32
+ use_texture=True,
33
+ rgba=(0.2, 0.1, 0.0, 1.0),
34
+ material=None,
35
+ upside_down=False,
36
+ add_second_base=False,
37
+ transparent_base=False,
38
+ ):
39
+ # Set name
40
+ self._name = name
41
+
42
+ # Set object attributes
43
+ self.bin_size = np.array(bin_size)
44
+ self.wall_thickness = wall_thickness
45
+ self.transparent_walls = transparent_walls
46
+ self.friction = friction if friction is None else np.array(friction)
47
+ self.density = density
48
+ self.use_texture = use_texture
49
+ self.rgba = rgba
50
+ self.bin_mat_name = "dark_wood_mat"
51
+
52
+ # if box should be constructed and initialized upside down
53
+ self.upside_down = upside_down
54
+
55
+ # if box should have a second base (so it will be a closed box)
56
+ self.add_second_base = add_second_base
57
+ if self.add_second_base:
58
+ assert not self.upside_down
59
+
60
+ # if base(s) should be transparent
61
+ self.transparent_base = transparent_base
62
+
63
+ self.has_material = material is not None
64
+ if self.has_material:
65
+ assert isinstance(material, CustomMaterial)
66
+ self.material = material
67
+ self.bin_mat_name = self.material.mat_attrib["name"]
68
+ else:
69
+ # default material
70
+ tex_attrib = {
71
+ "type": "cube",
72
+ }
73
+ mat_attrib = {
74
+ "texrepeat": "3 3",
75
+ "specular": "0.4",
76
+ "shininess": "0.1",
77
+ }
78
+ bin_mat = CustomMaterial(
79
+ texture="WoodDark",
80
+ tex_name="dark_wood",
81
+ mat_name=self.bin_mat_name,
82
+ tex_attrib=tex_attrib,
83
+ mat_attrib=mat_attrib,
84
+ )
85
+ self.material = bin_mat
86
+
87
+ # Element references
88
+ self._base_geom = "base"
89
+ if self.add_second_base:
90
+ self._second_base_geom = "base2"
91
+
92
+ # Other private attributes
93
+ self._important_sites = {}
94
+
95
+ # Create dictionary of values to create geoms for composite object and run super init
96
+ super().__init__(**self._get_geom_attrs())
97
+
98
+ # Define materials we want to use for this object
99
+ self.append_material(self.material)
100
+
101
+ def _get_geom_attrs(self):
102
+ """
103
+ Creates geom elements that will be passed to superclass CompositeObject constructor
104
+ Returns:
105
+ dict: args to be used by CompositeObject to generate geoms
106
+ """
107
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
108
+ base_args = {
109
+ "total_size": self.bin_size / 2.0,
110
+ "name": self.name,
111
+ "locations_relative_to_center": True,
112
+ "obj_types": "all",
113
+ "density": self.density,
114
+ }
115
+ obj_args = {}
116
+
117
+ # Base(s)
118
+ base_geom_loc = (0, 0, -(self.bin_size[2] - self.wall_thickness) / 2)
119
+ if self.upside_down:
120
+ base_geom_loc = (
121
+ base_geom_loc[0],
122
+ base_geom_loc[1],
123
+ -1.0 * base_geom_loc[2],
124
+ )
125
+ if self.transparent_base:
126
+ base_rgba = (1.0, 1.0, 1.0, 0.3)
127
+ base_mat = None
128
+ else:
129
+ base_rgba = None if self.use_texture else self.rgba
130
+ base_mat = self.bin_mat_name if self.use_texture else None
131
+
132
+ base_geom_names = [self._base_geom]
133
+ base_geom_locs = [base_geom_loc]
134
+ if self.add_second_base:
135
+ base_geom_names.append(self._second_base_geom)
136
+ base_geom_locs.append(
137
+ (base_geom_loc[0], base_geom_loc[1], -1.0 * base_geom_loc[2])
138
+ )
139
+
140
+ for base_g_name, base_g_loc in zip(base_geom_names, base_geom_locs):
141
+ add_to_dict(
142
+ dic=obj_args,
143
+ geom_types="box",
144
+ geom_locations=base_g_loc,
145
+ geom_quats=(1, 0, 0, 0),
146
+ geom_sizes=(
147
+ np.array((self.bin_size[0], self.bin_size[1], self.wall_thickness))
148
+ - np.array((self.wall_thickness, self.wall_thickness, 0))
149
+ )
150
+ / 2,
151
+ geom_names=base_g_name,
152
+ geom_rgbas=base_rgba,
153
+ geom_materials=base_mat,
154
+ geom_frictions=self.friction,
155
+ )
156
+
157
+ # Walls
158
+ x_vals = np.array(
159
+ [
160
+ 0,
161
+ -(self.bin_size[0] - self.wall_thickness) / 2,
162
+ 0,
163
+ (self.bin_size[0] - self.wall_thickness) / 2,
164
+ ]
165
+ )
166
+ y_vals = np.array(
167
+ [
168
+ -(self.bin_size[1] - self.wall_thickness) / 2,
169
+ 0,
170
+ (self.bin_size[1] - self.wall_thickness) / 2,
171
+ 0,
172
+ ]
173
+ )
174
+ w_vals = np.array(
175
+ [self.bin_size[0], self.bin_size[1], self.bin_size[0], self.bin_size[1]]
176
+ )
177
+ r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi])
178
+ if self.transparent_walls:
179
+ wall_rgba = (1.0, 1.0, 1.0, 0.3)
180
+ wall_mat = None
181
+ else:
182
+ wall_rgba = None if self.use_texture else self.rgba
183
+ wall_mat = self.bin_mat_name if self.use_texture else None
184
+ for i, (x, y, w, r) in enumerate(zip(x_vals, y_vals, w_vals, r_vals)):
185
+ add_to_dict(
186
+ dic=obj_args,
187
+ geom_types="box",
188
+ geom_locations=(x, y, 0),
189
+ geom_quats=T.convert_quat(
190
+ T.axisangle2quat(np.array([0, 0, r])), to="wxyz"
191
+ ),
192
+ geom_sizes=(self.wall_thickness / 2, w / 2, self.bin_size[2] / 2),
193
+ geom_names=f"wall{i}",
194
+ geom_rgbas=wall_rgba,
195
+ geom_materials=wall_mat,
196
+ geom_frictions=self.friction,
197
+ )
198
+
199
+ # Add back in base args and site args
200
+ obj_args.update(base_args)
201
+
202
+ # Return this dict
203
+ return obj_args
204
+
205
+ @property
206
+ def base_geoms(self):
207
+ """
208
+ Returns:
209
+ list of str: geom names corresponding to bin base
210
+ """
211
+ return [self.correct_naming(self._base_geom)]
third_party/robocasa/robocasa/models/objects/composite/box_pattern_object.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import CompositeObject
4
+ from robosuite.utils.mjcf_utils import add_to_dict
5
+ import robosuite.utils.transform_utils as T
6
+
7
+
8
+ class BoxPatternObject(CompositeObject):
9
+ """
10
+ Generates shapes by using a pattern of unit-size boxes.
11
+
12
+ Args:
13
+ name (str): Name of this Needle object
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ name,
19
+ unit_size,
20
+ pattern,
21
+ rgba=None,
22
+ material=None,
23
+ density=100.0,
24
+ # solref=[0.02, 1.],
25
+ # solimp=[0.9, 0.95, 0.001],
26
+ friction=None,
27
+ ):
28
+ """
29
+ Args:
30
+ unit_size (3d array / list): size of each unit block in each dimension
31
+
32
+ pattern (3d array / list): array of normalized sizes specifying the
33
+ geometry of the shape. A "0" indicates the absence of a cube and
34
+ a "1" indicates the presence of a full unit block. The dimensions
35
+ correspond to z, x, and y respectively.
36
+ """
37
+ self._name = name
38
+ self.rgba = rgba
39
+ self.material = material
40
+ self.density = density
41
+ self.friction = friction
42
+
43
+ # number of blocks in z, x, and y
44
+ self.pattern = np.array(pattern)
45
+ self.nz, self.nx, self.ny = self.pattern.shape
46
+ self.unit_size = unit_size
47
+ self.total_size = [
48
+ self.nx * unit_size[0],
49
+ self.ny * unit_size[1],
50
+ self.nz * unit_size[2],
51
+ ]
52
+
53
+ # Other private attributes
54
+ self._important_sites = {}
55
+
56
+ # Create dictionary of values to create geoms for composite object and run super init
57
+ super().__init__(**self._get_geom_attrs())
58
+
59
+ # Define materials we want to use for this object
60
+ if self.material is not None:
61
+ self.append_material(self.material)
62
+
63
+ def _get_geom_attrs(self):
64
+ """
65
+ Creates geom elements that will be passed to superclass CompositeObject constructor
66
+
67
+ Returns:
68
+ dict: args to be used by CompositeObject to generate geoms
69
+ """
70
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
71
+ base_args = {
72
+ "total_size": self.total_size,
73
+ "name": self.name,
74
+ "locations_relative_to_center": False,
75
+ "obj_types": "all",
76
+ "density": self.density,
77
+ }
78
+ obj_args = {}
79
+
80
+ geom_locations = []
81
+ geom_sizes = []
82
+ geom_names = []
83
+ nz, nx, ny = self.pattern.shape
84
+ for k in range(nz):
85
+ for i in range(nx):
86
+ for j in range(ny):
87
+ if self.pattern[k, i, j] > 0:
88
+ geom_sizes.append(
89
+ [
90
+ self.unit_size[0],
91
+ self.unit_size[1],
92
+ self.unit_size[2],
93
+ ]
94
+ )
95
+ geom_locations.append(
96
+ [
97
+ i * 2.0 * self.unit_size[0],
98
+ j * 2.0 * self.unit_size[1],
99
+ k * 2.0 * self.unit_size[2],
100
+ ]
101
+ )
102
+ geom_names.append("{}_{}_{}".format(k, i, j))
103
+
104
+ # geom_rgbas = [rgba for _ in geom_locations]
105
+ # geom_frictions = [friction for _ in geom_locations]
106
+ for i in range(len(geom_locations)):
107
+ add_to_dict(
108
+ dic=obj_args,
109
+ geom_types="box",
110
+ # needle geom needs to be offset from boundary in (x, z)
111
+ geom_locations=tuple(geom_locations[i]),
112
+ geom_quats=(1, 0, 0, 0),
113
+ geom_sizes=tuple(geom_sizes[i]),
114
+ geom_names=geom_names[i],
115
+ geom_rgbas=self.rgba,
116
+ geom_materials=self.material.name
117
+ if self.material is not None
118
+ else None,
119
+ geom_frictions=None,
120
+ )
121
+
122
+ # Add back in base args and site args
123
+ obj_args.update(base_args)
124
+
125
+ # Return this dict
126
+ return obj_args
third_party/robocasa/robocasa/models/objects/composite/lid.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import robosuite.utils.transform_utils as T
4
+ from robosuite.models.objects import CompositeObject
5
+ from robosuite.utils.mjcf_utils import CustomMaterial, add_to_dict
6
+
7
+
8
+ class Lid(CompositeObject):
9
+ """
10
+ Generates a square lid with a simple handle.
11
+ Args:
12
+ name (str): Name of this Lid object
13
+ lid_size (3-array): (length, width, thickness) of lid
14
+ handle_size (3-array): (thickness, length, height) of handle
15
+ transparent (bool): If True, lid will be semi-translucent
16
+ friction (3-array or None): If specified, sets friction values for this lid. None results in default values
17
+ density (float): Density value to use for all geoms. Defaults to 1000
18
+ use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored
19
+ rgba (4-array or None): If specified, sets rgba values for all geoms. None results in default values
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ name,
25
+ lid_size=(0.3, 0.3, 0.01),
26
+ handle_size=(0.02, 0.08, 0.03),
27
+ transparent=True,
28
+ friction=None,
29
+ density=250.0,
30
+ use_texture=True,
31
+ rgba=(0.2, 0.1, 0.0, 1.0),
32
+ ):
33
+ # Set name
34
+ self._name = name
35
+
36
+ # Set object attributes
37
+ self.lid_size = np.array(lid_size)
38
+ self.handle_size = np.array(handle_size)
39
+ self.transparent = transparent
40
+ self.friction = friction if friction is None else np.array(friction)
41
+ self.density = density
42
+ self.use_texture = use_texture
43
+ self.rgba = rgba
44
+ self.lid_mat_name = "dark_wood_mat"
45
+
46
+ # Element references
47
+ self._handle_geom = "handle"
48
+
49
+ # Other private attributes
50
+ self._important_sites = {}
51
+
52
+ # Create dictionary of values to create geoms for composite object and run super init
53
+ super().__init__(**self._get_geom_attrs())
54
+
55
+ # Define materials we want to use for this object
56
+ tex_attrib = {
57
+ "type": "cube",
58
+ }
59
+ mat_attrib = {
60
+ "texrepeat": "3 3",
61
+ "specular": "0.4",
62
+ "shininess": "0.1",
63
+ }
64
+ lid_mat = CustomMaterial(
65
+ texture="WoodDark",
66
+ tex_name="dark_wood",
67
+ mat_name=self.lid_mat_name,
68
+ tex_attrib=tex_attrib,
69
+ mat_attrib=mat_attrib,
70
+ )
71
+ self.append_material(lid_mat)
72
+
73
+ def _get_geom_attrs(self):
74
+ """
75
+ Creates geom elements that will be passed to superclass CompositeObject constructor
76
+ Returns:
77
+ dict: args to be used by CompositeObject to generate geoms
78
+ """
79
+ full_height = self.lid_size[2] + self.handle_size[2]
80
+ full_size = np.array([self.lid_size[0], self.lid_size[1], full_height])
81
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
82
+ base_args = {
83
+ "total_size": full_size / 2.0,
84
+ "name": self.name,
85
+ "locations_relative_to_center": True,
86
+ "obj_types": "all",
87
+ }
88
+ obj_args = {}
89
+
90
+ # Top
91
+ if self.transparent:
92
+ top_rgba = (1.0, 1.0, 1.0, 0.3)
93
+ top_mat = None
94
+ else:
95
+ top_rgba = None if self.use_texture else self.rgba
96
+ top_mat = self.lid_mat_name if self.use_texture else None
97
+ add_to_dict(
98
+ dic=obj_args,
99
+ geom_types="box",
100
+ geom_locations=(0, 0, (-full_size[2] + self.lid_size[2]) / 2),
101
+ geom_quats=(1, 0, 0, 0),
102
+ geom_sizes=np.array((full_size[0], full_size[1], self.lid_size[2])) / 2,
103
+ geom_names="top",
104
+ geom_rgbas=top_rgba,
105
+ geom_materials=top_mat,
106
+ geom_frictions=self.friction,
107
+ density=self.density,
108
+ )
109
+
110
+ # Handle
111
+ add_to_dict(
112
+ dic=obj_args,
113
+ geom_types="box",
114
+ geom_locations=(0, 0, (full_size[2] - self.handle_size[2]) / 2),
115
+ geom_quats=(1, 0, 0, 0),
116
+ geom_sizes=self.handle_size / 2,
117
+ geom_names=self._handle_geom,
118
+ geom_rgbas=None if self.use_texture else self.rgba,
119
+ geom_materials=self.lid_mat_name if self.use_texture else None,
120
+ geom_frictions=self.friction,
121
+ density=self.density * 2,
122
+ )
123
+
124
+ # Add back in base args and site args
125
+ obj_args.update(base_args)
126
+
127
+ # Return this dict
128
+ return obj_args
129
+
130
+ @property
131
+ def handle_geoms(self):
132
+ """
133
+ Returns:
134
+ list of str: geom names corresponding to lid handle
135
+ """
136
+ return [self.correct_naming(self._handle_geom)]
third_party/robocasa/robocasa/models/objects/composite/needle.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import CompositeObject
4
+ from robosuite.utils.mjcf_utils import add_to_dict, CustomMaterial
5
+ import robosuite.utils.transform_utils as T
6
+
7
+
8
+ class NeedleObject(CompositeObject):
9
+ """
10
+ Generates a needle with a handle (used in Threading task)
11
+
12
+ Args:
13
+ name (str): Name of this Needle object
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ name,
19
+ ):
20
+
21
+ ### TODO: make this object more general (with more args and configuration options) later ###
22
+
23
+ # Set object attributes
24
+ self._name = name
25
+ self.needle_mat_name = "darkwood_mat"
26
+
27
+ # Other private attributes
28
+ self._important_sites = {}
29
+
30
+ # Create dictionary of values to create geoms for composite object and run super init
31
+ super().__init__(**self._get_geom_attrs())
32
+
33
+ # Define materials we want to use for this object
34
+ tex_attrib = {
35
+ "type": "cube",
36
+ }
37
+ mat_attrib = {
38
+ "texrepeat": "1 1",
39
+ "specular": "0.4",
40
+ "shininess": "0.1",
41
+ }
42
+ needle_mat = CustomMaterial(
43
+ texture="WoodDark",
44
+ tex_name="darkwood",
45
+ mat_name="darkwood_mat",
46
+ tex_attrib=tex_attrib,
47
+ mat_attrib=mat_attrib,
48
+ )
49
+ self.append_material(needle_mat)
50
+
51
+ def _get_geom_attrs(self):
52
+ """
53
+ Creates geom elements that will be passed to superclass CompositeObject constructor
54
+
55
+ Returns:
56
+ dict: args to be used by CompositeObject to generate geoms
57
+ """
58
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
59
+ base_args = {
60
+ "total_size": [0.02, 0.08, 0.02],
61
+ "name": self.name,
62
+ "locations_relative_to_center": False,
63
+ "obj_types": "all",
64
+ "density": 100.0,
65
+ }
66
+ obj_args = {}
67
+
68
+ # make a skinny needle object with a large handle
69
+ needle_size = [0.005, 0.06, 0.005]
70
+ handle_size = [0.02, 0.02, 0.02]
71
+
72
+ # Needle
73
+ add_to_dict(
74
+ dic=obj_args,
75
+ geom_types="box",
76
+ # needle geom needs to be offset from boundary in (x, z)
77
+ geom_locations=(
78
+ (handle_size[0] - needle_size[0]),
79
+ 0.0,
80
+ (handle_size[2] - needle_size[2]),
81
+ ),
82
+ geom_quats=(1, 0, 0, 0),
83
+ geom_sizes=tuple(needle_size),
84
+ geom_names="needle",
85
+ geom_rgbas=None,
86
+ geom_materials=self.needle_mat_name,
87
+ # make the needle low friction to ensure easy insertion
88
+ geom_frictions=(0.3, 5e-3, 1e-4),
89
+ )
90
+
91
+ # Handle
92
+ add_to_dict(
93
+ dic=obj_args,
94
+ geom_types="box",
95
+ # handle geom needs to be offset in y
96
+ geom_locations=(0.0, 2.0 * needle_size[1], 0.0),
97
+ geom_quats=(1, 0, 0, 0),
98
+ geom_sizes=tuple(handle_size),
99
+ geom_names="handle",
100
+ geom_rgbas=None,
101
+ geom_materials=self.needle_mat_name,
102
+ geom_frictions=None,
103
+ )
104
+
105
+ # Add back in base args and site args
106
+ obj_args.update(base_args)
107
+
108
+ # Return this dict
109
+ return obj_args
third_party/robocasa/robocasa/models/objects/composite/pot_with_handles.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import robosuite.utils.transform_utils as T
4
+ from robosuite.models.objects import CompositeObject
5
+ from robosuite.utils.mjcf_utils import (
6
+ BLUE,
7
+ GREEN,
8
+ RED,
9
+ CustomMaterial,
10
+ add_to_dict,
11
+ array_to_string,
12
+ )
13
+
14
+
15
+ class PotWithHandlesObject(CompositeObject):
16
+ """
17
+ Generates the Pot object with side handles (used in TwoArmLift)
18
+
19
+ Args:
20
+ name (str): Name of this Pot object
21
+
22
+ body_half_size (3-array of float): If specified, defines the (x,y,z) half-dimensions of the main pot
23
+ body. Otherwise, defaults to [0.07, 0.07, 0.07]
24
+
25
+ handle_radius (float): Determines the pot handle radius
26
+
27
+ handle_length (float): Determines the pot handle length
28
+
29
+ handle_width (float): Determines the pot handle width
30
+
31
+ handle_friction (float): Friction value to use for pot handles. Defauls to 1.0
32
+
33
+ density (float): Density value to use for all geoms. Defaults to 1000
34
+
35
+ use_texture (bool): If true, geoms will be defined by realistic textures and rgba values will be ignored
36
+
37
+ rgba_body (4-array or None): If specified, sets pot body rgba values
38
+
39
+ rgba_handle_0 (4-array or None): If specified, sets handle 0 rgba values
40
+
41
+ rgba_handle_1 (4-array or None): If specified, sets handle 1 rgba values
42
+
43
+ solid_handle (bool): If true, uses a single geom to represent the handle
44
+
45
+ thickness (float): How thick to make the pot body walls
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ name,
51
+ body_half_size=(0.07, 0.07, 0.07),
52
+ handle_radius=0.01,
53
+ handle_length=0.09,
54
+ handle_width=0.09,
55
+ handle_friction=1.0,
56
+ density=1000,
57
+ use_texture=True,
58
+ rgba_body=None,
59
+ rgba_handle_0=None,
60
+ rgba_handle_1=None,
61
+ solid_handle=False,
62
+ thickness=0.01, # For body
63
+ ):
64
+ # Set name
65
+ self._name = name
66
+
67
+ # Set object attributes
68
+ self.body_half_size = np.array(body_half_size)
69
+ self.thickness = thickness
70
+ self.handle_radius = handle_radius
71
+ self.handle_length = handle_length
72
+ self.handle_width = handle_width
73
+ self.handle_friction = handle_friction
74
+ self.density = density
75
+ self.use_texture = use_texture
76
+ self.rgba_body = np.array(rgba_body) if rgba_body else RED
77
+ self.rgba_handle_0 = np.array(rgba_handle_0) if rgba_handle_0 else GREEN
78
+ self.rgba_handle_1 = np.array(rgba_handle_1) if rgba_handle_1 else BLUE
79
+ self.solid_handle = solid_handle
80
+
81
+ # Element references to be filled when generated
82
+ self._handle0_geoms = None
83
+ self._handle1_geoms = None
84
+ self.pot_base = None
85
+
86
+ # Other private attributes
87
+ self._important_sites = {}
88
+
89
+ # Create dictionary of values to create geoms for composite object and run super init
90
+ super().__init__(**self._get_geom_attrs())
91
+
92
+ # Define materials we want to use for this object
93
+ tex_attrib = {
94
+ "type": "cube",
95
+ }
96
+ mat_attrib = {
97
+ "texrepeat": "1 1",
98
+ "specular": "0.4",
99
+ "shininess": "0.1",
100
+ }
101
+ redwood = CustomMaterial(
102
+ texture="WoodRed",
103
+ tex_name="redwood",
104
+ mat_name="pot_mat",
105
+ tex_attrib=tex_attrib,
106
+ mat_attrib=mat_attrib,
107
+ )
108
+ greenwood = CustomMaterial(
109
+ texture="WoodGreen",
110
+ tex_name="greenwood",
111
+ mat_name="handle0_mat",
112
+ tex_attrib=tex_attrib,
113
+ mat_attrib=mat_attrib,
114
+ )
115
+ bluewood = CustomMaterial(
116
+ texture="WoodBlue",
117
+ tex_name="bluewood",
118
+ mat_name="handle1_mat",
119
+ tex_attrib=tex_attrib,
120
+ mat_attrib=mat_attrib,
121
+ )
122
+ self.append_material(redwood)
123
+ self.append_material(greenwood)
124
+ self.append_material(bluewood)
125
+
126
+ def _get_geom_attrs(self):
127
+ """
128
+ Creates geom elements that will be passed to superclass CompositeObject constructor
129
+
130
+ Returns:
131
+ dict: args to be used by CompositeObject to generate geoms
132
+ """
133
+ full_size = np.array(
134
+ (
135
+ self.body_half_size,
136
+ self.body_half_size + self.handle_length * 2,
137
+ self.body_half_size,
138
+ )
139
+ )
140
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
141
+ base_args = {
142
+ "total_size": full_size / 2.0,
143
+ "name": self.name,
144
+ "locations_relative_to_center": True,
145
+ "obj_types": "all",
146
+ }
147
+ site_attrs = []
148
+ obj_args = {}
149
+
150
+ # Initialize geom lists
151
+ self._handle0_geoms = []
152
+ self._handle1_geoms = []
153
+
154
+ # Add main pot body
155
+ # Base geom
156
+ name = f"base"
157
+ self.pot_base = [name]
158
+ add_to_dict(
159
+ dic=obj_args,
160
+ geom_types="box",
161
+ geom_locations=(0, 0, -self.body_half_size[2] + self.thickness / 2),
162
+ geom_quats=(1, 0, 0, 0),
163
+ geom_sizes=np.array(
164
+ [self.body_half_size[0], self.body_half_size[1], self.thickness / 2]
165
+ ),
166
+ geom_names=name,
167
+ geom_rgbas=None if self.use_texture else self.rgba_body,
168
+ geom_materials="pot_mat" if self.use_texture else None,
169
+ geom_frictions=None,
170
+ density=self.density,
171
+ )
172
+
173
+ # Walls
174
+ x_off = np.array(
175
+ [
176
+ 0,
177
+ -(self.body_half_size[0] - self.thickness / 2),
178
+ 0,
179
+ self.body_half_size[0] - self.thickness / 2,
180
+ ]
181
+ )
182
+ y_off = np.array(
183
+ [
184
+ -(self.body_half_size[1] - self.thickness / 2),
185
+ 0,
186
+ self.body_half_size[1] - self.thickness / 2,
187
+ 0,
188
+ ]
189
+ )
190
+ w_vals = np.array(
191
+ [
192
+ self.body_half_size[0],
193
+ self.body_half_size[1],
194
+ self.body_half_size[0],
195
+ self.body_half_size[1],
196
+ ]
197
+ )
198
+ r_vals = np.array([np.pi / 2, 0, -np.pi / 2, np.pi])
199
+ for i, (x, y, w, r) in enumerate(zip(x_off, y_off, w_vals, r_vals)):
200
+ add_to_dict(
201
+ dic=obj_args,
202
+ geom_types="box",
203
+ geom_locations=(x, y, 0),
204
+ geom_quats=T.convert_quat(
205
+ T.axisangle2quat(np.array([0, 0, r])), to="wxyz"
206
+ ),
207
+ geom_sizes=np.array([self.thickness / 2, w, self.body_half_size[2]]),
208
+ geom_names=f"body{i}",
209
+ geom_rgbas=None if self.use_texture else self.rgba_body,
210
+ geom_materials="pot_mat" if self.use_texture else None,
211
+ geom_frictions=None,
212
+ density=self.density,
213
+ )
214
+
215
+ # Add handles
216
+ main_bar_size = np.array(
217
+ [
218
+ self.handle_width / 2 + self.handle_radius,
219
+ self.handle_radius,
220
+ self.handle_radius,
221
+ ]
222
+ )
223
+ side_bar_size = np.array(
224
+ [self.handle_radius, self.handle_length / 2, self.handle_radius]
225
+ )
226
+ handle_z = self.body_half_size[2] - self.handle_radius
227
+ for i, (g_list, handle_side, rgba) in enumerate(
228
+ zip(
229
+ [self._handle0_geoms, self._handle1_geoms],
230
+ [1.0, -1.0],
231
+ [self.rgba_handle_0, self.rgba_handle_1],
232
+ )
233
+ ):
234
+ handle_center = np.array(
235
+ (
236
+ 0,
237
+ handle_side * (self.body_half_size[1] + self.handle_length),
238
+ handle_z,
239
+ )
240
+ )
241
+ # Solid handle case
242
+ if self.solid_handle:
243
+ handle_center = np.array(
244
+ (
245
+ 0,
246
+ handle_side * (self.body_half_size[1] + self.handle_length / 2),
247
+ handle_z,
248
+ )
249
+ )
250
+ name = f"handle{i}"
251
+ g_list.append(name)
252
+ add_to_dict(
253
+ dic=obj_args,
254
+ geom_types="box",
255
+ geom_locations=handle_center,
256
+ geom_quats=(1, 0, 0, 0),
257
+ geom_sizes=np.array(
258
+ [
259
+ self.handle_width / 2,
260
+ self.handle_length / 2,
261
+ self.handle_radius,
262
+ ]
263
+ ),
264
+ geom_names=name,
265
+ geom_rgbas=None if self.use_texture else rgba,
266
+ geom_materials=f"handle{i}_mat" if self.use_texture else None,
267
+ geom_frictions=(self.handle_friction, 0.005, 0.0001),
268
+ density=self.density,
269
+ )
270
+ # Hollow handle case
271
+ else:
272
+ # Center bar
273
+ name = f"handle{i}_c"
274
+ g_list.append(name)
275
+ add_to_dict(
276
+ dic=obj_args,
277
+ geom_types="box",
278
+ geom_locations=handle_center,
279
+ geom_quats=(1, 0, 0, 0),
280
+ geom_sizes=main_bar_size,
281
+ geom_names=name,
282
+ geom_rgbas=None if self.use_texture else rgba,
283
+ geom_materials=f"handle{i}_mat" if self.use_texture else None,
284
+ geom_frictions=(self.handle_friction, 0.005, 0.0001),
285
+ density=self.density,
286
+ )
287
+ # Side bars
288
+ for bar_side, suffix in zip([-1.0, 1.0], ["-", "+"]):
289
+ name = f"handle{i}_{suffix}"
290
+ g_list.append(name)
291
+ add_to_dict(
292
+ dic=obj_args,
293
+ geom_types="box",
294
+ geom_locations=(
295
+ bar_side * self.handle_width / 2,
296
+ handle_side
297
+ * (self.body_half_size[1] + self.handle_length / 2),
298
+ handle_z,
299
+ ),
300
+ geom_quats=(1, 0, 0, 0),
301
+ geom_sizes=side_bar_size,
302
+ geom_names=name,
303
+ geom_rgbas=None if self.use_texture else rgba,
304
+ geom_materials=f"handle{i}_mat" if self.use_texture else None,
305
+ geom_frictions=(self.handle_friction, 0.005, 0.0001),
306
+ density=self.density,
307
+ )
308
+ # Add relevant site
309
+ handle_site = self.get_site_attrib_template()
310
+ handle_name = f"handle{i}"
311
+ handle_site.update(
312
+ {
313
+ "name": handle_name,
314
+ "pos": array_to_string(
315
+ handle_center - handle_side * np.array([0, 0.005, 0])
316
+ ),
317
+ "size": "0.005",
318
+ "rgba": rgba,
319
+ }
320
+ )
321
+ site_attrs.append(handle_site)
322
+ # Add to important sites
323
+ self._important_sites[f"handle{i}"] = self.naming_prefix + handle_name
324
+
325
+ # Add pot body site
326
+ pot_site = self.get_site_attrib_template()
327
+ center_name = "center"
328
+ pot_site.update(
329
+ {
330
+ "name": center_name,
331
+ "size": "0.005",
332
+ }
333
+ )
334
+ site_attrs.append(pot_site)
335
+ # Add to important sites
336
+ self._important_sites["center"] = self.naming_prefix + center_name
337
+
338
+ # Add back in base args and site args
339
+ obj_args.update(base_args)
340
+ obj_args["sites"] = site_attrs # All sites are part of main (top) body
341
+
342
+ # Return this dict
343
+ return obj_args
344
+
345
+ @property
346
+ def handle_distance(self):
347
+
348
+ """
349
+ Calculates how far apart the handles are
350
+
351
+ Returns:
352
+ float: handle distance
353
+ """
354
+ return self.body_half_size[1] * 2 + self.handle_length * 2
355
+
356
+ @property
357
+ def handle0_geoms(self):
358
+ """
359
+ Returns:
360
+ list of str: geom names corresponding to handle0 (green handle)
361
+ """
362
+ return self.correct_naming(self._handle0_geoms)
363
+
364
+ @property
365
+ def handle1_geoms(self):
366
+ """
367
+ Returns:
368
+ list of str: geom names corresponding to handle1 (blue handle)
369
+ """
370
+ return self.correct_naming(self._handle1_geoms)
371
+
372
+ @property
373
+ def handle_geoms(self):
374
+ """
375
+ Returns:
376
+ list of str: geom names corresponding to both handles
377
+ """
378
+ return self.handle0_geoms + self.handle1_geoms
379
+
380
+ @property
381
+ def important_sites(self):
382
+ """
383
+ Returns:
384
+ dict: In addition to any default sites for this object, also provides the following entries
385
+
386
+ :`'handle0'`: Name of handle0 location site
387
+ :`'handle1'`: Name of handle1 location site
388
+ """
389
+ # Get dict from super call and add to it
390
+ dic = super().important_sites
391
+ dic.update(self._important_sites)
392
+ return dic
393
+
394
+ @property
395
+ def bottom_offset(self):
396
+ return np.array([0, 0, -1 * self.body_half_size[2]])
397
+
398
+ @property
399
+ def top_offset(self):
400
+ return np.array([0, 0, self.body_half_size[2]])
401
+
402
+ @property
403
+ def horizontal_radius(self):
404
+ return np.sqrt(2) * (max(self.body_half_size) + self.handle_length)
third_party/robocasa/robocasa/models/objects/composite/ring_tripod.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import CompositeObject
4
+ from robosuite.utils.mjcf_utils import add_to_dict
5
+ from robosuite.utils.mjcf_utils import CustomMaterial
6
+ import robosuite.utils.transform_utils as T
7
+
8
+
9
+ class RingTripodObject(CompositeObject):
10
+ """
11
+ Generates a tripod base with a small ring for threading a needle through it (used in Threading task)
12
+
13
+ Args:
14
+ name (str): Name of this RingTripod object
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ name,
20
+ ):
21
+
22
+ ### TODO: make this object more general (with more args and configuration options) later ###
23
+
24
+ # Set object attributes
25
+ self._name = name
26
+ self.tripod_mat_name = "lightwood_mat"
27
+
28
+ # Other private attributes
29
+ self._important_sites = {}
30
+
31
+ # Create dictionary of values to create geoms for composite object and run super init
32
+ super().__init__(**self._get_geom_attrs())
33
+
34
+ # Define materials we want to use for this object
35
+ tex_attrib = {
36
+ "type": "cube",
37
+ }
38
+ mat_attrib = {
39
+ "texrepeat": "1 1",
40
+ "specular": "0.4",
41
+ "shininess": "0.1",
42
+ }
43
+ tripod_mat = CustomMaterial(
44
+ texture="WoodLight",
45
+ tex_name="lightwood",
46
+ mat_name="lightwood_mat",
47
+ tex_attrib=tex_attrib,
48
+ mat_attrib=mat_attrib,
49
+ )
50
+ self.append_material(tripod_mat)
51
+
52
+ def _get_geom_attrs(self):
53
+ """
54
+ Creates geom elements that will be passed to superclass CompositeObject constructor
55
+
56
+ Returns:
57
+ dict: args to be used by CompositeObject to generate geoms
58
+ """
59
+ # Initialize dict of obj args that we'll pass to the CompositeObject constructor
60
+ total_size = (0.05, 0.05, 0.1)
61
+ base_args = {
62
+ "total_size": total_size,
63
+ "name": self.name,
64
+ "locations_relative_to_center": False,
65
+ "obj_types": "all",
66
+ "density": 100.0,
67
+ # NOTE: this lower value of solref allows the thin hole wall to avoid penetration through it
68
+ "solref": (0.02, 1.0),
69
+ "solimp": (0.9, 0.95, 0.001),
70
+ }
71
+ obj_args = {}
72
+
73
+ # pattern for threading ring
74
+ unit_size = [0.005, 0.002, 0.002]
75
+ pattern = np.ones((6, 1, 6))
76
+ for i in range(1, 5):
77
+ pattern[i][0][1:5] = np.zeros(4)
78
+ ring_size = [
79
+ unit_size[0] * pattern.shape[1],
80
+ unit_size[1] * pattern.shape[2],
81
+ unit_size[2] * pattern.shape[0],
82
+ ]
83
+ self.ring_size = np.array(ring_size)
84
+
85
+ # ring offset for where the ring is located relative to the (0, 0, 0) corner
86
+ ring_offset = [
87
+ total_size[0] - ring_size[0],
88
+ total_size[1] - ring_size[1],
89
+ 2.0 * (total_size[2] - ring_size[2]),
90
+ ]
91
+
92
+ # RING-GEOMS: use the pattern to instantiate geoms corresponding to the threading ring
93
+ nz, nx, ny = pattern.shape
94
+ self.num_ring_geoms = 0
95
+ for k in range(nz):
96
+ for i in range(nx):
97
+ for j in range(ny):
98
+ if pattern[k, i, j] > 0:
99
+ add_to_dict(
100
+ dic=obj_args,
101
+ geom_types="box",
102
+ # needle geom needs to be offset from boundary in (x, z)
103
+ geom_locations=(
104
+ (i * 2.0 * unit_size[0]) + ring_offset[0],
105
+ (j * 2.0 * unit_size[1]) + ring_offset[1],
106
+ (k * 2.0 * unit_size[2]) + ring_offset[2],
107
+ ),
108
+ geom_quats=(1, 0, 0, 0),
109
+ geom_sizes=tuple(unit_size),
110
+ geom_names="ring_{}".format(self.num_ring_geoms),
111
+ geom_rgbas=None,
112
+ geom_materials=self.tripod_mat_name,
113
+ # make the ring low friction to ensure easy insertion
114
+ geom_frictions=(0.3, 5e-3, 1e-4),
115
+ )
116
+ self.num_ring_geoms += 1
117
+
118
+ # TRIPOD-GEOMS: legs of the tripod
119
+ tripod_capsule_r = 0.01
120
+ tripod_capsule_h = 0.03
121
+ tripod_geom_locations = [
122
+ (0.0, 0.0, 0.0),
123
+ (0.0, 2.0 * total_size[1] - 2.0 * tripod_capsule_r, 0.0),
124
+ (
125
+ 2.0 * total_size[0] - 2.0 * tripod_capsule_r,
126
+ total_size[1] - tripod_capsule_r,
127
+ 0.0,
128
+ ),
129
+ ]
130
+ # rotate the legs to resemble a tripod
131
+ tripod_center = np.array([total_size[0], total_size[1], 0.0])
132
+ xy_offset = np.array([tripod_capsule_r, tripod_capsule_r, 0.0])
133
+ rotation_angle = -np.pi / 6.0 # 30 degrees
134
+ tripod_geom_quats = []
135
+ for i in range(3):
136
+ capsule_loc = np.array(tripod_geom_locations[i]) + xy_offset
137
+ capsule_loc[2] = 0.0 # only care about location in x-y plane
138
+ vec_to_center = tripod_center - capsule_loc
139
+ vec_to_center = vec_to_center / np.linalg.norm(vec_to_center)
140
+ # cross-product with z unit vector to get vector to rotate about
141
+ rot_vec = np.cross(vec_to_center, np.array([0.0, 0.0, 1.0]))
142
+ rot_quat = T.mat2quat(
143
+ T.rotation_matrix(angle=rotation_angle, direction=rot_vec)
144
+ )
145
+ tripod_geom_quats.append(T.convert_quat(rot_quat, to="wxyz"))
146
+
147
+ for i in range(3):
148
+ add_to_dict(
149
+ dic=obj_args,
150
+ geom_types="capsule",
151
+ geom_locations=tripod_geom_locations[i],
152
+ geom_quats=tripod_geom_quats[i],
153
+ geom_sizes=(tripod_capsule_r, tripod_capsule_h),
154
+ geom_names="tripod_{}".format(i),
155
+ geom_rgbas=None,
156
+ geom_materials=self.tripod_mat_name,
157
+ geom_frictions=None,
158
+ )
159
+
160
+ # POST-GEOMS: mounted base + post
161
+ base_thickness = 0.005
162
+ post_size = 0.005
163
+ post_geom_sizes = [
164
+ (total_size[0], total_size[1], base_thickness),
165
+ (
166
+ post_size,
167
+ post_size,
168
+ total_size[2]
169
+ - ring_size[2]
170
+ - base_thickness
171
+ - tripod_capsule_r
172
+ - tripod_capsule_h,
173
+ ),
174
+ ]
175
+ post_geom_locations = [
176
+ (0.0, 0.0, 2.0 * (tripod_capsule_r + tripod_capsule_h)),
177
+ (
178
+ total_size[0] - post_size,
179
+ total_size[1] - post_size,
180
+ 2.0 * (tripod_capsule_r + tripod_capsule_h + base_thickness),
181
+ ),
182
+ ]
183
+ for i in range(2):
184
+ add_to_dict(
185
+ dic=obj_args,
186
+ geom_types="box",
187
+ geom_locations=post_geom_locations[i],
188
+ geom_quats=(1, 0, 0, 0),
189
+ geom_sizes=post_geom_sizes[i],
190
+ geom_names="post_{}".format(i),
191
+ geom_rgbas=None,
192
+ geom_materials=self.tripod_mat_name,
193
+ geom_frictions=None,
194
+ )
195
+
196
+ # Add back in base args and site args
197
+ obj_args.update(base_args)
198
+
199
+ # Return this dict
200
+ return obj_args
third_party/robocasa/robocasa/models/objects/composite_body/__init__.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from .cup import CupObject
2
+ from .coffee_machine import CoffeeMachineObject
3
+ from .stacked_cylinder import StackedCylinderObject
4
+ from .inverse_stacked_cylinder import InverseStackedCylinderObject
5
+ from .stacked_box import StackedBoxObject
6
+ from .sliding_box import SlidingBoxObject
7
+ from .bin_with_handles import BinWithHandles
8
+ from .spray_bottle import SprayBottleObject
third_party/robocasa/robocasa/models/objects/composite_body/bin_with_handles.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject, Bin
2
+ import numpy as np
3
+
4
+ import robosuite.utils.transform_utils as T
5
+ from robosuite.utils.mjcf_utils import array_to_string
6
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
7
+
8
+
9
+ class BinWithHandles(CompositeBodyObject):
10
+ """
11
+ Bin with simple square handles on each side.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ name,
17
+ bin_size,
18
+ bin_wall_thickness,
19
+ bin_transparent_walls,
20
+ bin_upside_down,
21
+ center_handle_size,
22
+ adjacent_handle_size,
23
+ joints="default",
24
+ rgba=(0.2, 0.1, 0.0, 1.0),
25
+ material=None,
26
+ density=1000.0,
27
+ friction=None,
28
+ ):
29
+
30
+ # Object properties
31
+
32
+ # FULL size of bin
33
+ self.bin_size = list(bin_size)
34
+ self.bin_wall_thickness = bin_wall_thickness
35
+ self.bin_transparent_walls = bin_transparent_walls
36
+ self.bin_upside_down = bin_upside_down
37
+
38
+ # half-sizes of box geom used for center part of handle (which you grab)
39
+ self.center_handle_size = list(center_handle_size)
40
+
41
+ # half-sizes of box geoms used for adjacent parts of handle (not grabbed)
42
+ self.adjacent_handle_size = list(adjacent_handle_size)
43
+
44
+ # Create objects
45
+ objects = []
46
+ object_locations = []
47
+ object_quats = []
48
+ object_parents = []
49
+
50
+ # bin
51
+ self.bin = Bin(
52
+ name="bin",
53
+ bin_size=self.bin_size,
54
+ wall_thickness=self.bin_wall_thickness,
55
+ transparent_walls=self.bin_transparent_walls,
56
+ rgba=rgba,
57
+ material=material,
58
+ density=density,
59
+ friction=friction,
60
+ upside_down=bin_upside_down,
61
+ )
62
+ objects.append(self.bin)
63
+ object_locations.append([0.0, 0.0, 0.0])
64
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
65
+ object_parents.append(None)
66
+
67
+ # handles on each side
68
+
69
+ left_handle_1_loc = [
70
+ 0.0,
71
+ -(
72
+ self.bin_size[1] / 2.0
73
+ + 2.0 * self.adjacent_handle_size[1]
74
+ + self.center_handle_size[1]
75
+ ),
76
+ 0.0,
77
+ ]
78
+ left_handle_1_size = self.center_handle_size
79
+
80
+ left_handle_2_loc = [
81
+ (self.center_handle_size[0] - self.adjacent_handle_size[0]),
82
+ -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]),
83
+ 0.0,
84
+ ]
85
+ left_handle_2_size = self.adjacent_handle_size
86
+
87
+ left_handle_3_loc = [
88
+ -(self.center_handle_size[0] - self.adjacent_handle_size[0]),
89
+ -(self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]),
90
+ 0.0,
91
+ ]
92
+ left_handle_3_size = self.adjacent_handle_size
93
+
94
+ right_handle_1_loc = [
95
+ 0.0,
96
+ (
97
+ self.bin_size[1] / 2.0
98
+ + 2.0 * self.adjacent_handle_size[1]
99
+ + self.center_handle_size[1]
100
+ ),
101
+ 0.0,
102
+ ]
103
+ right_handle_1_size = self.center_handle_size
104
+
105
+ right_handle_2_loc = [
106
+ (self.center_handle_size[0] - self.adjacent_handle_size[0]),
107
+ (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]),
108
+ 0.0,
109
+ ]
110
+ right_handle_2_size = self.adjacent_handle_size
111
+
112
+ right_handle_3_loc = [
113
+ -(self.center_handle_size[0] - self.adjacent_handle_size[0]),
114
+ (self.bin_size[1] / 2.0 + self.adjacent_handle_size[1]),
115
+ 0.0,
116
+ ]
117
+ right_handle_3_size = self.adjacent_handle_size
118
+
119
+ handle_locs = [
120
+ left_handle_1_loc,
121
+ left_handle_2_loc,
122
+ left_handle_3_loc,
123
+ right_handle_1_loc,
124
+ right_handle_2_loc,
125
+ right_handle_3_loc,
126
+ ]
127
+ handle_sizes = [
128
+ left_handle_1_size,
129
+ left_handle_2_size,
130
+ left_handle_3_size,
131
+ right_handle_1_size,
132
+ right_handle_2_size,
133
+ right_handle_3_size,
134
+ ]
135
+ handle_ind = 1
136
+ for b_loc, b_size in zip(handle_locs, handle_sizes):
137
+ this_handle = BoxObject(
138
+ name="handle_{}".format(handle_ind),
139
+ size=b_size,
140
+ rgba=rgba,
141
+ material=material,
142
+ density=density,
143
+ friction=friction,
144
+ joints=None,
145
+ )
146
+ objects.append(this_handle)
147
+ object_locations.append(b_loc)
148
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
149
+ object_parents.append(None)
150
+ handle_ind += 1
151
+
152
+ # Run super init
153
+ super().__init__(
154
+ name=name,
155
+ objects=objects,
156
+ object_locations=object_locations,
157
+ object_quats=object_quats,
158
+ object_parents=object_parents,
159
+ joints=joints,
160
+ # total_size=body_total_size,
161
+ # locations_relative_to_corner=True,
162
+ )
third_party/robocasa/robocasa/models/objects/composite_body/coffee_machine.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject
2
+ from robocasa.models.objects.composite_body.cup import (
3
+ CupObject,
4
+ )
5
+ from robocasa.models.objects.xml_objects import (
6
+ CoffeeMachineBodyObject,
7
+ CoffeeMachineLidObject,
8
+ CoffeeMachineBaseObject,
9
+ )
10
+ import numpy as np
11
+
12
+ from robosuite.utils.mjcf_utils import array_to_string
13
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
14
+
15
+
16
+ class CoffeeMachineObject(CompositeBodyObject):
17
+ """
18
+ Coffee machine object with a lid fixed on a hinge joint.
19
+ """
20
+
21
+ def __init__(
22
+ self,
23
+ name,
24
+ add_cup=True,
25
+ pod_holder_friction=None,
26
+ joints="default",
27
+ density=1000.0,
28
+ ):
29
+
30
+ # pieces of the coffee machine
31
+ body = CoffeeMachineBodyObject(name="body")
32
+ body_size = body.get_bounding_box_half_size()
33
+ body_location = [0.0, 0.0, 0.0]
34
+
35
+ lid = CoffeeMachineLidObject(name="lid")
36
+ lid_size = self.lid_size = lid.get_bounding_box_half_size()
37
+ # add tolerance to allow lid to open fully
38
+ lid_location = [
39
+ body_size[0] - lid_size[0],
40
+ 2.0 * body_size[1] + 0.01,
41
+ 2.0 * (body_size[2] - lid_size[2]) + 0.005,
42
+ ]
43
+
44
+ # add in hinge joint to lid
45
+ hinge_pos = [0.0, -lid_size[1], 0.0]
46
+ hinge_joint = dict(
47
+ type="hinge",
48
+ axis="1 0 0",
49
+ pos=array_to_string(hinge_pos),
50
+ limited="true",
51
+ range="{} {}".format(0, 2.0 * np.pi / 3.0),
52
+ damping="0.005",
53
+ )
54
+ body_joints = dict(
55
+ lid_main=[hinge_joint]
56
+ ) # note: "main" gets appended to body name
57
+ lid = CoffeeMachineLidObject(name="lid")
58
+
59
+ base = CoffeeMachineBaseObject(name="base")
60
+ base_size = base.get_bounding_box_half_size()
61
+ base_location = [body_size[0] - base_size[0], 2.0 * body_size[1], 0.0]
62
+
63
+ pod_holder_holder = BoxObject(
64
+ name="pod_holder_holder",
65
+ size=[
66
+ 0.01,
67
+ # tolerance for having the lid stick out a little from the holder
68
+ 0.9 * (lid_size[1] - lid_size[0]),
69
+ 0.005,
70
+ ],
71
+ rgba=[0.839, 0.839, 0.839, 1], # silver
72
+ joints=None,
73
+ )
74
+ pod_holder_holder_size = pod_holder_holder.get_bounding_box_half_size()
75
+ pod_holder_holder_location = [
76
+ body_size[0] - pod_holder_holder_size[0],
77
+ 2.0 * body_size[1],
78
+ # put right underneath lid
79
+ 2.0 * (body_size[2] - lid_size[2] - pod_holder_holder_size[2]),
80
+ ]
81
+
82
+ pod_holder = CupObject(
83
+ name="pod_holder",
84
+ outer_cup_radius=lid_size[0],
85
+ inner_cup_radius=0.028,
86
+ cup_height=0.028,
87
+ cup_ngeoms=64, # 8,
88
+ cup_base_height=0.005,
89
+ cup_base_offset=0.002,
90
+ add_handle=False,
91
+ rgba=[1, 0, 0, 1],
92
+ density=density,
93
+ joints=None,
94
+ friction=pod_holder_friction,
95
+ )
96
+ pod_holder_size = self.pod_holder_size = pod_holder.get_bounding_box_half_size()
97
+ # pod_holder_size = self.pod_holder_size = np.array([0.0295, 0.0295, 0.028 ])
98
+ pod_holder_location = [
99
+ body_size[0] - pod_holder_size[0],
100
+ 2.0 * (body_size[1] + pod_holder_holder_size[1]),
101
+ # put right underneath lid
102
+ 2.0 * (body_size[2] - lid_size[2] - pod_holder_size[2]),
103
+ ]
104
+
105
+ total_size = [
106
+ body_size[0],
107
+ body_size[1] + base_size[1],
108
+ body_size[2],
109
+ ]
110
+
111
+ objects = [
112
+ body,
113
+ lid,
114
+ base,
115
+ pod_holder_holder,
116
+ pod_holder,
117
+ ]
118
+
119
+ object_locations = [
120
+ body_location,
121
+ lid_location,
122
+ base_location,
123
+ pod_holder_holder_location,
124
+ pod_holder_location,
125
+ ]
126
+
127
+ object_quats = [
128
+ [0.0, 0.0, 0.0, 1.0], # z-rotate body and base by 180
129
+ [1.0, 0.0, 0.0, 0.0],
130
+ [0.0, 0.0, 0.0, 1.0],
131
+ [1.0, 0.0, 0.0, 0.0],
132
+ [1.0, 0.0, 0.0, 0.0],
133
+ ]
134
+
135
+ # add a rigidly mounted cup to the base
136
+ self.add_cup = add_cup
137
+ if self.add_cup:
138
+ cup = CupObject(
139
+ name="cupppp",
140
+ outer_cup_radius=0.03,
141
+ inner_cup_radius=0.025,
142
+ cup_height=0.025,
143
+ cup_ngeoms=64, # 8,
144
+ cup_base_height=0.005,
145
+ cup_base_offset=0.005,
146
+ add_handle=True,
147
+ handle_outer_radius=0.015,
148
+ handle_inner_radius=0.010,
149
+ handle_thickness=0.003,
150
+ handle_ngeoms=64,
151
+ rgba=[0.839, 0.839, 0.839, 1],
152
+ density=1000.0,
153
+ joints=None,
154
+ )
155
+ cup_total_size = cup.get_bounding_box_half_size()
156
+ # cup_total_size = np.array([0.03 , 0.045, 0.025])
157
+ objects.append(cup)
158
+ object_locations.append(
159
+ [
160
+ body_size[0] - cup_total_size[0],
161
+ 2.0 * (body_size[1] + pod_holder_holder_size[1])
162
+ + pod_holder_size[1]
163
+ - cup_total_size[1],
164
+ 2.0 * base_size[2],
165
+ ]
166
+ )
167
+ rot_angle = -np.pi / 2.0
168
+ object_quats.append([np.cos(rot_angle / 2), 0, 0, np.sin(rot_angle / 2)])
169
+
170
+ object_parents = [None] * len(objects)
171
+
172
+ """
173
+ Variables to compare:
174
+
175
+ objects
176
+ [<robosuite.models.objects.xml_objects.CoffeeMachineBodyObject at 0x10f0f7640>,
177
+ <robosuite.models.objects.xml_objects.CoffeeMachineLidObject at 0x10f0f7c10>,
178
+ <robosuite.models.objects.xml_objects.CoffeeMachineBaseObject at 0x10f0f7190>,
179
+ <robosuite.models.objects.generated_objects.BoxObject at 0x10f0f7d90>,
180
+ <robosuite.models.objects.generated_objects.CupObject at 0x10f0f71f0>,
181
+ <robosuite.models.objects.generated_objects.CupObject at 0x10f0f7070>]
182
+
183
+ object_locations
184
+ [[0.0, 0.0, 0.0],
185
+ [0.056999999999999995, 0.21100000000000002, 0.20700000000000002],
186
+ [0.04449999999999999, 0.201, 0.0],
187
+ [0.0765, 0.201, 0.192],
188
+ [0.056999999999999995, 0.22710000000000002, 0.14600000000000002],
189
+ [0.056499999999999995, 0.21160000000000007, 0.01]]
190
+
191
+ object_quats
192
+ [[0.0, 0.0, 0.0, 1.0],
193
+ [1.0, 0.0, 0.0, 0.0],
194
+ [0.0, 0.0, 0.0, 1.0],
195
+ [1.0, 0.0, 0.0, 0.0],
196
+ [1.0, 0.0, 0.0, 0.0],
197
+ [0.7071067811865476, 0, 0, -0.7071067811865475]]
198
+
199
+ body_size
200
+ array([0.0865, 0.1005, 0.1105])
201
+
202
+ lid_size
203
+ array([0.0295, 0.044 , 0.0095])
204
+
205
+ lid_location
206
+ [0.056999999999999995, 0.21100000000000002, 0.20700000000000002]
207
+
208
+ base_size
209
+ array([0.042, 0.05 , 0.005])
210
+
211
+ base_location
212
+ [0.04449999999999999, 0.201, 0.0]
213
+
214
+ pod_holder_holder_size
215
+ array([0.01 , 0.01305, 0.005 ])
216
+
217
+ pod_holder_holder_location
218
+ [0.0765, 0.201, 0.192]
219
+
220
+ pod_holder_size
221
+ array([0.0295, 0.0295, 0.028 ])
222
+
223
+ pod_holder_location
224
+ [0.056999999999999995, 0.22710000000000002, 0.14600000000000002]
225
+
226
+ total_size
227
+ [0.0865, 0.15050000000000002, 0.1105]
228
+
229
+ cup.total_size
230
+ array([0.03 , 0.045, 0.025])
231
+ """
232
+
233
+ # Run super init
234
+ super().__init__(
235
+ name=name,
236
+ objects=objects,
237
+ object_locations=object_locations,
238
+ object_quats=object_quats,
239
+ object_parents=object_parents,
240
+ body_joints=body_joints, # make sure hinge joint is added
241
+ joints=joints,
242
+ # joints="default", # coffee machine can move
243
+ # joints=None, # coffee machine does not move
244
+ total_size=total_size,
245
+ locations_relative_to_corner=True,
246
+ )
third_party/robocasa/robocasa/models/objects/composite_body/cup.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import (
2
+ CompositeBodyObject,
3
+ BoxObject,
4
+ CylinderObject,
5
+ HollowCylinderObject,
6
+ )
7
+ import numpy as np
8
+
9
+ import robosuite.utils.transform_utils as T
10
+ from robosuite.utils.mjcf_utils import array_to_string
11
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
12
+
13
+
14
+ class CupObject(CompositeBodyObject):
15
+ """
16
+ Cup object with optional handle.
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ name,
22
+ outer_cup_radius=0.0425,
23
+ inner_cup_radius=0.03,
24
+ cup_height=0.05,
25
+ cup_ngeoms=8,
26
+ cup_base_height=0.01,
27
+ cup_base_offset=0.005,
28
+ add_handle=False,
29
+ handle_outer_radius=0.03,
30
+ handle_inner_radius=0.015,
31
+ handle_thickness=0.005,
32
+ handle_ngeoms=8,
33
+ joints="default",
34
+ rgba=None,
35
+ material=None,
36
+ density=100.0,
37
+ friction=None,
38
+ ):
39
+
40
+ # Object properties
41
+
42
+ # radius of the inner cup hole and entire cup
43
+ self.r1 = inner_cup_radius
44
+ self.r2 = outer_cup_radius
45
+
46
+ # number of geoms used to approximate the cylindrical shell
47
+ self.n = cup_ngeoms
48
+
49
+ # cup half-height
50
+ self.cup_height = cup_height
51
+
52
+ # cup base args
53
+ self.cup_base_height = cup_base_height
54
+ self.cup_base_offset = cup_base_offset
55
+
56
+ # handle args
57
+ self.add_handle = add_handle
58
+ self.handle_outer_radius = handle_outer_radius
59
+ self.handle_inner_radius = handle_inner_radius
60
+ self.handle_thickness = handle_thickness
61
+ self.handle_ngeoms = handle_ngeoms
62
+
63
+ # Create objects
64
+ objects = []
65
+ object_locations = []
66
+ object_quats = []
67
+ object_parents = []
68
+
69
+ # cup body
70
+ self.cup_body = HollowCylinderObject(
71
+ name="cup_body",
72
+ outer_radius=self.r2,
73
+ inner_radius=self.r1,
74
+ height=self.cup_height,
75
+ ngeoms=self.n,
76
+ rgba=rgba,
77
+ material=material,
78
+ density=density,
79
+ friction=friction,
80
+ )
81
+ objects.append(self.cup_body)
82
+ object_locations.append([0.0, 0.0, 0.0])
83
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
84
+ object_parents.append(None)
85
+
86
+ # cup base
87
+ self.cup_base = CylinderObject(
88
+ name="cup_base",
89
+ size=[self.cup_body.int_r, self.cup_base_height],
90
+ rgba=rgba,
91
+ material=material,
92
+ density=density,
93
+ solref=[0.02, 1.0],
94
+ solimp=[0.998, 0.998, 0.001],
95
+ joints=None,
96
+ )
97
+ objects.append(self.cup_base)
98
+ object_locations.append(
99
+ [0.0, 0.0, -self.cup_height + self.cup_base_height + self.cup_base_offset]
100
+ )
101
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
102
+ object_parents.append(None)
103
+
104
+ if self.add_handle:
105
+ # cup handle is a hollow half-cylinder
106
+ self.cup_handle = HollowCylinderObject(
107
+ name="cup_handle",
108
+ outer_radius=self.handle_outer_radius,
109
+ inner_radius=self.handle_inner_radius,
110
+ height=self.handle_thickness,
111
+ ngeoms=self.handle_ngeoms,
112
+ rgba=rgba,
113
+ material=material,
114
+ density=density,
115
+ make_half=True,
116
+ friction=friction,
117
+ )
118
+ # translate handle to right side of cup body, and rotate by +90 degrees about y-axis
119
+ # to orient the handle geoms on the cup body
120
+ objects.append(self.cup_handle)
121
+ object_locations.append(
122
+ [0.0, (self.cup_body.r2 + self.cup_handle.unit_box_width), 0.0]
123
+ )
124
+ object_quats.append(
125
+ T.convert_quat(
126
+ T.mat2quat(
127
+ T.rotation_matrix(angle=np.pi / 2.0, direction=[0.0, 1.0, 0.0])[
128
+ :3, :3
129
+ ]
130
+ ),
131
+ to="wxyz",
132
+ )
133
+ )
134
+ object_parents.append(None)
135
+
136
+ # total size of cup
137
+ body_total_size = [self.r2, self.r2, self.cup_height]
138
+ if self.add_handle:
139
+ body_total_size[1] += self.handle_outer_radius
140
+
141
+ """
142
+ To match on cup 1:
143
+
144
+ objects
145
+ [<robosuite.models.objects.generated_objects.HollowCylinderObject at 0x112881370>,
146
+ <robosuite.models.objects.generated_objects.CylinderObject at 0x112881c40>]
147
+
148
+ body_total_size
149
+ [0.0295, 0.0295, 0.028]
150
+
151
+ object_locations
152
+ [[0.0, 0.0, 0.0], [0.0, 0.0, -0.020999999999999998]]
153
+
154
+ object_quats
155
+ [[1.0, 0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0]]
156
+
157
+
158
+ To match on cup 2:
159
+
160
+ objects
161
+ [<robosuite.models.objects.generated_objects.HollowCylinderObject at 0x113e2b0d0>,
162
+ <robosuite.models.objects.generated_objects.CylinderObject at 0x113e2bbe0>,
163
+ <robosuite.models.objects.generated_objects.HollowCylinderObject at 0x113e2b040>]
164
+
165
+ body_total_size
166
+ [0.03, 0.045, 0.025]
167
+
168
+ object_locations
169
+ [[0.0, 0.0, 0.0], [0.0, 0.0, -0.015], [0.0, 0.03073601511491127, 0.0]]
170
+
171
+ object_quats
172
+ [[1.0, 0.0, 0.0, 0.0],
173
+ [1.0, 0.0, 0.0, 0.0],
174
+ array([ 0.70710677, -0. , 0.70710677, -0. ], dtype=float32)]
175
+ """
176
+
177
+ # Run super init
178
+ super().__init__(
179
+ name=name,
180
+ objects=objects,
181
+ object_locations=object_locations,
182
+ object_quats=object_quats,
183
+ object_parents=object_parents,
184
+ joints=joints,
185
+ total_size=body_total_size,
186
+ # locations_relative_to_corner=True,
187
+ )
third_party/robocasa/robocasa/models/objects/composite_body/inverse_stacked_cylinder.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import (
2
+ CompositeBodyObject,
3
+ BoxObject,
4
+ CylinderObject,
5
+ HollowCylinderObject,
6
+ )
7
+ import numpy as np
8
+
9
+ import robosuite.utils.transform_utils as T
10
+ from robosuite.utils.mjcf_utils import array_to_string
11
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
12
+
13
+
14
+ class InverseStackedCylinderObject(CompositeBodyObject):
15
+ """
16
+ Inverse of stacked cylinder object, where the top piece is a hollow cylinder object
17
+ and the bottom piece is a cylinder object. Optionally add a square base for stability.
18
+ """
19
+
20
+ def __init__(
21
+ self,
22
+ name,
23
+ radius_1,
24
+ radius_2,
25
+ height_1,
26
+ height_2,
27
+ ngeoms=64,
28
+ joints="default",
29
+ rgba=None,
30
+ material=None,
31
+ density=100.0,
32
+ friction=None,
33
+ square_base_width=None,
34
+ square_base_height=None,
35
+ ):
36
+
37
+ # Object properties
38
+
39
+ # radius of first (bottom) cylinder and inner radius of second (top) hollow cylinder
40
+ self.r1 = radius_1
41
+ self.r2 = radius_2
42
+
43
+ # half-height of first (bottom) cylinder and second (top) hollow cylinder
44
+ self.h1 = height_1
45
+ self.h2 = height_2
46
+
47
+ # num geoms to approximate the hollow cylinder
48
+ self.ngeoms = ngeoms
49
+
50
+ # whether to add square base
51
+ self.add_square_base = (square_base_width is not None) and (
52
+ square_base_height is not None
53
+ )
54
+
55
+ # half-width and half-height for square base
56
+ self.square_base_width = square_base_width
57
+ self.square_base_height = square_base_height
58
+
59
+ # Create objects
60
+ objects = []
61
+ object_locations = []
62
+ object_quats = []
63
+ object_parents = []
64
+
65
+ # NOTE: we will place the object frame at the vertical center of the two stacked cylinders
66
+ z_center = (self.h1 + self.h2) / 2.0
67
+ c1_offset = self.h1 - z_center
68
+ c2_offset = 2.0 * self.h1 + self.h2 - z_center
69
+
70
+ # first (bottom) cylinder
71
+ self.cylinder_1 = CylinderObject(
72
+ name="cylinder_1",
73
+ size=[self.r1, self.h1],
74
+ rgba=rgba,
75
+ material=material,
76
+ density=density,
77
+ friction=friction,
78
+ solref=[0.02, 1.0],
79
+ # solimp=[0.998, 0.998, 0.001],
80
+ solimp=[0.9, 0.95, 0.001],
81
+ joints=None,
82
+ )
83
+ objects.append(self.cylinder_1)
84
+ object_locations.append([0.0, 0.0, c1_offset])
85
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
86
+ object_parents.append(None)
87
+
88
+ # second (top) hollow cylinder
89
+ self.cylinder_2 = HollowCylinderObject(
90
+ name="cylinder_2",
91
+ outer_radius=self.r1, # match radius of first cylinder
92
+ inner_radius=self.r2,
93
+ height=self.h2,
94
+ ngeoms=self.ngeoms,
95
+ rgba=rgba,
96
+ material=material,
97
+ density=density,
98
+ friction=friction,
99
+ # TODO: maybe tune solimp and try (0.998, 0.998, 0.001)
100
+ solref=[0.02, 1.0],
101
+ solimp=[0.9, 0.95, 0.001],
102
+ # solimp=(0.998, 0.998, 0.001),
103
+ )
104
+ objects.append(self.cylinder_2)
105
+ object_locations.append([0.0, 0.0, c2_offset])
106
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
107
+ object_parents.append(None)
108
+
109
+ # # total size of object
110
+ # max_r = max(self.r1, self.r2)
111
+ # body_total_size = [max_r, max_r, self.h1 + self.h2]
112
+
113
+ if self.add_square_base:
114
+ # add square base underneath bottom cylinder
115
+ s1_offset = c1_offset - (self.square_base_height + self.h1)
116
+ self.square_base = BoxObject(
117
+ name="square_base",
118
+ size=[
119
+ self.square_base_width,
120
+ self.square_base_width,
121
+ self.square_base_height,
122
+ ],
123
+ rgba=rgba,
124
+ material=material,
125
+ )
126
+ objects.append(self.square_base)
127
+ object_locations.append([0.0, 0.0, s1_offset])
128
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
129
+ object_parents.append(None)
130
+
131
+ # Run super init
132
+ super().__init__(
133
+ name=name,
134
+ objects=objects,
135
+ object_locations=object_locations,
136
+ object_quats=object_quats,
137
+ object_parents=object_parents,
138
+ joints=joints,
139
+ # total_size=body_total_size,
140
+ # locations_relative_to_corner=True,
141
+ )
third_party/robocasa/robocasa/models/objects/composite_body/lightbulb.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import (
2
+ CompositeBodyObject,
3
+ BoxObject,
4
+ CylinderObject,
5
+ BallObject,
6
+ )
7
+ import numpy as np
8
+
9
+ import robosuite.utils.transform_utils as T
10
+ from robosuite.utils.mjcf_utils import array_to_string, new_site
11
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
12
+
13
+
14
+ class BallObjectWithSite(BallObject):
15
+ """
16
+ A ball object with a inner site (used for the bulb).
17
+ """
18
+
19
+ def _get_object_subtree(self):
20
+ # tree = super()._get_object_subtree()
21
+ tree = self._get_object_subtree_(ob_type="sphere")
22
+ site_element_attr = self.get_site_attrib_template()
23
+
24
+ site_element_attr["pos"] = "0 0 0.1"
25
+ site_element_attr["name"] = "center_site"
26
+ site_element_attr["size"] = "{} {} {}".format(
27
+ 2.0 * self.size[0], 2.0 * self.size[0], 2.0 * self.size[0]
28
+ )
29
+ site_element_attr["rgba"] = "1.0 0.0 0.0 1.0"
30
+ site_element_attr["group"] = "1"
31
+ # site_element_attr["rgba"] = "1.0 0.976 0.839 0.9"
32
+ # site_element_attr["rgba"] = "1.0 0.976 0.839 0.0"
33
+ tree.append(new_site(**site_element_attr))
34
+ return tree
35
+
36
+
37
+ class LightbulbObject(CompositeBodyObject):
38
+ """
39
+ A simple lightbulb constructed out of a base of alternating radius cylinders
40
+ and a sphere on top.
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ name,
46
+ radius_low,
47
+ radius_high,
48
+ cylinder_height,
49
+ num_cylinders,
50
+ sphere_radius,
51
+ joints="default",
52
+ density=100.0,
53
+ friction=None,
54
+ ):
55
+
56
+ # Object properties
57
+
58
+ # radii of alternating cylinders for base
59
+ self.radius_low = radius_low
60
+ self.radius_high = radius_high
61
+
62
+ # half-height of each cylinder
63
+ self.cylinder_height = cylinder_height
64
+
65
+ # number of cylinders for base
66
+ self.num_cylinders = num_cylinders
67
+
68
+ # radius of sphere at top
69
+ self.sphere_radius = sphere_radius
70
+
71
+ # toggle between translucent and yellow
72
+ self.translucent_rgba = (1.0, 1.0, 1.0, 0.3)
73
+ self.yellow_rgba = (1.0, 0.976, 0.839, 0.7)
74
+ # self.yellow_rgba = (0.0, 0.0, 0.0, 0.0)
75
+
76
+ # Create objects
77
+ objects = []
78
+ object_locations = []
79
+ object_quats = []
80
+ object_parents = []
81
+
82
+ # NOTE: we will place the object frame at the vertical center of all the stacked objects
83
+ self.z_center = (
84
+ (2.0 * self.cylinder_height) * self.num_cylinders + 2.0 * self.sphere_radius
85
+ ) / 2.0
86
+
87
+ metal = CustomMaterial(
88
+ texture="Metal",
89
+ tex_name="metal",
90
+ mat_name="MatMetal",
91
+ tex_attrib={"type": "cube"},
92
+ mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"},
93
+ )
94
+
95
+ # we will define all objects relative to the bottom of the object, and then subtract the z_center value
96
+ for cylinder_ind in range(self.num_cylinders):
97
+ r = self.radius_low if ((cylinder_ind % 2) == 0) else self.radius_high
98
+ cyl_obj = CylinderObject(
99
+ name="cylinder_{}".format(cylinder_ind),
100
+ size=[r, self.cylinder_height],
101
+ rgba=None,
102
+ material=metal,
103
+ density=density,
104
+ friction=friction,
105
+ solref=[0.02, 1.0],
106
+ solimp=[0.9, 0.95, 0.001],
107
+ joints=None,
108
+ )
109
+ objects.append(cyl_obj)
110
+ z_cyl = (2.0 * cylinder_ind + 1) * self.cylinder_height
111
+ object_locations.append([0.0, 0.0, z_cyl])
112
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
113
+ object_parents.append(None)
114
+
115
+ # then add translucent sphere at top
116
+ self.bulb = BallObject(
117
+ name="bulb",
118
+ size=[self.sphere_radius],
119
+ density=density,
120
+ friction=friction,
121
+ rgba=self.translucent_rgba,
122
+ material=None,
123
+ joints=None,
124
+ )
125
+ objects.append(self.bulb)
126
+ z_bulb = object_locations[-1][2] + self.cylinder_height + self.sphere_radius
127
+ object_locations.append([0.0, 0.0, z_bulb])
128
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
129
+ object_parents.append(None)
130
+
131
+ # do frame conversion from bottom of object to z_center
132
+ object_locations = [
133
+ [loc[0], loc[1], loc[2] - self.z_center] for loc in object_locations
134
+ ]
135
+
136
+ # add site that can be toggled to turn lightbulb on
137
+ sites = [
138
+ dict(
139
+ name="bulb_on",
140
+ pos=array_to_string(object_locations[-1]),
141
+ size="{}".format(0.95 * self.sphere_radius),
142
+ rgba=array_to_string(self.yellow_rgba),
143
+ )
144
+ ]
145
+
146
+ # Run super init
147
+ super().__init__(
148
+ name=name,
149
+ objects=objects,
150
+ object_locations=object_locations,
151
+ object_quats=object_quats,
152
+ object_parents=object_parents,
153
+ joints=joints,
154
+ sites=sites,
155
+ )
third_party/robocasa/robocasa/models/objects/composite_body/sliding_box.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import BoxObject, CompositeBodyObject, CylinderObject
4
+ from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string
5
+
6
+
7
+ class SlidingBoxObject(CompositeBodyObject):
8
+ """
9
+ An example object that demonstrates the CompositeBodyObject functionality. This object consists of two cube bodies
10
+ joined together by a slide joint allowing one box to slide on top of the other.
11
+
12
+ Args:
13
+ name (str): Name of this object
14
+
15
+ box1_size (3-array): (L, W, H) half-sizes for the first box
16
+
17
+ box2_size (3-array): (L, W, H) half-sizes for the second box
18
+
19
+ use_texture (bool): set True if using wood textures for the blocks
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ name,
25
+ box1_size=(0.1, 0.1, 0.02),
26
+ box2_size=(0.02, 0.02, 0.02),
27
+ use_texture=True,
28
+ ):
29
+ # Set box sizes
30
+ self.box1_size = np.array(box1_size)
31
+ self.box2_size = np.array(box2_size)
32
+
33
+ # Set box densities
34
+ self.box1_density = 10000.0
35
+ self.box2_density = 100.0
36
+
37
+ # Set texture attributes
38
+ self.use_texture = use_texture
39
+ self.box1_material = None
40
+ self.box2_material = None
41
+ self.box1_rgba = RED
42
+ self.box2_rgba = BLUE
43
+
44
+ # Define materials we want to use for this object
45
+ if self.use_texture:
46
+ # Remove RGBAs
47
+ self.box1_rgba = None
48
+ self.box2_rgba = None
49
+
50
+ # Set materials for each box
51
+ tex_attrib = {
52
+ "type": "cube",
53
+ }
54
+ mat_attrib = {
55
+ "texrepeat": "3 3",
56
+ "specular": "0.4",
57
+ "shininess": "0.1",
58
+ }
59
+ self.box1_material = CustomMaterial(
60
+ texture="WoodRed",
61
+ tex_name="box1_tex",
62
+ mat_name="box1_mat",
63
+ tex_attrib=tex_attrib,
64
+ mat_attrib=mat_attrib,
65
+ )
66
+ self.box2_material = CustomMaterial(
67
+ texture="WoodBlue",
68
+ tex_name="box2_tex",
69
+ mat_name="box2_mat",
70
+ tex_attrib=tex_attrib,
71
+ mat_attrib=mat_attrib,
72
+ )
73
+
74
+ # Create objects
75
+ objects = []
76
+ for i, (size, mat, rgba, density) in enumerate(
77
+ zip(
78
+ (self.box1_size, self.box2_size),
79
+ (self.box1_material, self.box2_material),
80
+ (self.box1_rgba, self.box2_rgba),
81
+ (self.box1_density, self.box2_density),
82
+ )
83
+ ):
84
+ objects.append(
85
+ BoxObject(
86
+ name=f"box{i + 1}",
87
+ size=size,
88
+ rgba=rgba,
89
+ material=mat,
90
+ )
91
+ )
92
+
93
+ # Define slide joint
94
+ rel_joint_pos = [0, 0, 0] # at second box
95
+ joint_lim = self.box1_size[1] - self.box2_size[1]
96
+ slide_joint = {
97
+ "name": "box_slide",
98
+ "type": "slide",
99
+ "axis": "0 1 0", # y-axis slide
100
+ "pos": array_to_string(rel_joint_pos),
101
+ "springref": "0",
102
+ "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio
103
+ "limited": "true",
104
+ "range": "{} {}".format(-joint_lim, joint_lim),
105
+ }
106
+
107
+ # Define positions -- second box should lie on top of first box
108
+ positions = [
109
+ np.zeros(3), # First box is centered at top-level body anyways
110
+ np.array([0, 0, self.box1_size[2] + self.box2_size[2]]),
111
+ ]
112
+
113
+ quats = [
114
+ None, # Default quaternion for box 1
115
+ None, # Default quaternion for box 2
116
+ ]
117
+
118
+ # Define parents -- which body each is aligned to
119
+ parents = [
120
+ None, # box 1 attached to top-level body
121
+ objects[0].root_body, # box 2 attached to box 1
122
+ ]
123
+
124
+ # Run super init
125
+ super().__init__(
126
+ name=name,
127
+ objects=objects,
128
+ object_locations=positions,
129
+ object_quats=quats,
130
+ object_parents=parents,
131
+ body_joints={objects[1].root_body: [slide_joint]},
132
+ )
third_party/robocasa/robocasa/models/objects/composite_body/socket.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject
2
+ import numpy as np
3
+
4
+ import robosuite.utils.transform_utils as T
5
+ from robosuite.utils.mjcf_utils import array_to_string
6
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
7
+ from .stacked_cylinder import StackedCylinderObject
8
+
9
+
10
+ class SocketObject(CompositeBodyObject):
11
+ """
12
+ Box geom connected to series of geoms with ball joints (wire) and connected to
13
+ cylinder representing plug.
14
+ """
15
+
16
+ def __init__(
17
+ self,
18
+ name,
19
+ joints="default",
20
+ rgba=None,
21
+ material=None,
22
+ density=100.0,
23
+ friction=None,
24
+ socket_base_size=(0.02, 0.02, 0.03),
25
+ wire_box_geom_size=(0.02, 0.005, 0.005),
26
+ wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0),
27
+ num_box_geoms_up=6,
28
+ num_box_geoms_left=2,
29
+ num_box_geoms_down=9,
30
+ merge_box_geoms=False,
31
+ merge_size=1,
32
+ cylinder_args=None,
33
+ ):
34
+
35
+ # Object properties
36
+
37
+ # box geom used for socket base
38
+ self.socket_base_size = socket_base_size
39
+
40
+ # box geoms used for wire
41
+ self.wire_box_geom_size = wire_box_geom_size
42
+ self.wire_box_geom_rgba = wire_box_geom_rgba
43
+
44
+ # wire parameters - number of geoms to use for up, left, and down portions
45
+ self.num_box_geoms_up = num_box_geoms_up
46
+ self.num_box_geoms_left = num_box_geoms_left
47
+ self.num_box_geoms_down = num_box_geoms_down
48
+
49
+ # if true, merge the box geoms along each direction of the wire into a single box geom
50
+ self.merge_box_geoms = merge_box_geoms
51
+
52
+ # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more
53
+ # than one box geom)
54
+ self.merge_size = merge_size
55
+
56
+ if cylinder_args is None:
57
+ # default cylinder args
58
+ cylinder_args = dict(
59
+ # bottom cylinder radius and half-height
60
+ radius_1=0.03,
61
+ height_1=0.075,
62
+ # top cylinder radius and half-height
63
+ radius_2=0.02,
64
+ height_2=0.025,
65
+ rgba=[0.839, 0.839, 0.839, 1],
66
+ density=1000.0,
67
+ # add square base
68
+ square_base_width=0.03,
69
+ square_base_height=0.005,
70
+ )
71
+ self.cylinder_args = dict(cylinder_args)
72
+ self.cylinder_args["joints"] = None
73
+
74
+ # materials
75
+ box_geom_material = CustomMaterial(
76
+ texture="Metal",
77
+ tex_name="metal",
78
+ mat_name="MatMetal",
79
+ tex_attrib={"type": "cube"},
80
+ mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"},
81
+ )
82
+ socket_material = CustomMaterial(
83
+ texture="WoodLight",
84
+ tex_name="lightwood",
85
+ mat_name="lightwood_mat",
86
+ tex_attrib={"type": "cube"},
87
+ mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"},
88
+ )
89
+
90
+ # params for ball joints used
91
+
92
+ # <joint name="J1" type="ball" pos="0 0 0" frictionloss="&friction;"/>
93
+ ball_joint_spec = {
94
+ "type": "ball",
95
+ "pos": "{} 0 0".format(self.wire_box_geom_size[0]),
96
+ "springref": "0",
97
+ "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio
98
+ "limited": "true",
99
+ "range": "0 {}".format(np.pi / 4),
100
+ }
101
+
102
+ # Create objects
103
+ objects = []
104
+ object_locations = []
105
+ object_quats = []
106
+ object_parents = []
107
+ object_joints = dict()
108
+
109
+ # NOTE: For absolute object locations (objects not defined relative to parent) we will use the socket base frame
110
+ # as a frame of reference, and add an offset from the center of the object (approximated via full width)
111
+ # to it.
112
+
113
+ # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base center
114
+ approx_full_width = self.num_box_geoms_left * (
115
+ 2.0 * self.wire_box_geom_size[0]
116
+ ) + (2.0 * self.socket_base_size[1])
117
+ approx_full_height = (self.num_box_geoms_down + 2) * (
118
+ 2.0 * self.wire_box_geom_size[0]
119
+ )
120
+
121
+ base_x_off = (
122
+ self.socket_base_size[0]
123
+ + (self.num_box_geoms_up) * (2.0 * self.wire_box_geom_size[0])
124
+ ) - (approx_full_height / 2.0)
125
+ base_y_off = (
126
+ self.num_box_geoms_left * self.wire_box_geom_size[0]
127
+ ) + self.socket_base_size[1]
128
+
129
+ # base of socket
130
+ self.socket_base = BoxObject(
131
+ name="stove_base",
132
+ size=list(self.socket_base_size),
133
+ rgba=rgba,
134
+ material=socket_material,
135
+ joints=None,
136
+ )
137
+ objects.append(self.socket_base)
138
+ object_locations.append([base_x_off, base_y_off, 0.0])
139
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
140
+ object_parents.append(None)
141
+
142
+ # chain above base
143
+ chain_ind = 0
144
+ up_chain_size = list(self.wire_box_geom_size)
145
+ num_geoms_iter = self.num_box_geoms_up - 1
146
+ if self.merge_box_geoms:
147
+ # only one big geom instead of chain of geoms
148
+ up_chain_size[0] *= self.num_box_geoms_up
149
+ up_chain_size[0] /= self.merge_size
150
+ # number of additional geoms to add
151
+ num_geoms_iter = self.merge_size - 1
152
+ chain_obj = BoxObject(
153
+ name="chain_{}".format(chain_ind),
154
+ size=list(up_chain_size),
155
+ rgba=list(self.wire_box_geom_rgba),
156
+ material=box_geom_material,
157
+ joints=None,
158
+ )
159
+ chain_ind += 1
160
+ objects.append(chain_obj)
161
+ object_locations.append(
162
+ [
163
+ base_x_off - (self.socket_base_size[0] + up_chain_size[0]),
164
+ base_y_off,
165
+ 0.0,
166
+ ]
167
+ )
168
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
169
+ object_parents.append(None)
170
+ if self.merge_box_geoms:
171
+ # add ball joint and make sure to place it at the edge of the geom
172
+ ball_joint = dict(ball_joint_spec)
173
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
174
+ ball_joint["pos"] = "{} 0 0".format(up_chain_size[0])
175
+ object_joints[chain_obj.root_body] = [ball_joint]
176
+
177
+ for i in range(num_geoms_iter):
178
+ chain_obj = BoxObject(
179
+ name="chain_{}".format(chain_ind),
180
+ size=list(up_chain_size),
181
+ rgba=list(self.wire_box_geom_rgba),
182
+ material=box_geom_material,
183
+ joints=None,
184
+ )
185
+ chain_ind += 1
186
+ parent = objects[-1].root_body
187
+ objects.append(chain_obj)
188
+ object_locations.append([-2.0 * up_chain_size[0], 0.0, 0.0])
189
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
190
+ object_parents.append(parent)
191
+
192
+ # add ball joint and make sure to place it at the edge of the geom
193
+ ball_joint = dict(ball_joint_spec)
194
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
195
+ ball_joint["pos"] = "{} 0 0".format(up_chain_size[0])
196
+ object_joints[chain_obj.root_body] = [ball_joint]
197
+
198
+ # add chain in left direction
199
+ rot_quat = T.convert_quat(
200
+ T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz"
201
+ )
202
+ left_chain_size = list(self.wire_box_geom_size)
203
+ num_geoms_iter = self.num_box_geoms_left - 1
204
+ if self.merge_box_geoms:
205
+ # only one big geom instead of chain of geoms
206
+ left_chain_size[0] *= self.num_box_geoms_left
207
+ # HACK: merge entire left chain since this side is small
208
+ left_merge_size = 1
209
+ left_chain_size[0] /= left_merge_size
210
+ # number of additional geoms to add
211
+ num_geoms_iter = left_merge_size - 1
212
+ chain_obj = BoxObject(
213
+ name="chain_{}".format(chain_ind),
214
+ size=list(left_chain_size),
215
+ rgba=list(self.wire_box_geom_rgba),
216
+ material=box_geom_material,
217
+ joints=None,
218
+ )
219
+ chain_ind += 1
220
+ parent = objects[-1].root_body
221
+ objects.append(chain_obj)
222
+ object_locations.append([-up_chain_size[0], -left_chain_size[0], 0.0])
223
+ object_quats.append(rot_quat)
224
+ object_parents.append(parent)
225
+
226
+ ball_joint = dict(ball_joint_spec)
227
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
228
+ ball_joint["pos"] = "{} 0 0".format(left_chain_size[0])
229
+ object_joints[chain_obj.root_body] = [ball_joint]
230
+
231
+ for i in range(num_geoms_iter):
232
+ chain_obj = BoxObject(
233
+ name="chain_{}".format(chain_ind),
234
+ size=list(left_chain_size),
235
+ rgba=list(self.wire_box_geom_rgba),
236
+ material=box_geom_material,
237
+ joints=None,
238
+ )
239
+ chain_ind += 1
240
+ parent = objects[-1].root_body
241
+ objects.append(chain_obj)
242
+ object_locations.append([-2.0 * left_chain_size[0], 0.0, 0.0])
243
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
244
+ object_parents.append(parent)
245
+
246
+ ball_joint = dict(ball_joint_spec)
247
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
248
+ ball_joint["pos"] = "{} 0 0".format(left_chain_size[0])
249
+ object_joints[chain_obj.root_body] = [ball_joint]
250
+
251
+ # add chain in downward direction
252
+ rot_quat = T.convert_quat(
253
+ T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz"
254
+ )
255
+ down_chain_size = list(self.wire_box_geom_size)
256
+ num_geoms_iter = self.num_box_geoms_down - 1
257
+ if self.merge_box_geoms:
258
+ # only one big geom instead of chain of geoms
259
+ down_chain_size[0] *= self.num_box_geoms_down
260
+ down_chain_size[0] /= self.merge_size
261
+ # number of additional geoms to add
262
+ num_geoms_iter = self.merge_size - 1
263
+ chain_obj = BoxObject(
264
+ name="chain_{}".format(chain_ind),
265
+ size=list(down_chain_size),
266
+ rgba=list(self.wire_box_geom_rgba),
267
+ material=box_geom_material,
268
+ joints=None,
269
+ )
270
+ chain_ind += 1
271
+ parent = objects[-1].root_body
272
+ objects.append(chain_obj)
273
+ object_locations.append([-left_chain_size[0], -down_chain_size[0], 0.0])
274
+ object_quats.append(rot_quat)
275
+ object_parents.append(parent)
276
+
277
+ ball_joint = dict(ball_joint_spec)
278
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
279
+ ball_joint["pos"] = "{} 0 0".format(down_chain_size[0])
280
+ object_joints[chain_obj.root_body] = [ball_joint]
281
+
282
+ for i in range(num_geoms_iter):
283
+ chain_obj = BoxObject(
284
+ name="chain_{}".format(chain_ind),
285
+ size=list(down_chain_size),
286
+ rgba=list(self.wire_box_geom_rgba),
287
+ material=box_geom_material,
288
+ joints=None,
289
+ )
290
+ chain_ind += 1
291
+ parent = objects[-1].root_body
292
+ objects.append(chain_obj)
293
+ object_locations.append([-2.0 * down_chain_size[0], 0.0, 0.0])
294
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
295
+ object_parents.append(parent)
296
+
297
+ ball_joint = dict(ball_joint_spec)
298
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
299
+ ball_joint["pos"] = "{} 0 0".format(down_chain_size[0])
300
+ object_joints[chain_obj.root_body] = [ball_joint]
301
+
302
+ # add cylinder object
303
+ self.cylinder_obj = StackedCylinderObject(
304
+ name="cylinder_obj",
305
+ **self.cylinder_args,
306
+ )
307
+
308
+ x_off = -(down_chain_size[0] + self.cylinder_obj.square_base_width)
309
+ y_off = 0.0
310
+ z_off = ((self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0) - down_chain_size[
311
+ 2
312
+ ]
313
+ parent = objects[-1].root_body
314
+ objects.append(self.cylinder_obj)
315
+ object_locations.append([x_off, y_off, z_off])
316
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
317
+ object_parents.append(parent)
318
+
319
+ # # add debug site to see object center
320
+ # sites = [
321
+ # dict(
322
+ # name="TMP",
323
+ # pos=array_to_string([0., 0., 0.]),
324
+ # size="{}".format(0.1),
325
+ # rgba=array_to_string([1., 0., 0., 1.]),
326
+ # )
327
+ # ]
328
+
329
+ # Run super init
330
+ super().__init__(
331
+ name=name,
332
+ objects=objects,
333
+ object_locations=object_locations,
334
+ object_quats=object_quats,
335
+ object_parents=object_parents,
336
+ joints=joints,
337
+ body_joints=object_joints,
338
+ # sites=sites,
339
+ )
third_party/robocasa/robocasa/models/objects/composite_body/spray_bottle.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.models.objects import (
4
+ BoxObject,
5
+ CompositeBodyObject,
6
+ CylinderObject,
7
+ ConeObject,
8
+ )
9
+ from robosuite.utils.mjcf_utils import BLUE, RED, CustomMaterial, array_to_string
10
+
11
+
12
+ class SprayBottleObject(CompositeBodyObject):
13
+ """
14
+ A spray bottle object where the trigger is modeled via a slide joint.
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ name,
20
+ base_cylinder_radius,
21
+ base_cylinder_height,
22
+ cone_outer_radius,
23
+ cone_inner_radius,
24
+ cone_height,
25
+ cone_ngeoms,
26
+ neck_height,
27
+ top_length,
28
+ top_thickness,
29
+ trigger_height,
30
+ trigger_width,
31
+ trigger_length,
32
+ joints="default",
33
+ rgba=None,
34
+ material=None,
35
+ density=100.0,
36
+ friction=None,
37
+ square_base_width=None,
38
+ square_base_height=None,
39
+ ):
40
+ # Sizes
41
+ self.base_cylinder_radius = base_cylinder_radius
42
+ self.base_cylinder_height = base_cylinder_height
43
+ self.cone_outer_radius = cone_outer_radius
44
+ self.cone_inner_radius = cone_inner_radius
45
+ self.cone_height = cone_height
46
+ self.cone_ngeoms = cone_ngeoms
47
+ self.neck_height = neck_height
48
+ self.top_length = top_length
49
+ self.top_thickness = top_thickness
50
+ self.trigger_height = trigger_height
51
+ self.trigger_width = trigger_width
52
+ self.trigger_length = trigger_length
53
+
54
+ # whether to add square base
55
+ self.add_square_base = (square_base_width is not None) and (
56
+ square_base_height is not None
57
+ )
58
+
59
+ # half-width and half-height for square base
60
+ self.square_base_width = square_base_width
61
+ self.square_base_height = square_base_height
62
+
63
+ assert (
64
+ self.top_length > self.cone_inner_radius
65
+ ), "top needs to stick out past neck"
66
+
67
+ # Create objects
68
+ objects = []
69
+ object_locations = []
70
+ object_quats = []
71
+ object_parents = []
72
+
73
+ # base cylinder
74
+ self.base_cylinder = CylinderObject(
75
+ name="base_cylinder",
76
+ size=[self.base_cylinder_radius, self.base_cylinder_height],
77
+ rgba=rgba,
78
+ material=material,
79
+ density=density,
80
+ friction=friction,
81
+ solref=[0.02, 1.0],
82
+ # solimp=[0.998, 0.998, 0.001],
83
+ solimp=[0.9, 0.95, 0.001],
84
+ joints=None,
85
+ )
86
+ objects.append(self.base_cylinder)
87
+ object_locations.append([0.0, 0.0, 0.0])
88
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
89
+ object_parents.append(None)
90
+
91
+ # cone that is part of neck
92
+ # z_cone = self.base_cylinder_height # cone frame is bottom center of cone
93
+ z_cone = self.base_cylinder_height + (self.cone_height / 2.0)
94
+ self.neck_cone = ConeObject(
95
+ name="neck_cone",
96
+ outer_radius=self.cone_outer_radius,
97
+ inner_radius=self.cone_inner_radius,
98
+ height=self.cone_height, # full height, not half-height
99
+ ngeoms=self.cone_ngeoms,
100
+ use_box=False,
101
+ rgba=rgba,
102
+ material=material,
103
+ density=density,
104
+ solref=(0.02, 1.0),
105
+ # solimp=[0.998, 0.998, 0.001],
106
+ solimp=(0.9, 0.95, 0.001),
107
+ friction=friction,
108
+ )
109
+ objects.append(self.neck_cone)
110
+ object_locations.append([0.0, 0.0, z_cone])
111
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
112
+ object_parents.append(None)
113
+
114
+ # cylinder that is part of neck
115
+ z_cyl = self.base_cylinder_height + self.cone_height + self.neck_height
116
+ self.neck_cylinder = CylinderObject(
117
+ name="neck_cylinder",
118
+ size=[self.cone_inner_radius, self.neck_height], # match cone radius
119
+ rgba=rgba,
120
+ material=material,
121
+ density=density,
122
+ friction=friction,
123
+ solref=[0.02, 1.0],
124
+ # solimp=[0.998, 0.998, 0.001],
125
+ solimp=[0.9, 0.95, 0.001],
126
+ joints=None,
127
+ )
128
+ objects.append(self.neck_cylinder)
129
+ object_locations.append([0.0, 0.0, z_cyl])
130
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
131
+ object_parents.append(None)
132
+
133
+ # top box object
134
+ box_x_off = -(self.top_length - self.cone_inner_radius)
135
+ box_z_off = z_cyl + self.neck_height + self.top_thickness
136
+ self.top_box = BoxObject(
137
+ name="top_box",
138
+ size=[self.top_length, self.cone_inner_radius, self.top_thickness],
139
+ density=density,
140
+ friction=friction,
141
+ rgba=rgba,
142
+ material=material,
143
+ joints=None,
144
+ )
145
+ objects.append(self.top_box)
146
+ object_locations.append([box_x_off, 0.0, box_z_off])
147
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
148
+ object_parents.append(None)
149
+
150
+ # trigger object, which is defined relative to top box object
151
+ trigger_x_off = -(
152
+ 0.5 * self.top_length
153
+ ) # place halfway along length of top object
154
+ trigger_z_off = -(self.top_thickness + self.trigger_height)
155
+ self.trigger = BoxObject(
156
+ name="trigger",
157
+ size=[self.trigger_length, self.trigger_width, self.trigger_height],
158
+ density=density,
159
+ friction=friction,
160
+ rgba=rgba,
161
+ material=material,
162
+ joints=None,
163
+ )
164
+ objects.append(self.trigger)
165
+ object_locations.append([trigger_x_off, 0.0, trigger_z_off])
166
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
167
+ object_parents.append(objects[-2].root_body) # NOTE: relative to top box object
168
+
169
+ # define slide joint for trigger
170
+ rel_joint_pos = [0, 0, 0] # at trigger
171
+ joint_lim_min = 0.0
172
+ joint_lim_max = (
173
+ self.top_length
174
+ ) # trigger was shifted to left by 0.5 * top_length, so allow it to go to right by top_length
175
+ slide_joint = {
176
+ "name": "trigger_slide",
177
+ "type": "slide",
178
+ "axis": "1 0 0", # x-axis slide
179
+ "pos": array_to_string(rel_joint_pos),
180
+ "springref": "0",
181
+ "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio
182
+ "limited": "true",
183
+ "range": "{} {}".format(joint_lim_min, joint_lim_max),
184
+ }
185
+
186
+ if self.add_square_base:
187
+ # add square base underneath bottom cylinder
188
+ s1_offset = -(self.square_base_height + self.base_cylinder_height)
189
+ self.square_base = BoxObject(
190
+ name="square_base",
191
+ size=[
192
+ self.square_base_width,
193
+ self.square_base_width,
194
+ self.square_base_height,
195
+ ],
196
+ rgba=rgba,
197
+ material=material,
198
+ )
199
+ objects.append(self.square_base)
200
+ object_locations.append([0.0, 0.0, s1_offset])
201
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
202
+ object_parents.append(None)
203
+
204
+ # Run super init
205
+ super().__init__(
206
+ name=name,
207
+ objects=objects,
208
+ object_locations=object_locations,
209
+ object_quats=object_quats,
210
+ object_parents=object_parents,
211
+ joints=joints,
212
+ body_joints={objects[-1].root_body: [slide_joint]},
213
+ )
third_party/robocasa/robocasa/models/objects/composite_body/stacked_box.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject, Bin
2
+ import numpy as np
3
+
4
+ import robosuite.utils.transform_utils as T
5
+ from robosuite.utils.mjcf_utils import array_to_string
6
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
7
+
8
+
9
+ class StackedBoxObject(CompositeBodyObject):
10
+ """
11
+ Two boxes - one stacked on top of the other.
12
+ """
13
+
14
+ def __init__(
15
+ self,
16
+ name,
17
+ box_1_size,
18
+ box_2_size,
19
+ joints="default",
20
+ box_1_rgba=None,
21
+ box_2_rgba=None,
22
+ box_1_material=None,
23
+ box_2_material=None,
24
+ density=100.0,
25
+ friction=None,
26
+ make_box_2_transparent=False,
27
+ ):
28
+
29
+ # Object properties
30
+
31
+ # half-sizes of first (bottom) box
32
+ self.box_1_size = list(box_1_size)
33
+
34
+ # half-sizes of second (top) box
35
+ self.box_2_size = list(box_2_size)
36
+
37
+ # maybe make box 2 have transparent top and bottom walls
38
+ self.make_box_2_transparent = make_box_2_transparent
39
+
40
+ # Create objects
41
+ objects = []
42
+ object_locations = []
43
+ object_quats = []
44
+ object_parents = []
45
+
46
+ # NOTE: we will place the object frame at the vertical center of the two stacked boxes
47
+ z_center = (self.box_1_size[2] + self.box_2_size[2]) / 2.0
48
+ b1_offset = self.box_1_size[2] - z_center
49
+ b2_offset = 2.0 * self.box_1_size[2] + self.box_2_size[2] - z_center
50
+
51
+ # first (bottom) box
52
+ self.box_1 = BoxObject(
53
+ name="box_1",
54
+ size=self.box_1_size,
55
+ rgba=box_1_rgba,
56
+ material=box_1_material,
57
+ density=density,
58
+ friction=friction,
59
+ joints=None,
60
+ )
61
+ objects.append(self.box_1)
62
+ object_locations.append([0.0, 0.0, b1_offset])
63
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
64
+ object_parents.append(None)
65
+
66
+ # second (top) box
67
+ if self.make_box_2_transparent:
68
+ self.box_2 = Bin(
69
+ name="box_2",
70
+ bin_size=(
71
+ 2.0 * self.box_2_size[0],
72
+ 2.0 * self.box_2_size[1],
73
+ 2.0 * self.box_2_size[2],
74
+ ),
75
+ wall_thickness=0.01,
76
+ transparent_walls=False,
77
+ friction=friction,
78
+ density=density,
79
+ use_texture=True,
80
+ rgba=box_2_rgba,
81
+ material=box_2_material,
82
+ upside_down=False,
83
+ add_second_base=True,
84
+ transparent_base=True,
85
+ )
86
+ else:
87
+ self.box_2 = BoxObject(
88
+ name="box_2",
89
+ size=self.box_2_size,
90
+ rgba=box_2_rgba,
91
+ material=box_2_material,
92
+ density=density,
93
+ friction=friction,
94
+ joints=None,
95
+ )
96
+ objects.append(self.box_2)
97
+ object_locations.append([0.0, 0.0, b2_offset])
98
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
99
+ object_parents.append(None)
100
+
101
+ # Run super init
102
+ super().__init__(
103
+ name=name,
104
+ objects=objects,
105
+ object_locations=object_locations,
106
+ object_quats=object_quats,
107
+ object_parents=object_parents,
108
+ joints=joints,
109
+ # total_size=body_total_size,
110
+ # locations_relative_to_corner=True,
111
+ )
third_party/robocasa/robocasa/models/objects/composite_body/stacked_cylinder.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject
2
+ import numpy as np
3
+
4
+ import robosuite.utils.transform_utils as T
5
+ from robosuite.utils.mjcf_utils import array_to_string
6
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
7
+
8
+
9
+ class StackedCylinderObject(CompositeBodyObject):
10
+ """
11
+ Two cylinders - one stacked on top of the other.
12
+ Optionally add a square base for stability.
13
+ """
14
+
15
+ def __init__(
16
+ self,
17
+ name,
18
+ radius_1,
19
+ radius_2,
20
+ height_1,
21
+ height_2,
22
+ joints="default",
23
+ rgba=None,
24
+ material=None,
25
+ density=100.0,
26
+ friction=None,
27
+ square_base_width=None,
28
+ square_base_height=None,
29
+ ):
30
+
31
+ # Object properties
32
+
33
+ # radius of first (bottom) cylinder and second (top) cylinder
34
+ self.r1 = radius_1
35
+ self.r2 = radius_2
36
+
37
+ # half-height of first (bottom) cylinder and second (top) cylinder
38
+ self.h1 = height_1
39
+ self.h2 = height_2
40
+
41
+ # whether to add square base
42
+ self.add_square_base = (square_base_width is not None) and (
43
+ square_base_height is not None
44
+ )
45
+
46
+ # half-width and half-height for square base
47
+ self.square_base_width = square_base_width
48
+ self.square_base_height = square_base_height
49
+
50
+ # Create objects
51
+ objects = []
52
+ object_locations = []
53
+ object_quats = []
54
+ object_parents = []
55
+
56
+ # NOTE: we will place the object frame at the vertical center of the two stacked cylinders
57
+ z_center = (self.h1 + self.h2) / 2.0
58
+ c1_offset = self.h1 - z_center
59
+ c2_offset = 2.0 * self.h1 + self.h2 - z_center
60
+
61
+ # first (bottom) cylinder
62
+ self.cylinder_1 = CylinderObject(
63
+ name="cylinder_1",
64
+ size=[self.r1, self.h1],
65
+ rgba=rgba,
66
+ material=material,
67
+ density=density,
68
+ friction=friction,
69
+ solref=[0.02, 1.0],
70
+ solimp=[0.9, 0.95, 0.001],
71
+ # solimp=[0.998, 0.998, 0.001],
72
+ joints=None,
73
+ )
74
+ objects.append(self.cylinder_1)
75
+ object_locations.append([0.0, 0.0, c1_offset])
76
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
77
+ object_parents.append(None)
78
+
79
+ # second (top) cylinder
80
+ self.cylinder_2 = CylinderObject(
81
+ name="cylinder_2",
82
+ size=[self.r2, self.h2],
83
+ rgba=rgba,
84
+ material=material,
85
+ density=density,
86
+ friction=friction,
87
+ solref=[0.02, 1.0],
88
+ # solimp=[0.998, 0.998, 0.001],
89
+ solimp=[0.9, 0.95, 0.001],
90
+ joints=None,
91
+ )
92
+ objects.append(self.cylinder_2)
93
+ object_locations.append([0.0, 0.0, c2_offset])
94
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
95
+ object_parents.append(None)
96
+
97
+ # # total size of object
98
+ # max_r = max(self.r1, self.r2)
99
+ # body_total_size = [max_r, max_r, self.h1 + self.h2]
100
+
101
+ if self.add_square_base:
102
+ # add square base underneath bottom cylinder
103
+ s1_offset = c1_offset - (self.square_base_height + self.h1)
104
+ self.square_base = BoxObject(
105
+ name="square_base",
106
+ size=[
107
+ self.square_base_width,
108
+ self.square_base_width,
109
+ self.square_base_height,
110
+ ],
111
+ rgba=rgba,
112
+ material=material,
113
+ )
114
+ objects.append(self.square_base)
115
+ object_locations.append([0.0, 0.0, s1_offset])
116
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
117
+ object_parents.append(None)
118
+
119
+ # Run super init
120
+ super().__init__(
121
+ name=name,
122
+ objects=objects,
123
+ object_locations=object_locations,
124
+ object_quats=object_quats,
125
+ object_parents=object_parents,
126
+ joints=joints,
127
+ # total_size=body_total_size,
128
+ # locations_relative_to_corner=True,
129
+ )
third_party/robocasa/robocasa/models/objects/composite_body/stove_plug.py ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.objects import CompositeBodyObject, BoxObject, CylinderObject
2
+ import numpy as np
3
+
4
+ import robosuite.utils.transform_utils as T
5
+ from robosuite.utils.mjcf_utils import array_to_string
6
+ from robosuite.utils.mjcf_utils import RED, BLUE, CustomMaterial
7
+ from .inverse_stacked_cylinder import InverseStackedCylinderObject
8
+ from .lightbulb import LightbulbObject
9
+
10
+ import robosuite_task_zoo
11
+ from robosuite_task_zoo.models.kitchen import StoveObject
12
+
13
+
14
+ class StoveObjectNew(StoveObject):
15
+ """
16
+ Override some offsets for placement sampler.
17
+ """
18
+
19
+ @property
20
+ def bottom_offset(self):
21
+ # unused since we directly hardcode z
22
+ return np.array([0, 0, -0.02])
23
+
24
+ @property
25
+ def top_offset(self):
26
+ # unused since we directly hardcode z
27
+ return np.array([0, 0, 0.02])
28
+
29
+ @property
30
+ def horizontal_radius(self):
31
+ return 0.1
32
+
33
+
34
+ class StovePlugObject(CompositeBodyObject):
35
+ """
36
+ Stove on wooden block with chain (plug) connected. Optionally replace the stove
37
+ with a lightbulb if @lightbulb_args is provided.
38
+ """
39
+
40
+ def __init__(
41
+ self,
42
+ name,
43
+ joints="default",
44
+ rgba=None,
45
+ material=None,
46
+ density=100.0,
47
+ friction=None,
48
+ stove_base_size=(0.12, 0.12, 0.01),
49
+ stove_z_half_size=0.025,
50
+ wire_box_geom_size=(0.005, 0.02, 0.005),
51
+ wire_box_geom_rgba=(0.0, 0.0, 0.0, 1.0),
52
+ num_box_geoms_left=5,
53
+ num_box_geoms_vert=8,
54
+ num_box_geoms_right=8,
55
+ merge_box_geoms=False,
56
+ merge_size=1,
57
+ cylinder_args=None,
58
+ lightbulb_args=None,
59
+ ):
60
+
61
+ # Object properties
62
+
63
+ # half sizes for stove base box object
64
+ # self.stove_base_size = (0.1, 0.1, 0.02)
65
+ self.stove_base_size = stove_base_size
66
+ self.stove_z_half_size = stove_z_half_size # note: estimated approximately
67
+
68
+ # box geoms used for wire
69
+ self.wire_box_geom_size = wire_box_geom_size
70
+ self.wire_box_geom_rgba = wire_box_geom_rgba
71
+
72
+ # wire parameters - number of geoms to use for left, down, and right portions
73
+ self.num_box_geoms_left = num_box_geoms_left
74
+ self.num_box_geoms_vert = num_box_geoms_vert
75
+ self.num_box_geoms_right = num_box_geoms_right
76
+
77
+ # if true, merge the box geoms along each direction of the wire into a single box geom
78
+ self.merge_box_geoms = merge_box_geoms
79
+
80
+ # number of box geoms to use for each merged size (set to higher than 1 to merge the geoms into more
81
+ # than one box geom)
82
+ self.merge_size = merge_size
83
+
84
+ if cylinder_args is None:
85
+ # default cylinder args
86
+ cylinder_args = dict(
87
+ # bottom cylinder radius and half-height
88
+ radius_1=0.03,
89
+ height_1=0.01,
90
+ # top hollow cylinder inner radius and half-height
91
+ radius_2=0.025,
92
+ height_2=0.025,
93
+ # NOTE: reduce to 8 geoms if desired
94
+ ngeoms=64,
95
+ rgba=[0.839, 0.839, 0.839, 1],
96
+ density=1000.0,
97
+ # add square base
98
+ square_base_width=0.03,
99
+ square_base_height=0.005,
100
+ )
101
+ self.cylinder_args = dict(cylinder_args)
102
+ self.cylinder_args["joints"] = None
103
+
104
+ self.use_lightbulb = lightbulb_args is not None
105
+ if self.use_lightbulb:
106
+ self.lightbulb_args = dict(lightbulb_args)
107
+ self.lightbulb_args["joints"] = None
108
+
109
+ # materials
110
+ box_geom_material = CustomMaterial(
111
+ texture="Metal",
112
+ tex_name="metal",
113
+ mat_name="MatMetal",
114
+ tex_attrib={"type": "cube"},
115
+ mat_attrib={"specular": "1", "shininess": "0.3", "rgba": "0.9 0.9 0.9 1"},
116
+ )
117
+ stove_base_material = CustomMaterial(
118
+ texture="WoodLight",
119
+ tex_name="lightwood",
120
+ mat_name="lightwood_mat",
121
+ tex_attrib={"type": "cube"},
122
+ mat_attrib={"texrepeat": "1 1", "specular": "0.4", "shininess": "0.1"},
123
+ )
124
+
125
+ # params for ball joints used
126
+
127
+ # <joint name="J1" type="ball" pos="0 0 0" frictionloss="&friction;"/>
128
+ ball_joint_spec = {
129
+ "type": "ball",
130
+ "pos": "0 {} 0".format(self.wire_box_geom_size[1]),
131
+ "springref": "0",
132
+ "springdamper": "0.1 1.0", # mass-spring system with 0.1 time constant, 1.0 damping ratio
133
+ "limited": "true",
134
+ "range": "0 {}".format(np.pi / 4),
135
+ }
136
+
137
+ # Create objects
138
+ objects = []
139
+ object_locations = []
140
+ object_quats = []
141
+ object_parents = []
142
+ object_joints = dict()
143
+
144
+ # NOTE: For absolute object locations (objects not defined relative to parent) we will use the stove base frame
145
+ # as a frame of reference, and add an offset from the center of the object (approximated via full width)
146
+ # to it.
147
+
148
+ # get an approximate x-y bounding box below, and place the center there, and define offset relative to stove base cente
149
+ approx_full_width = self.num_box_geoms_left * (
150
+ 2.0 * self.wire_box_geom_size[1]
151
+ ) + (2.0 * self.stove_base_size[1])
152
+ approx_full_height = (self.num_box_geoms_vert + 2) * (
153
+ 2.0 * self.wire_box_geom_size[1]
154
+ )
155
+
156
+ stove_base_x_off = -(approx_full_height / 2.0) + self.stove_base_size[0]
157
+ stove_base_y_off = (approx_full_width / 2.0) - self.stove_base_size[1]
158
+
159
+ # base of stove
160
+ self.stove_base = BoxObject(
161
+ name="stove_base",
162
+ size=list(self.stove_base_size),
163
+ rgba=rgba,
164
+ material=stove_base_material,
165
+ joints=None,
166
+ )
167
+ objects.append(self.stove_base)
168
+ object_locations.append([stove_base_x_off, stove_base_y_off, 0.0])
169
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
170
+ object_parents.append(None)
171
+
172
+ if self.use_lightbulb:
173
+ # lightbulb
174
+ self.lightbulb = LightbulbObject(
175
+ name="lightbulb",
176
+ **self.lightbulb_args,
177
+ )
178
+ objects.append(self.lightbulb)
179
+ object_locations.append(
180
+ [
181
+ stove_base_x_off,
182
+ stove_base_y_off,
183
+ (self.stove_base_size[2] + self.lightbulb.z_center),
184
+ ]
185
+ )
186
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
187
+ object_parents.append(None)
188
+ else:
189
+ # stove
190
+ self.stove = StoveObjectNew(
191
+ name="new_stove",
192
+ joints=None,
193
+ )
194
+ objects.append(self.stove)
195
+ object_locations.append(
196
+ [
197
+ stove_base_x_off,
198
+ stove_base_y_off,
199
+ (self.stove_base_size[2] + self.stove_z_half_size),
200
+ ]
201
+ )
202
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
203
+ object_parents.append(None)
204
+
205
+ # chain to the left of stove base
206
+ chain_ind = 0
207
+ left_chain_size = list(self.wire_box_geom_size)
208
+ num_geoms_iter = self.num_box_geoms_left - 1
209
+ if self.merge_box_geoms:
210
+ # only one big geom instead of chain of geoms
211
+ left_chain_size[1] *= self.num_box_geoms_left
212
+ left_chain_size[1] /= self.merge_size
213
+ # number of additional geoms to add
214
+ num_geoms_iter = self.merge_size - 1
215
+ left_chain_obj = BoxObject(
216
+ name="chain_{}".format(chain_ind),
217
+ size=list(left_chain_size),
218
+ rgba=list(self.wire_box_geom_rgba),
219
+ material=box_geom_material,
220
+ joints=None,
221
+ )
222
+ chain_ind += 1
223
+ objects.append(left_chain_obj)
224
+ object_locations.append(
225
+ [
226
+ stove_base_x_off - 0.75 * self.stove_base_size[0],
227
+ stove_base_y_off - (self.stove_base_size[1] + left_chain_size[1]),
228
+ 0.0,
229
+ ]
230
+ )
231
+ # object_locations.append([0., -(self.stove_base_size[1] + left_chain_size[1]), 0.])
232
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
233
+ object_parents.append(None)
234
+ if self.merge_box_geoms:
235
+ # add ball joint and make sure to place it at the edge of the geom
236
+ ball_joint = dict(ball_joint_spec)
237
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
238
+ ball_joint["pos"] = "0 {} 0".format(left_chain_size[1])
239
+ object_joints[left_chain_obj.root_body] = [ball_joint]
240
+ for i in range(num_geoms_iter):
241
+ left_chain_obj = BoxObject(
242
+ name="chain_{}".format(chain_ind),
243
+ size=list(left_chain_size),
244
+ rgba=list(self.wire_box_geom_rgba),
245
+ material=box_geom_material,
246
+ joints=None,
247
+ )
248
+ chain_ind += 1
249
+ parent = objects[-1].root_body
250
+ objects.append(left_chain_obj)
251
+ object_locations.append([0.0, -2.0 * left_chain_size[1], 0.0])
252
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
253
+ object_parents.append(parent)
254
+
255
+ # add ball joint and make sure to place it at the edge of the geom
256
+ ball_joint = dict(ball_joint_spec)
257
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
258
+ ball_joint["pos"] = "0 {} 0".format(left_chain_size[1])
259
+ object_joints[left_chain_obj.root_body] = [ball_joint]
260
+
261
+ # add chain in downward direction
262
+ rot_quat = T.convert_quat(
263
+ T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz"
264
+ )
265
+ vert_chain_size = list(self.wire_box_geom_size)
266
+ num_geoms_iter = self.num_box_geoms_vert - 1
267
+ if self.merge_box_geoms:
268
+ # only one big geom instead of chain of geoms
269
+ vert_chain_size[1] *= self.num_box_geoms_vert
270
+ vert_chain_size[1] /= self.merge_size
271
+ # number of additional geoms to add
272
+ num_geoms_iter = self.merge_size - 1
273
+ vert_chain_obj = BoxObject(
274
+ name="chain_{}".format(chain_ind),
275
+ size=list(vert_chain_size),
276
+ rgba=list(self.wire_box_geom_rgba),
277
+ material=box_geom_material,
278
+ joints=None,
279
+ )
280
+ chain_ind += 1
281
+ parent = objects[-1].root_body
282
+ objects.append(vert_chain_obj)
283
+ object_locations.append([vert_chain_size[1], -left_chain_size[1], 0.0])
284
+ object_quats.append(rot_quat)
285
+ object_parents.append(parent)
286
+
287
+ ball_joint = dict(ball_joint_spec)
288
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
289
+ ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1])
290
+ object_joints[vert_chain_obj.root_body] = [ball_joint]
291
+
292
+ for i in range(num_geoms_iter):
293
+ vert_chain_obj = BoxObject(
294
+ name="chain_{}".format(chain_ind),
295
+ size=list(vert_chain_size),
296
+ rgba=list(self.wire_box_geom_rgba),
297
+ material=box_geom_material,
298
+ joints=None,
299
+ )
300
+ chain_ind += 1
301
+ parent = objects[-1].root_body
302
+ objects.append(vert_chain_obj)
303
+ object_locations.append([0.0, -2.0 * vert_chain_size[1], 0.0])
304
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
305
+ object_parents.append(parent)
306
+
307
+ ball_joint = dict(ball_joint_spec)
308
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
309
+ ball_joint["pos"] = "0 {} 0".format(vert_chain_size[1])
310
+ object_joints[vert_chain_obj.root_body] = [ball_joint]
311
+
312
+ # add chain in rightward direction
313
+ rot_quat = T.convert_quat(
314
+ T.axisangle2quat(np.array([0.0, 0.0, 1.0]) * (np.pi / 2.0)), to="wxyz"
315
+ )
316
+ right_chain_size = list(self.wire_box_geom_size)
317
+ num_geoms_iter = self.num_box_geoms_right - 1
318
+ if self.merge_box_geoms:
319
+ # only one big geom instead of chain of geoms
320
+ right_chain_size[1] *= self.num_box_geoms_right
321
+ right_chain_size[1] /= self.merge_size
322
+ # number of additional geoms to add
323
+ num_geoms_iter = self.merge_size - 1
324
+ right_chain_obj = BoxObject(
325
+ name="chain_{}".format(chain_ind),
326
+ size=list(right_chain_size),
327
+ rgba=list(self.wire_box_geom_rgba),
328
+ material=box_geom_material,
329
+ joints=None,
330
+ )
331
+ chain_ind += 1
332
+ parent = objects[-1].root_body
333
+ objects.append(right_chain_obj)
334
+ object_locations.append([right_chain_size[1], -vert_chain_size[1], 0.0])
335
+ object_quats.append(rot_quat)
336
+ object_parents.append(parent)
337
+
338
+ ball_joint = dict(ball_joint_spec)
339
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
340
+ ball_joint["pos"] = "0 {} 0".format(right_chain_size[1])
341
+ object_joints[right_chain_obj.root_body] = [ball_joint]
342
+
343
+ for i in range(num_geoms_iter):
344
+ right_chain_obj = BoxObject(
345
+ name="chain_{}".format(chain_ind),
346
+ size=list(right_chain_size),
347
+ rgba=list(self.wire_box_geom_rgba),
348
+ material=box_geom_material,
349
+ joints=None,
350
+ )
351
+ chain_ind += 1
352
+ parent = objects[-1].root_body
353
+ objects.append(right_chain_obj)
354
+ object_locations.append([0.0, -2.0 * right_chain_size[1], 0.0])
355
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
356
+ object_parents.append(parent)
357
+
358
+ ball_joint = dict(ball_joint_spec)
359
+ ball_joint["name"] = "ball_joint_{}".format(chain_ind)
360
+ ball_joint["pos"] = "0 {} 0".format(right_chain_size[1])
361
+ object_joints[right_chain_obj.root_body] = [ball_joint]
362
+
363
+ # add cylinder object
364
+ self.cylinder_obj = InverseStackedCylinderObject(
365
+ name="cylinder_obj",
366
+ **self.cylinder_args,
367
+ )
368
+
369
+ x_off = 0.0
370
+ y_off = -(right_chain_size[1] + self.cylinder_obj.square_base_width)
371
+ z_off = (
372
+ (self.cylinder_obj.h1 + self.cylinder_obj.h2) / 2.0
373
+ ) - right_chain_size[2]
374
+ parent = objects[-1].root_body
375
+ objects.append(self.cylinder_obj)
376
+ object_locations.append([x_off, y_off, z_off])
377
+ object_quats.append([1.0, 0.0, 0.0, 0.0])
378
+ object_parents.append(parent)
379
+
380
+ # # add debug site to see object center
381
+ # sites = [
382
+ # dict(
383
+ # name="TMP",
384
+ # pos=array_to_string([0., 0., 0.]),
385
+ # size="{}".format(0.1),
386
+ # rgba=array_to_string([1., 0., 0., 1.]),
387
+ # )
388
+ # ]
389
+
390
+ # Run super init
391
+ super().__init__(
392
+ name=name,
393
+ objects=objects,
394
+ object_locations=object_locations,
395
+ object_quats=object_quats,
396
+ object_parents=object_parents,
397
+ joints=joints,
398
+ body_joints=object_joints,
399
+ # sites=sites,
400
+ )
third_party/robocasa/robocasa/models/objects/kitchen_object_utils.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import os
3
+ import xml.etree.ElementTree as ET
4
+ from copy import deepcopy
5
+
6
+ import numpy as np
7
+ from robosuite.utils.mjcf_utils import find_elements, string_to_array
8
+
9
+ import robocasa
10
+ from robocasa.models.objects.kitchen_objects import OBJ_CATEGORIES, OBJ_GROUPS
11
+ from robosuite.utils.mjcf_utils import xml_path_completion
12
+
13
+ BASE_ASSET_ZOO_PATH = os.path.join(robocasa.models.assets_root, "objects")
14
+ OBJ_REGISTRIES = ["objaverse", "aigen", "infinigen", "sketchfab", "lightwheel"]
15
+
16
+
17
+ class ObjCat:
18
+ """
19
+ Class that encapsulates data for an object category.
20
+
21
+ Args:
22
+ name (str): name of the object category
23
+
24
+ types (tuple) or (str): type(s)/categories the object belongs to. Examples include meat, sweets, fruit, etc.
25
+
26
+ model_folders (list): list of folders containing the MJCF models for the object category
27
+
28
+ exclude (list): list of model names to exclude
29
+
30
+ graspable (bool): whether the object is graspable
31
+
32
+ washable (bool): whether the object is washable
33
+
34
+ microwavable (bool): whether the object is microwavable
35
+
36
+ cookable (bool): whether the object is cookable
37
+
38
+ freezable (bool): whether the object is freezable
39
+
40
+ scale (float): scale of the object meshes/geoms
41
+
42
+ solimp (tuple): solimp values for the object meshes/geoms
43
+
44
+ solref (tuple): solref values for the object meshes/geoms
45
+
46
+ density (float): density of the object meshes/geoms
47
+
48
+ friction (tuple): friction values for the object meshes/geoms
49
+
50
+ priority: priority of the object
51
+
52
+ aigen_cat (bool): True if the object is an AI-generated object otherwise use obj_registry. Kept for backwards compatibility
53
+
54
+ obj_registry (str): the object registry the category belongs to, one of ["objaverse", "aigen", "infinigen", "sketchfab", "lightwheel"]
55
+ """
56
+
57
+ def __init__(
58
+ self,
59
+ name,
60
+ types,
61
+ model_folders=None,
62
+ exclude=None,
63
+ graspable=False,
64
+ washable=False,
65
+ microwavable=False,
66
+ cookable=False,
67
+ freezable=False,
68
+ scale=1.0,
69
+ solimp=(0.998, 0.998, 0.001),
70
+ solref=(0.001, 2),
71
+ margin=0,
72
+ density=100,
73
+ friction=(0.95, 0.3, 0.1),
74
+ priority=None,
75
+ aigen_cat=False,
76
+ obj_registry="objaverse",
77
+ ):
78
+ self.name = name
79
+ if not isinstance(types, tuple):
80
+ types = (types,)
81
+ self.types = types
82
+
83
+ self.obj_registry = "aigen" if aigen_cat else obj_registry
84
+ self.graspable = graspable
85
+ self.washable = washable
86
+ self.microwavable = microwavable
87
+ self.cookable = cookable
88
+ self.freezable = freezable
89
+
90
+ self.scale = scale
91
+ self.solimp = solimp
92
+ self.solref = solref
93
+ self.margin = margin
94
+ self.density = density
95
+ self.friction = friction
96
+ self.priority = priority
97
+ self.exclude = exclude or []
98
+
99
+ if model_folders is None:
100
+ if self.obj_registry == "aigen":
101
+ subf = "aigen_objs"
102
+ else:
103
+ subf = self.obj_registry
104
+ model_folders = ["{}/{}".format(subf, name)]
105
+ cat_mjcf_paths = []
106
+ for folder in model_folders:
107
+ cat_path = os.path.join(BASE_ASSET_ZOO_PATH, folder)
108
+ for root, _, files in os.walk(cat_path):
109
+ if "model.xml" in files:
110
+ model_name = os.path.basename(root)
111
+ if model_name in self.exclude:
112
+ continue
113
+ cat_mjcf_paths.append(os.path.join(root, "model.xml"))
114
+ self.mjcf_paths = sorted(cat_mjcf_paths)
115
+
116
+ def get_mjcf_kwargs(self):
117
+ """
118
+ returns relevant data to apply to the MJCF model for the object category
119
+ """
120
+ return deepcopy(
121
+ dict(
122
+ scale=self.scale,
123
+ solimp=self.solimp,
124
+ solref=self.solref,
125
+ density=self.density,
126
+ friction=self.friction,
127
+ priority=self.priority,
128
+ margin=self.margin,
129
+ )
130
+ )
131
+
132
+
133
+ # update OBJ_CATEGORIES with ObjCat instances. Maps name to the different registries it can belong to
134
+ # and then maps the registry to the ObjCat instance
135
+ for name, kwargs in OBJ_CATEGORIES.items():
136
+
137
+ # get the properties that are common across registries
138
+ common_properties = deepcopy(kwargs)
139
+ valid_properties = [
140
+ "graspable",
141
+ "washable",
142
+ "microwavable",
143
+ "cookable",
144
+ "freezable",
145
+ "types",
146
+ ] + list(OBJ_REGISTRIES)
147
+
148
+ for k in common_properties.keys():
149
+ assert k in valid_properties
150
+
151
+ # extract registry-specific kwargs
152
+ registry_kwargs = {}
153
+ for registry in OBJ_REGISTRIES:
154
+ registry_kwargs[registry] = common_properties.pop(registry, None)
155
+
156
+ assert "scale" not in kwargs
157
+ OBJ_CATEGORIES[name] = {}
158
+
159
+ # create instances for each registry
160
+ for registry in OBJ_REGISTRIES:
161
+ if registry_kwargs[registry] is not None:
162
+ registry_kwargs[registry].update(common_properties)
163
+ OBJ_CATEGORIES[name][registry] = ObjCat(
164
+ name=name, obj_registry=registry, **registry_kwargs[registry]
165
+ )
166
+
167
+
168
+ def sample_kitchen_object(
169
+ groups,
170
+ exclude_groups=None,
171
+ exclude_cat=None,
172
+ graspable=None,
173
+ washable=None,
174
+ microwavable=None,
175
+ cookable=None,
176
+ freezable=None,
177
+ rng=None,
178
+ obj_registries=None,
179
+ prefer_leading_registry=False,
180
+ prefer_leading_category=False,
181
+ prefer_leading_object=False,
182
+ split=None,
183
+ max_size=(None, None, None),
184
+ object_scale=None,
185
+ ):
186
+ """
187
+ Sample a kitchen object from the specified groups and within max_size bounds.
188
+
189
+ Args:
190
+ groups (list or str): groups to sample from or the exact xml path of the object to spawn
191
+
192
+ exclude_groups (str or list): groups to exclude
193
+
194
+ exclude_cat (str or list): categories to exclude
195
+
196
+ graspable (bool): whether the sampled object must be graspable
197
+
198
+ washable (bool): whether the sampled object must be washable
199
+
200
+ microwavable (bool): whether the sampled object must be microwavable
201
+
202
+ cookable (bool): whether the sampled object must be cookable
203
+
204
+ freezable (bool): whether the sampled object must be freezable
205
+
206
+ rng (np.random.Generator): random number object
207
+
208
+ obj_registries (tuple): registries to sample from
209
+
210
+ prefer_leading_registry (bool): sample obj_registries in order instead of random
211
+
212
+ prefer_leading_category (bool): sample categories in order instead of random
213
+
214
+ prefer_leading_object (bool): sample objects in order instead of random
215
+
216
+ split (str): split to sample from. Split "A" specifies all but the last 3 object instances
217
+ (or the first half - whichever is larger), "B" specifies the rest, and None specifies all.
218
+
219
+ max_size (tuple): max size of the object. If the sampled object is not within bounds of max size, function will resample
220
+
221
+ object_scale (float or dict): scale of the object. If set will multiply the scale of the sampled object by this value
222
+
223
+
224
+ Returns:
225
+ dict: kwargs to apply to the MJCF model for the sampled object
226
+
227
+ dict: info about the sampled object - the path of the mjcf, groups which the object's category belongs to, the category of the object
228
+ the sampling split the object came from, and the groups the object was sampled from
229
+ """
230
+ for obj_registry in obj_registries:
231
+ subf = obj_registry if obj_registry != "aigen" else "aigen_objs"
232
+ if not os.path.exists(os.path.join(BASE_ASSET_ZOO_PATH, subf)):
233
+ script = (
234
+ "download_kitchen_assets.py"
235
+ if obj_registry in ("objaverse", "aigen")
236
+ else "download_groot_assets.py"
237
+ )
238
+ raise FileNotFoundError(
239
+ f"Object registry {obj_registry} directory not found at {os.path.join(BASE_ASSET_ZOO_PATH, subf)}. Try running {script}."
240
+ )
241
+
242
+ valid_object_sampled = False
243
+ while valid_object_sampled is False:
244
+ mjcf_kwargs, info = sample_kitchen_object_helper(
245
+ groups=groups,
246
+ exclude_groups=exclude_groups,
247
+ exclude_cat=exclude_cat,
248
+ graspable=graspable,
249
+ washable=washable,
250
+ microwavable=microwavable,
251
+ cookable=cookable,
252
+ freezable=freezable,
253
+ rng=rng,
254
+ obj_registries=obj_registries,
255
+ prefer_leading_registry=prefer_leading_registry,
256
+ prefer_leading_category=prefer_leading_category,
257
+ prefer_leading_object=prefer_leading_object,
258
+ split=split,
259
+ object_scale=object_scale,
260
+ )
261
+
262
+ # check if object size is within bounds
263
+ mjcf_path = info["mjcf_path"]
264
+ tree = ET.parse(mjcf_path)
265
+ root = tree.getroot()
266
+ bottom = string_to_array(
267
+ find_elements(root=root, tags="site", attribs={"name": "bottom_site"}).get(
268
+ "pos"
269
+ )
270
+ )
271
+ top = string_to_array(
272
+ find_elements(root=root, tags="site", attribs={"name": "top_site"}).get(
273
+ "pos"
274
+ )
275
+ )
276
+ horizontal_radius = string_to_array(
277
+ find_elements(
278
+ root=root, tags="site", attribs={"name": "horizontal_radius_site"}
279
+ ).get("pos")
280
+ )
281
+ scale = mjcf_kwargs["scale"]
282
+ obj_size = (
283
+ np.array(
284
+ [horizontal_radius[0] * 2, horizontal_radius[1] * 2, top[2] - bottom[2]]
285
+ )
286
+ * scale
287
+ )
288
+ valid_object_sampled = True
289
+ for i in range(3):
290
+ if max_size[i] is not None and obj_size[i] > max_size[i]:
291
+ valid_object_sampled = False
292
+
293
+ return mjcf_kwargs, info
294
+
295
+
296
+ def sample_kitchen_object_helper(
297
+ groups,
298
+ exclude_groups=None,
299
+ exclude_cat=None,
300
+ graspable=None,
301
+ washable=None,
302
+ microwavable=None,
303
+ cookable=None,
304
+ freezable=None,
305
+ rng=None,
306
+ obj_registries=None,
307
+ prefer_leading_registry=False,
308
+ prefer_leading_category=False,
309
+ prefer_leading_object=False,
310
+ split=None,
311
+ object_scale=None,
312
+ ):
313
+ """
314
+ Helper function to sample a kitchen object.
315
+
316
+ Args:
317
+ groups (list or str): groups to sample from or the exact xml path of the object to spawn
318
+
319
+ exclude_groups (str or list): groups to exclude
320
+
321
+ exclude_cat (str or list): categories to exclude
322
+
323
+ graspable (bool): whether the sampled object must be graspable
324
+
325
+ washable (bool): whether the sampled object must be washable
326
+
327
+ microwavable (bool): whether the sampled object must be microwavable
328
+
329
+ cookable (bool): whether whether the sampled object must be cookable
330
+
331
+ freezable (bool): whether whether the sampled object must be freezable
332
+
333
+ rng (np.random.Generator): random number object
334
+
335
+ obj_registries (tuple): registries to sample from
336
+
337
+ prefer_leading_registry (bool): sample obj_registries in order instead of random
338
+
339
+ prefer_leading_category (bool): sample categories in order instead of random
340
+
341
+ prefer_leading_object (bool): sample objects in order instead of random
342
+
343
+ split (str): split to sample from. Split "A" specifies all but the last 3 object instances
344
+ (or the first half - whichever is larger), "B" specifies the rest, and None specifies all.
345
+
346
+ object_scale (float): scale of the object. If set will multiply the scale of the sampled object by this value
347
+
348
+
349
+ Returns:
350
+ dict: kwargs to apply to the MJCF model for the sampled object
351
+
352
+ dict: info about the sampled object - the path of the mjcf, groups which the object's category belongs to, the category of the object
353
+ the sampling split the object came from, and the groups the object was sampled from
354
+ """
355
+ if rng is None:
356
+ rng = np.random.default_rng()
357
+
358
+ # If all groups are xml paths, randomly select one
359
+ if isinstance(groups, (list, tuple)) and all(
360
+ isinstance(g, str) and g.endswith(".xml") for g in groups
361
+ ):
362
+ groups = rng.choice(groups)
363
+
364
+ # option to spawn specific object instead of sampling from a group
365
+ if isinstance(groups, str) and groups.endswith(".xml"):
366
+ mjcf_path = xml_path_completion(groups, root=robocasa.models.assets_root)
367
+ # reverse look up mjcf_path to category
368
+ mjcf_kwargs = dict()
369
+ cat = None
370
+ obj_found = False
371
+ for cand_cat in OBJ_CATEGORIES:
372
+ for reg in obj_registries:
373
+ if (
374
+ reg in OBJ_CATEGORIES[cand_cat]
375
+ and mjcf_path in OBJ_CATEGORIES[cand_cat][reg].mjcf_paths
376
+ ):
377
+ mjcf_kwargs = OBJ_CATEGORIES[cand_cat][reg].get_mjcf_kwargs()
378
+ cat = cand_cat
379
+ obj_found = True
380
+ break
381
+ if obj_found:
382
+ break
383
+ if obj_found is False:
384
+ raise ValueError(
385
+ f"Could not find object with MJCF path: {mjcf_path} in any registered category"
386
+ )
387
+ mjcf_kwargs["mjcf_path"] = mjcf_path
388
+ else:
389
+ if not isinstance(groups, tuple) and not isinstance(groups, list):
390
+ groups = [groups]
391
+
392
+ if exclude_groups is None:
393
+ exclude_groups = []
394
+ if not isinstance(exclude_groups, tuple) and not isinstance(
395
+ exclude_groups, list
396
+ ):
397
+ exclude_groups = [exclude_groups]
398
+
399
+ invalid_categories = []
400
+ for g in exclude_groups:
401
+ for cat in OBJ_GROUPS[g]:
402
+ invalid_categories.append(cat)
403
+
404
+ if exclude_cat is None:
405
+ exclude_cat = []
406
+ if not isinstance(exclude_cat, tuple) and not isinstance(exclude_cat, list):
407
+ exclude_cat = [exclude_cat]
408
+
409
+ for cat in exclude_cat:
410
+ invalid_categories.append(cat)
411
+
412
+ valid_categories = []
413
+ for g in groups:
414
+ for cat in OBJ_GROUPS[g]:
415
+ # don't repeat if already added
416
+ if cat in valid_categories:
417
+ continue
418
+ if cat in invalid_categories:
419
+ continue
420
+
421
+ # don't include if category not represented in any registry
422
+ # don't include if category has no valid mjcf files
423
+ cat_in_any_reg = False
424
+ for reg in obj_registries:
425
+ if reg in OBJ_CATEGORIES[cat]:
426
+ if len(OBJ_CATEGORIES[cat][reg].mjcf_paths) > 0:
427
+ cat_in_any_reg = True
428
+ else:
429
+ print(
430
+ f"WARNING: No object files found for category '{cat}' in registry '{reg}'. Check if registry is installed and up to date."
431
+ )
432
+
433
+ if not cat_in_any_reg:
434
+ continue
435
+
436
+ invalid = False
437
+ for reg in obj_registries:
438
+ if reg not in OBJ_CATEGORIES[cat]:
439
+ continue
440
+ cat_meta = OBJ_CATEGORIES[cat][reg]
441
+ if graspable is True and cat_meta.graspable is not True:
442
+ invalid = True
443
+ if washable is True and cat_meta.washable is not True:
444
+ invalid = True
445
+ if microwavable is True and cat_meta.microwavable is not True:
446
+ invalid = True
447
+ if cookable is True and cat_meta.cookable is not True:
448
+ invalid = True
449
+ if freezable is True and cat_meta.freezable is not True:
450
+ invalid = True
451
+
452
+ if invalid:
453
+ continue
454
+
455
+ valid_categories.append(cat)
456
+
457
+ if len(valid_categories) == 0:
458
+ raise ValueError(
459
+ f"No valid categories found for sampling from groups: {groups}. Check if the object registry is installed and up to date."
460
+ )
461
+
462
+ if prefer_leading_category:
463
+ cat = valid_categories[0]
464
+ else:
465
+ cat = rng.choice(valid_categories)
466
+
467
+ choices = {reg: [] for reg in obj_registries}
468
+
469
+ for reg in obj_registries:
470
+ if reg not in OBJ_CATEGORIES[cat]:
471
+ choices[reg] = []
472
+ continue
473
+ reg_choices = deepcopy(OBJ_CATEGORIES[cat][reg].mjcf_paths)
474
+
475
+ if len(reg_choices) == 0:
476
+ print(
477
+ f"WARNING: Registry '{reg}' is enabled and category '{cat}' claims to support this registry, but no actual object files were found. Is your object registry downloaded and up to date?"
478
+ )
479
+
480
+ # exclude out objects based on split
481
+ if split is not None:
482
+ split_th = max(len(choices) - 3, int(math.ceil(len(reg_choices) / 2)))
483
+ if split == "A":
484
+ reg_choices = reg_choices[:split_th]
485
+ elif split == "B":
486
+ reg_choices = reg_choices[split_th:]
487
+ else:
488
+ raise ValueError
489
+ choices[reg] = reg_choices
490
+
491
+ if sum(len(choices[reg]) for reg in obj_registries) == 0:
492
+ raise ValueError(
493
+ f"No valid object files found for category '{cat}' in any enabled registries."
494
+ )
495
+
496
+ if prefer_leading_registry:
497
+ chosen_reg = next(reg for reg in obj_registries if len(choices[reg]) > 0)
498
+ else:
499
+ chosen_reg = rng.choice(
500
+ obj_registries,
501
+ p=np.array([len(choices[reg]) for reg in obj_registries])
502
+ / sum(len(choices[reg]) for reg in obj_registries),
503
+ )
504
+ if prefer_leading_object:
505
+ mjcf_path = choices[chosen_reg][0]
506
+ else:
507
+ mjcf_path = rng.choice(choices[chosen_reg])
508
+ mjcf_kwargs = OBJ_CATEGORIES[cat][chosen_reg].get_mjcf_kwargs()
509
+ mjcf_kwargs["mjcf_path"] = mjcf_path
510
+
511
+ if object_scale is not None:
512
+ scale_value = (
513
+ object_scale.get(cat, 1.0)
514
+ if isinstance(object_scale, dict)
515
+ else object_scale
516
+ )
517
+ mjcf_kwargs["scale"] = (np.array(mjcf_kwargs["scale"]) * scale_value).tolist()
518
+
519
+ groups_containing_sampled_obj = []
520
+ for group, group_cats in OBJ_GROUPS.items():
521
+ if cat in group_cats:
522
+ groups_containing_sampled_obj.append(group)
523
+
524
+ info = {
525
+ "groups_containing_sampled_obj": groups_containing_sampled_obj,
526
+ "groups": groups,
527
+ "cat": cat,
528
+ "split": split,
529
+ "mjcf_path": mjcf_path,
530
+ }
531
+
532
+ return mjcf_kwargs, info
533
+
534
+
535
+ def search_kitchen_object(
536
+ groups,
537
+ obj_registries=None,
538
+ ):
539
+ mjcf_paths = []
540
+ valid_categories = []
541
+ if not isinstance(groups, tuple) and not isinstance(groups, list):
542
+ groups = [groups]
543
+ for g in groups:
544
+ for cat in OBJ_GROUPS[g]:
545
+ if cat in valid_categories:
546
+ continue
547
+ valid_categories.append(cat)
548
+ for reg in obj_registries:
549
+ if reg in OBJ_CATEGORIES[cat]:
550
+ mjcf_paths.extend(OBJ_CATEGORIES[cat][reg].mjcf_paths)
551
+ return mjcf_paths
third_party/robocasa/robocasa/models/objects/kitchen_objects.py ADDED
@@ -0,0 +1,2509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import os
3
+ import robocasa
4
+
5
+ BASE_ASSET_ZOO_PATH = os.path.join(robocasa.models.assets_root, "objects")
6
+
7
+
8
+ # Constant that contains information about each object category. These will be used to generate the ObjCat classes for each category
9
+ OBJ_CATEGORIES = dict(
10
+ liquor=dict(
11
+ types=("drink", "alcohol"),
12
+ graspable=True,
13
+ washable=False,
14
+ microwavable=False,
15
+ cookable=False,
16
+ freezable=False,
17
+ aigen=dict(
18
+ model_folders=["aigen_objs/alcohol"],
19
+ scale=1.50,
20
+ ),
21
+ objaverse=dict(
22
+ model_folders=["objaverse/alcohol"],
23
+ scale=1.35,
24
+ ),
25
+ ),
26
+ apple=dict(
27
+ types=("fruit"),
28
+ graspable=True,
29
+ washable=True,
30
+ microwavable=False,
31
+ cookable=True,
32
+ freezable=False,
33
+ aigen=dict(
34
+ scale=1.0,
35
+ ),
36
+ objaverse=dict(
37
+ scale=0.90,
38
+ ),
39
+ ),
40
+ avocado=dict(
41
+ types=("vegetable"),
42
+ graspable=True,
43
+ washable=True,
44
+ microwavable=False,
45
+ cookable=False,
46
+ freezable=False,
47
+ aigen=dict(
48
+ scale=0.90,
49
+ ),
50
+ objaverse=dict(
51
+ scale=0.90,
52
+ ),
53
+ ),
54
+ bagel=dict(
55
+ types=("bread_food"),
56
+ graspable=False,
57
+ washable=False,
58
+ microwavable=False,
59
+ cookable=False,
60
+ freezable=False,
61
+ aigen=dict(
62
+ scale=1.2,
63
+ ),
64
+ objaverse=dict(
65
+ exclude=[
66
+ "bagel_8",
67
+ ],
68
+ ),
69
+ ),
70
+ bagged_food=dict(
71
+ types=("packaged_food"),
72
+ graspable=False,
73
+ washable=False,
74
+ microwavable=False,
75
+ cookable=False,
76
+ freezable=True,
77
+ aigen=dict(
78
+ scale=1.1,
79
+ ),
80
+ objaverse=dict(
81
+ exclude=[
82
+ "bagged_food_12",
83
+ ],
84
+ ),
85
+ ),
86
+ baguette=dict(
87
+ types=("bread_food"),
88
+ graspable=True,
89
+ washable=False,
90
+ microwavable=False,
91
+ cookable=False,
92
+ freezable=True,
93
+ aigen=dict(
94
+ scale=1.35,
95
+ ),
96
+ objaverse=dict(
97
+ exclude=[
98
+ "baguette_3", # small holes on ends
99
+ ],
100
+ ),
101
+ ),
102
+ banana=dict(
103
+ types=("fruit"),
104
+ graspable=True,
105
+ washable=True,
106
+ microwavable=False,
107
+ cookable=False,
108
+ freezable=False,
109
+ aigen=dict(
110
+ scale=1.10,
111
+ ),
112
+ objaverse=dict(
113
+ scale=0.95,
114
+ ),
115
+ ),
116
+ bar=dict(
117
+ types=("packaged_food"),
118
+ graspable=True,
119
+ washable=False,
120
+ microwavable=False,
121
+ cookable=False,
122
+ freezable=True,
123
+ aigen=dict(
124
+ scale=[1.25, 1.25, 1.75],
125
+ ),
126
+ objaverse=dict(
127
+ scale=[0.75, 0.75, 1.2],
128
+ exclude=[
129
+ "bar_1", # small holes scattered
130
+ ],
131
+ ),
132
+ ),
133
+ bar_soap=dict(
134
+ types=("cleaner"),
135
+ graspable=True,
136
+ washable=True,
137
+ microwavable=False,
138
+ cookable=False,
139
+ freezable=False,
140
+ aigen=dict(
141
+ scale=[1.25, 1.25, 1.40],
142
+ ),
143
+ objaverse=dict(
144
+ scale=[0.95, 0.95, 1.05],
145
+ exclude=["bar_soap_2"],
146
+ ),
147
+ ),
148
+ beer=dict(
149
+ types=("drink", "alcohol"),
150
+ graspable=True,
151
+ washable=True,
152
+ microwavable=False,
153
+ cookable=False,
154
+ freezable=False,
155
+ aigen=dict(
156
+ scale=1.30,
157
+ ),
158
+ objaverse=dict(scale=1.15),
159
+ ),
160
+ bell_pepper=dict(
161
+ types=("vegetable"),
162
+ graspable=True,
163
+ washable=True,
164
+ microwavable=True,
165
+ cookable=True,
166
+ freezable=True,
167
+ aigen=dict(
168
+ scale=1.0,
169
+ ),
170
+ objaverse=dict(
171
+ scale=0.75,
172
+ ),
173
+ ),
174
+ book=dict(
175
+ types=("book"),
176
+ graspable=True,
177
+ washable=False,
178
+ microwavable=False,
179
+ cookable=False,
180
+ freezable=False,
181
+ sketchfab=dict(
182
+ scale=1.0,
183
+ ),
184
+ ),
185
+ bookshelf=dict(
186
+ types=("furniture"),
187
+ graspable=False,
188
+ washable=False,
189
+ microwavable=False,
190
+ cookable=False,
191
+ freezable=False,
192
+ sketchfab=dict(
193
+ scale=1.0,
194
+ density=5000,
195
+ solimp=(0.95, 0.98, 0.001),
196
+ solref=(0.004, 1),
197
+ ),
198
+ ),
199
+ bottled_drink=dict(
200
+ types=("drink"),
201
+ graspable=True,
202
+ washable=True,
203
+ microwavable=False,
204
+ cookable=False,
205
+ freezable=True,
206
+ aigen=dict(
207
+ scale=1.25,
208
+ ),
209
+ infinigen=dict(
210
+ scale=1.25,
211
+ ),
212
+ objaverse=dict(),
213
+ ),
214
+ bottled_water=dict(
215
+ types=("drink"),
216
+ graspable=True,
217
+ washable=True,
218
+ microwavable=False,
219
+ cookable=False,
220
+ freezable=True,
221
+ aigen=dict(
222
+ scale=1.30,
223
+ ),
224
+ objaverse=dict(
225
+ scale=1.10,
226
+ exclude=[
227
+ "bottled_water_0", # minor hole at top
228
+ "bottled_water_5", # causing error. eigenvalues of mesh inertia violate A + B >= C
229
+ ],
230
+ ),
231
+ ),
232
+ bowl=dict(
233
+ types=("receptacle", "stackable"),
234
+ graspable=True,
235
+ washable=True,
236
+ microwavable=True,
237
+ cookable=False,
238
+ freezable=False,
239
+ aigen=dict(
240
+ scale=1.75,
241
+ ),
242
+ infinigen=dict(
243
+ scale=1.0,
244
+ ),
245
+ objaverse=dict(
246
+ scale=2.0,
247
+ exclude=[
248
+ "bowl_21", # can see through from bottom of bowl
249
+ ],
250
+ ),
251
+ ),
252
+ boxed_drink=dict(
253
+ types=("drink"),
254
+ graspable=True,
255
+ washable=True,
256
+ microwavable=False,
257
+ cookable=False,
258
+ freezable=True,
259
+ aigen=dict(
260
+ scale=1.1,
261
+ ),
262
+ objaverse=dict(
263
+ scale=0.80,
264
+ exclude=[
265
+ "boxed_drink_9", # hole on bottom
266
+ "boxed_drink_6", # hole on bottom
267
+ "boxed_drink_8", # hole on bottom
268
+ ],
269
+ ),
270
+ ),
271
+ boxed_food=dict(
272
+ types=("packaged_food"),
273
+ graspable=True,
274
+ washable=False,
275
+ microwavable=True,
276
+ cookable=False,
277
+ freezable=True,
278
+ aigen=dict(
279
+ scale=1.25,
280
+ ),
281
+ objaverse=dict(
282
+ scale=1.1,
283
+ exclude=[
284
+ "boxed_food_5", # causing error. eigenvalues of mesh inertia violate A + B >= C
285
+ ],
286
+ # exclude=[
287
+ # "boxed_food_5",
288
+ # "boxed_food_3", "boxed_food_1", "boxed_food_6", "boxed_food_11", "boxed_food_10", "boxed_food_8", "boxed_food_9", "boxed_food_7", "boxed_food_2", # self turning due to single collision geom
289
+ # ],
290
+ ),
291
+ ),
292
+ bread=dict(
293
+ types=("bread_food"),
294
+ graspable=True,
295
+ washable=False,
296
+ microwavable=False,
297
+ cookable=False,
298
+ freezable=True,
299
+ aigen=dict(
300
+ scale=[0.80, 0.80, 1.0],
301
+ ),
302
+ objaverse=dict(
303
+ scale=[0.70, 0.70, 1.0],
304
+ exclude=["bread_22"], # hole on bottom
305
+ ),
306
+ ),
307
+ broccoli=dict(
308
+ types=("vegetable"),
309
+ graspable=True,
310
+ washable=True,
311
+ microwavable=True,
312
+ cookable=True,
313
+ freezable=True,
314
+ aigen=dict(
315
+ scale=1.35,
316
+ ),
317
+ objaverse=dict(
318
+ scale=1.25,
319
+ exclude=[
320
+ "broccoli_2", # holes on one part
321
+ ],
322
+ ),
323
+ ),
324
+ cake=dict(
325
+ types=("sweets"),
326
+ graspable=True,
327
+ washable=False,
328
+ microwavable=False,
329
+ cookable=False,
330
+ freezable=True,
331
+ aigen=dict(
332
+ scale=0.8,
333
+ ),
334
+ objaverse=dict(
335
+ scale=0.8,
336
+ ),
337
+ ),
338
+ can=dict(
339
+ types=("drink"),
340
+ graspable=True,
341
+ washable=True,
342
+ microwavable=False,
343
+ cookable=False,
344
+ freezable=True,
345
+ aigen=dict(),
346
+ objaverse=dict(
347
+ exclude=[
348
+ "can_10", # hole on bottom
349
+ "can_5", # causing error: faces of mesh have inconsistent orientation.
350
+ ],
351
+ ),
352
+ infinigen=dict(
353
+ scale=1.00,
354
+ ),
355
+ ),
356
+ candle=dict(
357
+ types=("decoration"),
358
+ graspable=True,
359
+ washable=False,
360
+ microwavable=False,
361
+ cookable=False,
362
+ freezable=False,
363
+ aigen=dict(
364
+ scale=1.5,
365
+ ),
366
+ objaverse=dict(
367
+ exclude=[
368
+ "candle_11", # hole at bottom
369
+ # "candle_2", # can't see from bottom view angle
370
+ # "candle_15", # can't see from bottom view angle
371
+ ],
372
+ ),
373
+ ),
374
+ canned_food=dict(
375
+ types=("packaged_food"),
376
+ graspable=True,
377
+ washable=True,
378
+ microwavable=True,
379
+ cookable=False,
380
+ freezable=True,
381
+ aigen=dict(
382
+ scale=1.15,
383
+ ),
384
+ objaverse=dict(
385
+ scale=0.90,
386
+ exclude=[
387
+ "canned_food_7", # holes at top and bottom
388
+ ],
389
+ ),
390
+ ),
391
+ cardboard_box=dict(
392
+ types=("receptacle"),
393
+ graspable=False,
394
+ washable=True,
395
+ microwavable=False,
396
+ cookable=False,
397
+ freezable=False,
398
+ lightwheel=dict(
399
+ exclude=[
400
+ "CardboardBox018", # odd shape
401
+ "CardboardBox023", # odd shape
402
+ "CardboardBox024", # odd shape
403
+ "CardboardBox030", # odd shape
404
+ ],
405
+ ),
406
+ ),
407
+ carrot=dict(
408
+ types=("vegetable"),
409
+ graspable=True,
410
+ washable=True,
411
+ microwavable=True,
412
+ cookable=True,
413
+ freezable=True,
414
+ aigen=dict(
415
+ scale=1.25,
416
+ ),
417
+ objaverse=dict(),
418
+ ),
419
+ cereal=dict(
420
+ types=("packaged_food"),
421
+ graspable=True,
422
+ washable=False,
423
+ microwavable=False,
424
+ cookable=False,
425
+ freezable=False,
426
+ aigen=dict(
427
+ scale=1.15,
428
+ ),
429
+ objaverse=dict(
430
+ # exclude=[
431
+ # "cereal_2", "cereal_5", "cereal_13", "cereal_3", "cereal_9", "cereal_0", "cereal_7", "cereal_4", "cereal_8", "cereal_12", "cereal_11", "cereal_1", "cereal_6", "cereal_10", # self turning due to single collision geom
432
+ # ]
433
+ ),
434
+ ),
435
+ cheese=dict(
436
+ types=("dairy"),
437
+ graspable=True,
438
+ washable=True,
439
+ microwavable=True,
440
+ cookable=True,
441
+ freezable=True,
442
+ aigen=dict(
443
+ scale=1.0,
444
+ ),
445
+ objaverse=dict(
446
+ scale=0.85,
447
+ ),
448
+ ),
449
+ chips=dict(
450
+ types=("packaged_food"),
451
+ graspable=False,
452
+ washable=False,
453
+ microwavable=False,
454
+ cookable=False,
455
+ freezable=False,
456
+ aigen=dict(
457
+ scale=1.5,
458
+ ),
459
+ objaverse=dict(
460
+ exclude=[
461
+ "chips_12", # minor hole at bottom of bag
462
+ # "chips_2", # a weird texture at top/bottom but keeping this
463
+ ]
464
+ ),
465
+ ),
466
+ chocolate=dict(
467
+ types=("sweets"),
468
+ graspable=False,
469
+ washable=False,
470
+ microwavable=False,
471
+ cookable=False,
472
+ freezable=True,
473
+ aigen=dict(
474
+ scale=[1.0, 1.0, 1.35],
475
+ ),
476
+ objaverse=dict(
477
+ scale=[0.80, 0.80, 1.20],
478
+ exclude=[
479
+ # "chocolate_2", # self turning due to single collision geom
480
+ ],
481
+ ),
482
+ ),
483
+ coffee_cup=dict(
484
+ types=("drink"),
485
+ graspable=True,
486
+ washable=False,
487
+ microwavable=True,
488
+ cookable=False,
489
+ freezable=False,
490
+ aigen=dict(
491
+ scale=1.35,
492
+ ),
493
+ objaverse=dict(
494
+ exclude=[
495
+ "coffee_cup_18", # can see thru top
496
+ "coffee_cup_5", # can see thru from bottom side
497
+ "coffee_cup_19", # can see thru from bottom side
498
+ ],
499
+ ),
500
+ ),
501
+ coffee_pod=dict(
502
+ types=("packaged_food"),
503
+ graspable=True,
504
+ washable=False,
505
+ microwavable=False,
506
+ cookable=False,
507
+ freezable=False,
508
+ sketchfab=dict(
509
+ scale=1.0,
510
+ ),
511
+ ),
512
+ clock=dict(
513
+ types=("decoration"),
514
+ graspable=False,
515
+ washable=False,
516
+ microwavable=False,
517
+ cookable=False,
518
+ freezable=False,
519
+ sketchfab=dict(
520
+ scale=1.0,
521
+ ),
522
+ ),
523
+ condiment_bottle=dict(
524
+ types=("condiment"),
525
+ graspable=True,
526
+ washable=True,
527
+ microwavable=False,
528
+ cookable=False,
529
+ freezable=False,
530
+ aigen=dict(
531
+ scale=1.35,
532
+ model_folders=["aigen_objs/condiment"],
533
+ ),
534
+ objaverse=dict(
535
+ scale=1.05,
536
+ model_folders=["objaverse/condiment"],
537
+ ),
538
+ ),
539
+ corn=dict(
540
+ types=("vegetable"),
541
+ graspable=True,
542
+ washable=True,
543
+ microwavable=True,
544
+ cookable=True,
545
+ freezable=True,
546
+ aigen=dict(
547
+ scale=1.5,
548
+ ),
549
+ objaverse=dict(scale=1.05),
550
+ ),
551
+ croissant=dict(
552
+ types=("pastry"),
553
+ graspable=True,
554
+ washable=False,
555
+ microwavable=False,
556
+ cookable=False,
557
+ freezable=True,
558
+ aigen=dict(
559
+ scale=0.90,
560
+ ),
561
+ objaverse=dict(
562
+ scale=0.90,
563
+ ),
564
+ ),
565
+ cucumber=dict(
566
+ types=("vegetable"),
567
+ graspable=True,
568
+ washable=True,
569
+ microwavable=False,
570
+ cookable=False,
571
+ freezable=True,
572
+ aigen=dict(
573
+ scale=1.1,
574
+ ),
575
+ objaverse=dict(),
576
+ ),
577
+ cup=dict(
578
+ types=("receptacle", "stackable"),
579
+ graspable=True,
580
+ washable=True,
581
+ microwavable=True,
582
+ cookable=False,
583
+ freezable=False,
584
+ aigen=dict(
585
+ scale=1.35,
586
+ solimp=(0.95, 0.98, 0.001),
587
+ solref=(0.004, 1),
588
+ margin=0.004,
589
+ ),
590
+ infinigen=dict(
591
+ scale=1.0,
592
+ solimp=(0.95, 0.98, 0.001),
593
+ solref=(0.004, 1),
594
+ margin=0.004,
595
+ ),
596
+ objaverse=dict(
597
+ solimp=(0.95, 0.98, 0.001),
598
+ solref=(0.004, 1),
599
+ margin=0.004,
600
+ ),
601
+ ),
602
+ cupcake=dict(
603
+ types=("sweets"),
604
+ graspable=True,
605
+ washable=False,
606
+ microwavable=False,
607
+ cookable=False,
608
+ freezable=True,
609
+ aigen=dict(
610
+ scale=0.90,
611
+ ),
612
+ objaverse=dict(
613
+ exclude=[
614
+ "cupcake_0", # can see thru bottom
615
+ "cupcake_10", # can see thru bottom,
616
+ "cupcake_1", # very small hole at bottom
617
+ ]
618
+ ),
619
+ ),
620
+ cutting_board=dict(
621
+ types=("receptacle"),
622
+ graspable=False,
623
+ washable=True,
624
+ microwavable=False,
625
+ cookable=False,
626
+ freezable=False,
627
+ aigen=dict(
628
+ scale=2.0,
629
+ ),
630
+ objaverse=dict(
631
+ scale=1.35,
632
+ exclude=[
633
+ "cutting_board_14",
634
+ "cutting_board_3",
635
+ "cutting_board_10",
636
+ "cutting_board_6", # these models still modeled with meshes which should work most of the time, but excluding them for safety
637
+ ],
638
+ ),
639
+ ),
640
+ dish_rack=dict(
641
+ types=("receptacle"),
642
+ graspable=False,
643
+ washable=False,
644
+ microwavable=False,
645
+ cookable=False,
646
+ freezable=False,
647
+ sketchfab=dict(
648
+ scale=0.8,
649
+ ),
650
+ lightwheel=dict(),
651
+ ),
652
+ donut=dict(
653
+ types=("sweets", "pastry"),
654
+ graspable=True,
655
+ washable=False,
656
+ microwavable=False,
657
+ cookable=False,
658
+ freezable=True,
659
+ aigen=dict(
660
+ scale=1.5,
661
+ ),
662
+ objaverse=dict(
663
+ scale=1.15,
664
+ ),
665
+ ),
666
+ egg=dict(
667
+ types=("dairy"),
668
+ graspable=True,
669
+ washable=True,
670
+ microwavable=True,
671
+ cookable=True,
672
+ freezable=True,
673
+ aigen=dict(
674
+ scale=1.15,
675
+ ),
676
+ objaverse=dict(
677
+ scale=0.85,
678
+ ),
679
+ ),
680
+ eggplant=dict(
681
+ types=("vegetable"),
682
+ graspable=True,
683
+ washable=True,
684
+ microwavable=True,
685
+ cookable=True,
686
+ freezable=True,
687
+ aigen=dict(
688
+ scale=1.30,
689
+ ),
690
+ objaverse=dict(scale=0.95),
691
+ ),
692
+ fish=dict(
693
+ types=("meat"),
694
+ graspable=True,
695
+ washable=True,
696
+ microwavable=True,
697
+ cookable=True,
698
+ freezable=True,
699
+ aigen=dict(
700
+ scale=[1.35, 1.35, 2.0],
701
+ ),
702
+ objaverse=dict(
703
+ scale=[1.0, 1.0, 1.5],
704
+ ),
705
+ ),
706
+ fork=dict(
707
+ types=("utensil"),
708
+ graspable=False,
709
+ washable=True,
710
+ microwavable=True,
711
+ cookable=True,
712
+ freezable=False,
713
+ aigen=dict(
714
+ scale=1.75,
715
+ ),
716
+ infinigen=dict(
717
+ scale=1.75,
718
+ ),
719
+ objaverse=dict(),
720
+ ),
721
+ garlic=dict(
722
+ types=("vegetable"),
723
+ graspable=True,
724
+ washable=True,
725
+ microwavable=True,
726
+ cookable=True,
727
+ freezable=True,
728
+ aigen=dict(
729
+ scale=1.3,
730
+ ),
731
+ objaverse=dict(scale=1.10, exclude=["garlic_3"]), # has hole on side
732
+ ),
733
+ glasses=dict(
734
+ types=("glasses"),
735
+ graspable=False,
736
+ washable=False,
737
+ microwavable=False,
738
+ cookable=False,
739
+ freezable=False,
740
+ sketchfab=dict(scale=1.0),
741
+ ),
742
+ hot_dog=dict(
743
+ types=("cooked_food"),
744
+ graspable=True,
745
+ washable=False,
746
+ microwavable=True,
747
+ cookable=False,
748
+ freezable=True,
749
+ aigen=dict(
750
+ scale=1.4,
751
+ ),
752
+ objaverse=dict(),
753
+ ),
754
+ jam=dict(
755
+ types=("packaged_food"),
756
+ graspable=True,
757
+ washable=True,
758
+ microwavable=False,
759
+ cookable=False,
760
+ freezable=True,
761
+ aigen=dict(
762
+ scale=1.05,
763
+ ),
764
+ objaverse=dict(
765
+ scale=0.90,
766
+ ),
767
+ ),
768
+ jug=dict(
769
+ types=("receptacle"),
770
+ graspable=True,
771
+ washable=True,
772
+ microwavable=False,
773
+ cookable=False,
774
+ freezable=False,
775
+ aigen=dict(
776
+ scale=1.5,
777
+ ),
778
+ objaverse=dict(
779
+ scale=1.5,
780
+ ),
781
+ ),
782
+ ketchup=dict(
783
+ types=("condiment"),
784
+ graspable=True,
785
+ washable=True,
786
+ microwavable=False,
787
+ cookable=False,
788
+ freezable=False,
789
+ aigen=dict(
790
+ scale=1.35,
791
+ ),
792
+ objaverse=dict(
793
+ exclude=[
794
+ "ketchup_5" # causing error: faces of mesh have inconsistent orientation.
795
+ ]
796
+ ),
797
+ ),
798
+ kettle_electric=dict(
799
+ types=("receptacle"),
800
+ graspable=True,
801
+ washable=False,
802
+ microwavable=False,
803
+ cookable=False,
804
+ freezable=False,
805
+ objaverse=dict(
806
+ scale=1.35,
807
+ model_folders=["objaverse/kettle"],
808
+ exclude=[
809
+ f"kettle_{i}"
810
+ for i in range(29)
811
+ if i not in [0, 7, 9, 12, 13, 17, 24, 25, 26, 27]
812
+ ],
813
+ ),
814
+ aigen=dict(
815
+ scale=1.5,
816
+ model_folders=["aigen_objs/kettle"],
817
+ exclude=[f"kettle_{i}" for i in range(11) if i not in [0, 2, 6, 9, 10, 11]],
818
+ ),
819
+ ),
820
+ kettle_non_electric=dict(
821
+ types=("receptacle"),
822
+ graspable=True,
823
+ washable=True,
824
+ microwavable=False,
825
+ cookable=False,
826
+ freezable=False,
827
+ objaverse=dict(
828
+ scale=1.35,
829
+ model_folders=["objaverse/kettle"],
830
+ exclude=[
831
+ f"kettle_{i}"
832
+ for i in range(29)
833
+ if i in [0, 7, 9, 12, 13, 17, 24, 25, 26, 27]
834
+ ],
835
+ ),
836
+ aigen=dict(
837
+ scale=1.5,
838
+ model_folders=["aigen_objs/kettle"],
839
+ exclude=[f"kettle_{i}" for i in range(11) if i in [0, 2, 6, 9, 10, 11]],
840
+ ),
841
+ lightwheel=dict(),
842
+ ),
843
+ kiwi=dict(
844
+ types=("fruit"),
845
+ graspable=True,
846
+ washable=True,
847
+ microwavable=False,
848
+ cookable=False,
849
+ freezable=True,
850
+ aigen=dict(
851
+ scale=0.90,
852
+ ),
853
+ objaverse=dict(
854
+ scale=0.90,
855
+ ),
856
+ ),
857
+ knife=dict(
858
+ types=("utensil"),
859
+ graspable=False,
860
+ washable=True,
861
+ microwavable=True,
862
+ cookable=True,
863
+ freezable=False,
864
+ aigen=dict(
865
+ scale=1.35,
866
+ ),
867
+ infinigen=dict(
868
+ scale=1.35,
869
+ ),
870
+ objaverse=dict(
871
+ scale=1.20,
872
+ ),
873
+ ),
874
+ ladle=dict(
875
+ types=("utensil"),
876
+ graspable=True,
877
+ washable=True,
878
+ microwavable=False,
879
+ cookable=True,
880
+ freezable=False,
881
+ aigen=dict(
882
+ scale=1.5,
883
+ ),
884
+ objaverse=dict(
885
+ scale=1.10,
886
+ ),
887
+ ),
888
+ lemon=dict(
889
+ types=("vegetable"),
890
+ graspable=True,
891
+ washable=True,
892
+ microwavable=False,
893
+ cookable=True,
894
+ freezable=True,
895
+ aigen=dict(
896
+ scale=1.1,
897
+ ),
898
+ objaverse=dict(),
899
+ ),
900
+ lime=dict(
901
+ types=("vegetable"),
902
+ graspable=True,
903
+ washable=True,
904
+ microwavable=False,
905
+ cookable=True,
906
+ freezable=True,
907
+ objaverse=dict(
908
+ scale=1.0,
909
+ ),
910
+ aigen=dict(
911
+ scale=0.90,
912
+ ),
913
+ ),
914
+ mango=dict(
915
+ types=("fruit"),
916
+ graspable=True,
917
+ washable=True,
918
+ microwavable=False,
919
+ cookable=True,
920
+ freezable=True,
921
+ aigen=dict(
922
+ scale=1.0,
923
+ ),
924
+ objaverse=dict(
925
+ scale=0.85,
926
+ exclude=[
927
+ "mango_3", # one half is pitch dark
928
+ ],
929
+ ),
930
+ ),
931
+ milk=dict(
932
+ types=("dairy", "drink"),
933
+ graspable=True,
934
+ washable=True,
935
+ microwavable=False,
936
+ cookable=False,
937
+ freezable=False,
938
+ aigen=dict(
939
+ scale=1.35,
940
+ ),
941
+ objaverse=dict(
942
+ exclude=[
943
+ "milk_6" # causing error: eigenvalues of mesh inertia violate A + B >= C
944
+ ]
945
+ ),
946
+ ),
947
+ mug=dict(
948
+ types=("receptacle", "stackable"),
949
+ graspable=True,
950
+ washable=True,
951
+ microwavable=True,
952
+ cookable=False,
953
+ freezable=False,
954
+ aigen=dict(
955
+ scale=1.0,
956
+ ),
957
+ objaverse=dict(),
958
+ ),
959
+ mug_tree=dict(
960
+ types=("mug_tree"),
961
+ graspable=False,
962
+ washable=False,
963
+ microwavable=False,
964
+ cookable=False,
965
+ freezable=False,
966
+ sketchfab=dict(
967
+ scale=1.0,
968
+ ),
969
+ lightwheel=dict(),
970
+ ),
971
+ mushroom=dict(
972
+ types=("vegetable"),
973
+ graspable=True,
974
+ washable=True,
975
+ microwavable=True,
976
+ cookable=True,
977
+ freezable=True,
978
+ aigen=dict(
979
+ scale=1.35,
980
+ ),
981
+ objaverse=dict(
982
+ scale=1.20,
983
+ exclude=[
984
+ # "mushroom_16", # very very small holes. keeping anyway
985
+ ],
986
+ ),
987
+ ),
988
+ onion=dict(
989
+ types=("vegetable"),
990
+ graspable=True,
991
+ washable=True,
992
+ microwavable=True,
993
+ cookable=True,
994
+ freezable=False,
995
+ aigen=dict(
996
+ scale=1.1,
997
+ ),
998
+ objaverse=dict(),
999
+ ),
1000
+ orange=dict(
1001
+ types=("fruit"),
1002
+ graspable=True,
1003
+ washable=True,
1004
+ microwavable=False,
1005
+ cookable=False,
1006
+ freezable=False,
1007
+ aigen=dict(
1008
+ scale=1.05,
1009
+ ),
1010
+ objaverse=dict(
1011
+ exclude=[
1012
+ # "orange_11", # bottom half is dark. keeping anyway
1013
+ ]
1014
+ ),
1015
+ ),
1016
+ pan=dict(
1017
+ types=("receptacle"),
1018
+ graspable=True,
1019
+ washable=True,
1020
+ microwavable=False,
1021
+ cookable=False,
1022
+ freezable=False,
1023
+ aigen=dict(
1024
+ scale=2.25,
1025
+ ),
1026
+ infinigen=dict(
1027
+ scale=2.25,
1028
+ ),
1029
+ objaverse=dict(
1030
+ scale=1.70,
1031
+ exclude=[
1032
+ "pan_16", # causing error. faces of mesh have inconsistent orientation,
1033
+ "pan_0",
1034
+ "pan_12",
1035
+ "pan_17",
1036
+ "pan_22", # these are technically what we consider "pots"
1037
+ ],
1038
+ ),
1039
+ ),
1040
+ pot=dict(
1041
+ types=("receptacle"),
1042
+ graspable=True,
1043
+ washable=True,
1044
+ microwavable=False,
1045
+ cookable=False,
1046
+ freezable=False,
1047
+ aigen=dict(
1048
+ scale=2.25,
1049
+ ),
1050
+ infinigen=dict(
1051
+ scale=1.3,
1052
+ ),
1053
+ objaverse=dict(
1054
+ model_folders=["objaverse/pan"],
1055
+ scale=1.70,
1056
+ exclude=list(
1057
+ set([f"pan_{i}" for i in range(25)])
1058
+ - set(["pan_0", "pan_12", "pan_17", "pan_22"])
1059
+ ),
1060
+ ),
1061
+ lightwheel=dict(),
1062
+ ),
1063
+ peach=dict(
1064
+ types=("fruit"),
1065
+ graspable=True,
1066
+ washable=True,
1067
+ microwavable=False,
1068
+ cookable=False,
1069
+ freezable=False,
1070
+ aigen=dict(
1071
+ scale=1.05,
1072
+ ),
1073
+ objaverse=dict(),
1074
+ ),
1075
+ pear=dict(
1076
+ types=("fruit"),
1077
+ graspable=True,
1078
+ washable=True,
1079
+ microwavable=False,
1080
+ cookable=False,
1081
+ freezable=False,
1082
+ aigen=dict(),
1083
+ objaverse=dict(
1084
+ exclude=[
1085
+ "pear_4", # has big hole. excluding
1086
+ ]
1087
+ ),
1088
+ ),
1089
+ pen_holder=dict(
1090
+ types=("pen_holder"),
1091
+ graspable=False,
1092
+ washable=False,
1093
+ microwavable=False,
1094
+ cookable=False,
1095
+ freezable=False,
1096
+ sketchfab=dict(
1097
+ scale=1.0,
1098
+ ),
1099
+ ),
1100
+ plate=dict(
1101
+ types=("receptacle"),
1102
+ graspable=False,
1103
+ washable=True,
1104
+ microwavable=True,
1105
+ cookable=False,
1106
+ freezable=False,
1107
+ aigen=dict(
1108
+ scale=1.65,
1109
+ ),
1110
+ infinigen=dict(
1111
+ scale=1.65,
1112
+ ),
1113
+ objaverse=dict(
1114
+ scale=1.35,
1115
+ exclude=[
1116
+ "plate_6", # causing error: faces of mesh have inconsistent orientation.
1117
+ ],
1118
+ ),
1119
+ ),
1120
+ placemat=dict(
1121
+ types=("receptacle"),
1122
+ graspable=False,
1123
+ washable=False,
1124
+ microwavable=False,
1125
+ cookable=False,
1126
+ freezable=False,
1127
+ sketchfab=dict(
1128
+ scale=1.0,
1129
+ exclude=[
1130
+ "placemat_1", # unstable
1131
+ ],
1132
+ ),
1133
+ lightwheel=dict(
1134
+ scale=0.7,
1135
+ exclude=["placemat025"], # too long
1136
+ ),
1137
+ ),
1138
+ potato=dict(
1139
+ types=("vegetable"),
1140
+ graspable=True,
1141
+ washable=True,
1142
+ microwavable=True,
1143
+ cookable=True,
1144
+ freezable=True,
1145
+ aigen=dict(
1146
+ scale=1.10,
1147
+ ),
1148
+ objaverse=dict(),
1149
+ ),
1150
+ rolling_pin=dict(
1151
+ types=("tool"),
1152
+ graspable=True,
1153
+ washable=True,
1154
+ microwavable=False,
1155
+ cookable=False,
1156
+ freezable=False,
1157
+ aigen=dict(
1158
+ scale=1.6,
1159
+ ),
1160
+ objaverse=dict(
1161
+ scale=1.25,
1162
+ exclude=[
1163
+ # "rolling_pin_5", # can see thru side handle edges, keeping anyway
1164
+ # "rolling_pin_1", # can see thru side handle edges, keeping anyway
1165
+ ],
1166
+ ),
1167
+ ),
1168
+ rubix_cube=dict(
1169
+ types=("toy"),
1170
+ graspable=True,
1171
+ washable=False,
1172
+ microwavable=False,
1173
+ cookable=False,
1174
+ freezable=False,
1175
+ sketchfab=dict(scale=1.0),
1176
+ lightwheel=dict(),
1177
+ ),
1178
+ scissors=dict(
1179
+ types=("tool"),
1180
+ graspable=False,
1181
+ washable=True,
1182
+ microwavable=False,
1183
+ cookable=False,
1184
+ freezable=False,
1185
+ aigen=dict(
1186
+ scale=1.35,
1187
+ ),
1188
+ objaverse=dict(
1189
+ scale=1.15,
1190
+ ),
1191
+ ),
1192
+ shaker=dict(
1193
+ types=("condiment"),
1194
+ graspable=True,
1195
+ washable=False,
1196
+ microwavable=False,
1197
+ cookable=False,
1198
+ freezable=False,
1199
+ aigen=dict(
1200
+ scale=1.25,
1201
+ ),
1202
+ objaverse=dict(),
1203
+ ),
1204
+ soap_dispenser=dict(
1205
+ types=("cleaner"),
1206
+ graspable=True,
1207
+ washable=True,
1208
+ microwavable=False,
1209
+ cookable=False,
1210
+ freezable=False,
1211
+ aigen=dict(
1212
+ scale=1.7,
1213
+ ),
1214
+ objaverse=dict(
1215
+ exclude=[
1216
+ # "soap_dispenser_4", # can see thru body but that's fine if this is glass
1217
+ ]
1218
+ ),
1219
+ ),
1220
+ spatula=dict(
1221
+ types=("utensil"),
1222
+ graspable=False,
1223
+ washable=True,
1224
+ microwavable=False,
1225
+ cookable=True,
1226
+ freezable=False,
1227
+ aigen=dict(
1228
+ scale=1.30,
1229
+ ),
1230
+ objaverse=dict(
1231
+ scale=1.10,
1232
+ ),
1233
+ ),
1234
+ sponge=dict(
1235
+ types=("cleaner"),
1236
+ graspable=True,
1237
+ washable=True,
1238
+ microwavable=False,
1239
+ cookable=False,
1240
+ freezable=False,
1241
+ aigen=dict(
1242
+ scale=1.20,
1243
+ ),
1244
+ objaverse=dict(
1245
+ scale=0.90,
1246
+ # exclude=[
1247
+ # "sponge_7", "sponge_1", # self turning due to single collision geom
1248
+ # ]
1249
+ ),
1250
+ ),
1251
+ spoon=dict(
1252
+ types=("utensil"),
1253
+ graspable=False,
1254
+ washable=True,
1255
+ microwavable=True,
1256
+ cookable=True,
1257
+ freezable=False,
1258
+ aigen=dict(
1259
+ scale=1.5,
1260
+ ),
1261
+ infinigen=dict(
1262
+ scale=1.5,
1263
+ ),
1264
+ objaverse=dict(),
1265
+ ),
1266
+ spray=dict(
1267
+ types=("cleaner"),
1268
+ graspable=True,
1269
+ washable=True,
1270
+ microwavable=False,
1271
+ cookable=False,
1272
+ freezable=False,
1273
+ aigen=dict(
1274
+ scale=1.75,
1275
+ ),
1276
+ objaverse=dict(
1277
+ scale=1.75,
1278
+ ),
1279
+ ),
1280
+ spray_bottle=dict(
1281
+ types=("cleaner"),
1282
+ graspable=True,
1283
+ washable=True,
1284
+ microwavable=False,
1285
+ cookable=False,
1286
+ freezable=False,
1287
+ sketchfab=dict(
1288
+ scale=1.0,
1289
+ ),
1290
+ ),
1291
+ squash=dict(
1292
+ types=("vegetable"),
1293
+ graspable=True,
1294
+ washable=True,
1295
+ microwavable=True,
1296
+ cookable=True,
1297
+ freezable=True,
1298
+ aigen=dict(
1299
+ scale=1.15,
1300
+ ),
1301
+ objaverse=dict(
1302
+ exclude=[
1303
+ "squash_10", # hole at bottom
1304
+ ],
1305
+ ),
1306
+ ),
1307
+ steak=dict(
1308
+ types=("meat"),
1309
+ graspable=True,
1310
+ washable=True,
1311
+ microwavable=True,
1312
+ cookable=True,
1313
+ freezable=True,
1314
+ aigen=dict(
1315
+ scale=[1.0, 1.0, 2.0],
1316
+ ),
1317
+ objaverse=dict(
1318
+ scale=[1.0, 1.0, 2.0],
1319
+ exclude=[
1320
+ "steak_13", # bottom texture completely messed up
1321
+ "steak_1", # bottom texture completely messed up
1322
+ # "steak_9", # bottom with some minor issues, keeping anyway
1323
+ ],
1324
+ ),
1325
+ ),
1326
+ stapler=dict(
1327
+ types=("tool"),
1328
+ graspable=False,
1329
+ washable=False,
1330
+ microwavable=False,
1331
+ cookable=False,
1332
+ freezable=False,
1333
+ sketchfab=dict(scale=1.0),
1334
+ ),
1335
+ sweet_potato=dict(
1336
+ types=("vegetable"),
1337
+ graspable=True,
1338
+ washable=True,
1339
+ microwavable=True,
1340
+ cookable=True,
1341
+ freezable=True,
1342
+ aigen=dict(),
1343
+ objaverse=dict(),
1344
+ ),
1345
+ tangerine=dict(
1346
+ types=("fruit"),
1347
+ graspable=True,
1348
+ washable=True,
1349
+ microwavable=False,
1350
+ cookable=False,
1351
+ freezable=False,
1352
+ aigen=dict(),
1353
+ objaverse=dict(),
1354
+ ),
1355
+ teapot=dict(
1356
+ types=("receptacle"),
1357
+ graspable=True,
1358
+ washable=True,
1359
+ microwavable=False,
1360
+ cookable=False,
1361
+ freezable=False,
1362
+ aigen=dict(
1363
+ scale=1.25,
1364
+ ),
1365
+ objaverse=dict(
1366
+ scale=1.25,
1367
+ exclude=[
1368
+ "teapot_9", # hole on bottom
1369
+ ],
1370
+ ),
1371
+ ),
1372
+ tomato=dict(
1373
+ types=("vegetable"),
1374
+ graspable=True,
1375
+ washable=True,
1376
+ microwavable=True,
1377
+ cookable=True,
1378
+ freezable=False,
1379
+ aigen=dict(
1380
+ scale=1.25,
1381
+ ),
1382
+ objaverse=dict(),
1383
+ ),
1384
+ tray=dict(
1385
+ types=("receptacle"),
1386
+ graspable=False,
1387
+ washable=True,
1388
+ microwavable=False,
1389
+ cookable=False,
1390
+ freezable=False,
1391
+ aigen=dict(scale=2.0),
1392
+ objaverse=dict(
1393
+ scale=1.80,
1394
+ ),
1395
+ lightwheel=dict(),
1396
+ ),
1397
+ tupperware=dict(
1398
+ types=("receptacle"),
1399
+ graspable=False,
1400
+ washable=True,
1401
+ microwavable=False,
1402
+ cookable=False,
1403
+ freezable=False,
1404
+ lightwheel=dict(),
1405
+ ),
1406
+ waffle=dict(
1407
+ types=("sweets"),
1408
+ graspable=False,
1409
+ washable=False,
1410
+ microwavable=True,
1411
+ cookable=False,
1412
+ freezable=True,
1413
+ aigen=dict(
1414
+ scale=1.75,
1415
+ ),
1416
+ objaverse=dict(
1417
+ exclude=[
1418
+ "waffle_2", # bottom completely messed up
1419
+ ]
1420
+ ),
1421
+ ),
1422
+ water_bottle=dict(
1423
+ types=("drink"),
1424
+ graspable=True,
1425
+ washable=True,
1426
+ microwavable=False,
1427
+ cookable=False,
1428
+ freezable=True,
1429
+ aigen=dict(
1430
+ scale=1.6,
1431
+ ),
1432
+ objaverse=dict(
1433
+ scale=1.5,
1434
+ exclude=[
1435
+ "water_bottle_11", # sides and bottom see thru, but ok if glass. keeping anyway
1436
+ ],
1437
+ ),
1438
+ ),
1439
+ wine=dict(
1440
+ types=("drink", "alcohol"),
1441
+ graspable=True,
1442
+ washable=True,
1443
+ microwavable=False,
1444
+ cookable=False,
1445
+ freezable=False,
1446
+ aigen=dict(
1447
+ scale=1.9,
1448
+ ),
1449
+ objaverse=dict(
1450
+ scale=1.6,
1451
+ exclude=[
1452
+ "wine_7", # causing error. faces of mesh have inconsistent orientation
1453
+ ],
1454
+ ),
1455
+ ),
1456
+ yogurt=dict(
1457
+ types=("dairy", "packaged_food"),
1458
+ graspable=True,
1459
+ washable=True,
1460
+ microwavable=False,
1461
+ cookable=False,
1462
+ freezable=True,
1463
+ aigen=dict(
1464
+ scale=1.0,
1465
+ ),
1466
+ objaverse=dict(
1467
+ scale=0.95,
1468
+ ),
1469
+ ),
1470
+ dates=dict(
1471
+ graspable=False,
1472
+ washable=True,
1473
+ microwavable=False,
1474
+ cookable=False,
1475
+ freezable=True,
1476
+ types=("fruit"),
1477
+ aigen=dict(),
1478
+ ),
1479
+ lemonade=dict(
1480
+ aigen=dict(
1481
+ scale=1.5,
1482
+ ),
1483
+ graspable=True,
1484
+ washable=False,
1485
+ microwavable=False,
1486
+ cookable=False,
1487
+ freezable=False,
1488
+ types=("drink"),
1489
+ ),
1490
+ walnut=dict(
1491
+ aigen=dict(
1492
+ scale=1.15,
1493
+ ),
1494
+ graspable=True,
1495
+ washable=True,
1496
+ microwavable=False,
1497
+ cookable=False,
1498
+ freezable=False,
1499
+ types=(),
1500
+ ),
1501
+ cheese_grater=dict(
1502
+ aigen=dict(
1503
+ scale=2.15,
1504
+ ),
1505
+ graspable=True,
1506
+ washable=True,
1507
+ microwavable=False,
1508
+ cookable=False,
1509
+ freezable=False,
1510
+ types=("tool"),
1511
+ ),
1512
+ syrup_bottle=dict(
1513
+ aigen=dict(
1514
+ scale=1.35,
1515
+ ),
1516
+ graspable=True,
1517
+ washable=False,
1518
+ microwavable=False,
1519
+ cookable=False,
1520
+ freezable=False,
1521
+ types=("condiment"),
1522
+ ),
1523
+ scallops=dict(
1524
+ aigen=dict(
1525
+ scale=1.25,
1526
+ ),
1527
+ graspable=True,
1528
+ washable=True,
1529
+ microwavable=True,
1530
+ cookable=True,
1531
+ freezable=True,
1532
+ types=("meat"),
1533
+ ),
1534
+ candy=dict(
1535
+ aigen=dict(),
1536
+ graspable=True,
1537
+ washable=False,
1538
+ microwavable=False,
1539
+ cookable=False,
1540
+ freezable=False,
1541
+ types=("sweets"),
1542
+ ),
1543
+ whisk=dict(
1544
+ aigen=dict(
1545
+ scale=1.8,
1546
+ ),
1547
+ graspable=True,
1548
+ washable=True,
1549
+ microwavable=False,
1550
+ cookable=False,
1551
+ freezable=False,
1552
+ types=("utensil"),
1553
+ ),
1554
+ pitcher=dict(
1555
+ aigen=dict(
1556
+ scale=1.75,
1557
+ ),
1558
+ graspable=True,
1559
+ washable=True,
1560
+ microwavable=True,
1561
+ cookable=False,
1562
+ freezable=False,
1563
+ types=("receptacle"),
1564
+ ),
1565
+ ice_cream=dict(
1566
+ aigen=dict(
1567
+ scale=1.25,
1568
+ ),
1569
+ graspable=True,
1570
+ washable=False,
1571
+ microwavable=False,
1572
+ cookable=False,
1573
+ freezable=True,
1574
+ types=("sweets"),
1575
+ ),
1576
+ cherry=dict(
1577
+ aigen=dict(),
1578
+ graspable=True,
1579
+ washable=True,
1580
+ microwavable=False,
1581
+ cookable=False,
1582
+ freezable=True,
1583
+ types=("fruit"),
1584
+ ),
1585
+ peanut_butter=dict(
1586
+ aigen=dict(
1587
+ scale=1.25,
1588
+ model_folders=["aigen_objs/peanut_butter_jar"],
1589
+ ),
1590
+ graspable=True,
1591
+ washable=False,
1592
+ microwavable=False,
1593
+ cookable=False,
1594
+ freezable=True,
1595
+ types=("packaged_food"),
1596
+ ),
1597
+ thermos=dict(
1598
+ aigen=dict(
1599
+ scale=1.75,
1600
+ ),
1601
+ graspable=True,
1602
+ washable=True,
1603
+ microwavable=True,
1604
+ cookable=False,
1605
+ freezable=True,
1606
+ types=("drink"),
1607
+ ),
1608
+ ham=dict(
1609
+ aigen=dict(
1610
+ scale=1.5,
1611
+ ),
1612
+ graspable=False,
1613
+ washable=True,
1614
+ microwavable=True,
1615
+ cookable=True,
1616
+ freezable=True,
1617
+ types=("meat"),
1618
+ ),
1619
+ dumpling=dict(
1620
+ aigen=dict(
1621
+ scale=1.15,
1622
+ ),
1623
+ graspable=True,
1624
+ washable=True,
1625
+ microwavable=True,
1626
+ cookable=True,
1627
+ freezable=True,
1628
+ types=("meat", "cooked_food"),
1629
+ ),
1630
+ cabbage=dict(
1631
+ aigen=dict(
1632
+ scale=2.0,
1633
+ ),
1634
+ graspable=False,
1635
+ washable=True,
1636
+ microwavable=False,
1637
+ cookable=True,
1638
+ freezable=True,
1639
+ types=("vegetable"),
1640
+ ),
1641
+ lettuce=dict(
1642
+ aigen=dict(
1643
+ scale=2.0,
1644
+ ),
1645
+ graspable=False,
1646
+ washable=True,
1647
+ microwavable=False,
1648
+ cookable=False,
1649
+ freezable=True,
1650
+ types=("vegetable"),
1651
+ ),
1652
+ tongs=dict(
1653
+ aigen=dict(
1654
+ scale=1.5,
1655
+ ),
1656
+ graspable=True,
1657
+ washable=True,
1658
+ microwavable=False,
1659
+ cookable=False,
1660
+ freezable=False,
1661
+ types=("tool"),
1662
+ ),
1663
+ ginger=dict(
1664
+ aigen=dict(
1665
+ scale=1.35,
1666
+ ),
1667
+ graspable=True,
1668
+ washable=True,
1669
+ microwavable=False,
1670
+ cookable=True,
1671
+ freezable=True,
1672
+ types=("vegetable"),
1673
+ ),
1674
+ ice_cube_tray=dict(
1675
+ aigen=dict(
1676
+ scale=2.0,
1677
+ ),
1678
+ graspable=True,
1679
+ washable=True,
1680
+ microwavable=False,
1681
+ cookable=False,
1682
+ freezable=True,
1683
+ types=("receptacle"),
1684
+ ),
1685
+ shrimp=dict(
1686
+ aigen=dict(
1687
+ scale=1.15,
1688
+ ),
1689
+ graspable=False,
1690
+ washable=True,
1691
+ microwavable=True,
1692
+ cookable=True,
1693
+ freezable=True,
1694
+ types=("meat"),
1695
+ ),
1696
+ cantaloupe=dict(
1697
+ aigen=dict(
1698
+ scale=1.5,
1699
+ ),
1700
+ graspable=False,
1701
+ washable=True,
1702
+ microwavable=False,
1703
+ cookable=False,
1704
+ freezable=True,
1705
+ types=("fruit"),
1706
+ ),
1707
+ honey_bottle=dict(
1708
+ aigen=dict(
1709
+ scale=1.10,
1710
+ ),
1711
+ graspable=True,
1712
+ washable=False,
1713
+ microwavable=False,
1714
+ cookable=False,
1715
+ freezable=True,
1716
+ types=("packaged_food"),
1717
+ ),
1718
+ grapes=dict(
1719
+ aigen=dict(
1720
+ scale=1.5,
1721
+ ),
1722
+ graspable=True,
1723
+ washable=True,
1724
+ microwavable=False,
1725
+ cookable=False,
1726
+ freezable=True,
1727
+ types=("fruit"),
1728
+ ),
1729
+ spaghetti_box=dict(
1730
+ aigen=dict(
1731
+ scale=1.25,
1732
+ ),
1733
+ graspable=False,
1734
+ washable=False,
1735
+ microwavable=False,
1736
+ cookable=False,
1737
+ freezable=False,
1738
+ types=("packaged_food"),
1739
+ ),
1740
+ chili_pepper=dict(
1741
+ aigen=dict(
1742
+ scale=1.10,
1743
+ ),
1744
+ graspable=True,
1745
+ washable=True,
1746
+ microwavable=True,
1747
+ cookable=True,
1748
+ freezable=True,
1749
+ types=("vegetable"),
1750
+ ),
1751
+ celery=dict(
1752
+ aigen=dict(
1753
+ scale=2.0,
1754
+ ),
1755
+ graspable=True,
1756
+ washable=True,
1757
+ microwavable=True,
1758
+ cookable=True,
1759
+ freezable=True,
1760
+ types=("vegetable"),
1761
+ ),
1762
+ burrito=dict(
1763
+ aigen=dict(
1764
+ scale=1.35,
1765
+ ),
1766
+ graspable=True,
1767
+ washable=False,
1768
+ microwavable=True,
1769
+ cookable=False,
1770
+ freezable=True,
1771
+ types=("cooked_food"),
1772
+ ),
1773
+ olive_oil_bottle=dict(
1774
+ aigen=dict(
1775
+ scale=1.5,
1776
+ ),
1777
+ graspable=True,
1778
+ washable=False,
1779
+ microwavable=False,
1780
+ cookable=False,
1781
+ freezable=True,
1782
+ types=("packaged_food"),
1783
+ ),
1784
+ kebabs=dict(
1785
+ aigen=dict(
1786
+ scale=1.65,
1787
+ ),
1788
+ graspable=True,
1789
+ washable=False,
1790
+ microwavable=True,
1791
+ cookable=True,
1792
+ freezable=True,
1793
+ types=("cooked_food"),
1794
+ ),
1795
+ bottle_opener=dict(
1796
+ aigen=dict(),
1797
+ graspable=False,
1798
+ washable=True,
1799
+ microwavable=False,
1800
+ cookable=False,
1801
+ freezable=True,
1802
+ types=("tool"),
1803
+ ),
1804
+ chicken_breast=dict(
1805
+ aigen=dict(
1806
+ scale=1.35,
1807
+ ),
1808
+ graspable=True,
1809
+ washable=True,
1810
+ microwavable=True,
1811
+ cookable=True,
1812
+ freezable=True,
1813
+ types=("meat"),
1814
+ ),
1815
+ jello_cup=dict(
1816
+ aigen=dict(
1817
+ scale=1.15,
1818
+ ),
1819
+ graspable=True,
1820
+ washable=False,
1821
+ microwavable=False,
1822
+ cookable=False,
1823
+ freezable=True,
1824
+ types=("packaged_food"),
1825
+ ),
1826
+ lobster=dict(
1827
+ aigen=dict(
1828
+ scale=1.15,
1829
+ ),
1830
+ graspable=True,
1831
+ washable=True,
1832
+ microwavable=True,
1833
+ cookable=True,
1834
+ freezable=True,
1835
+ types=("meat"),
1836
+ ),
1837
+ brussel_sprout=dict(
1838
+ aigen=dict(),
1839
+ graspable=True,
1840
+ washable=True,
1841
+ microwavable=True,
1842
+ cookable=True,
1843
+ freezable=True,
1844
+ types=("vegetable"),
1845
+ ),
1846
+ sushi=dict(
1847
+ aigen=dict(
1848
+ scale=0.90,
1849
+ ),
1850
+ graspable=True,
1851
+ washable=False,
1852
+ microwavable=False,
1853
+ cookable=False,
1854
+ freezable=True,
1855
+ types=("meat"),
1856
+ ),
1857
+ baking_sheet=dict(
1858
+ aigen=dict(
1859
+ scale=1.75,
1860
+ ),
1861
+ graspable=False,
1862
+ washable=True,
1863
+ microwavable=False,
1864
+ cookable=False,
1865
+ freezable=False,
1866
+ types=("receptacle"),
1867
+ ),
1868
+ wine_glass=dict(
1869
+ aigen=dict(
1870
+ scale=1.5,
1871
+ ),
1872
+ infinigen=dict(
1873
+ scale=1.0,
1874
+ ),
1875
+ graspable=True,
1876
+ washable=True,
1877
+ microwavable=True,
1878
+ cookable=False,
1879
+ freezable=True,
1880
+ types=("receptacle"),
1881
+ ),
1882
+ asparagus=dict(
1883
+ aigen=dict(
1884
+ scale=1.35,
1885
+ ),
1886
+ graspable=True,
1887
+ washable=True,
1888
+ microwavable=True,
1889
+ cookable=True,
1890
+ freezable=True,
1891
+ types=("vegetable"),
1892
+ ),
1893
+ lamb_chop=dict(
1894
+ aigen=dict(
1895
+ scale=1.15,
1896
+ ),
1897
+ graspable=True,
1898
+ washable=True,
1899
+ microwavable=True,
1900
+ cookable=True,
1901
+ freezable=True,
1902
+ types=("meat"),
1903
+ ),
1904
+ pickle=dict(
1905
+ aigen=dict(
1906
+ scale=1.0,
1907
+ ),
1908
+ graspable=True,
1909
+ washable=True,
1910
+ microwavable=False,
1911
+ cookable=False,
1912
+ freezable=True,
1913
+ types=("vegetable"),
1914
+ ),
1915
+ bacon=dict(
1916
+ aigen=dict(
1917
+ scale=1.35,
1918
+ ),
1919
+ graspable=False,
1920
+ washable=False,
1921
+ microwavable=True,
1922
+ cookable=True,
1923
+ freezable=False,
1924
+ types=("meat"),
1925
+ ),
1926
+ canola_oil=dict(
1927
+ aigen=dict(
1928
+ scale=1.75,
1929
+ ),
1930
+ graspable=True,
1931
+ washable=False,
1932
+ microwavable=False,
1933
+ cookable=False,
1934
+ freezable=False,
1935
+ types=("packaged_food"),
1936
+ ),
1937
+ strawberry=dict(
1938
+ aigen=dict(
1939
+ scale=0.9,
1940
+ ),
1941
+ graspable=True,
1942
+ washable=True,
1943
+ microwavable=False,
1944
+ cookable=False,
1945
+ freezable=True,
1946
+ types=("fruit"),
1947
+ ),
1948
+ watermelon=dict(
1949
+ aigen=dict(
1950
+ scale=2.5,
1951
+ ),
1952
+ graspable=False,
1953
+ washable=True,
1954
+ microwavable=False,
1955
+ cookable=False,
1956
+ freezable=False,
1957
+ types=("fruit"),
1958
+ ),
1959
+ pizza_cutter=dict(
1960
+ aigen=dict(
1961
+ scale=1.4,
1962
+ ),
1963
+ graspable=False,
1964
+ washable=True,
1965
+ microwavable=False,
1966
+ cookable=False,
1967
+ freezable=False,
1968
+ types=("tool"),
1969
+ ),
1970
+ pomegranate=dict(
1971
+ aigen=dict(
1972
+ scale=1.25,
1973
+ ),
1974
+ graspable=True,
1975
+ washable=True,
1976
+ microwavable=False,
1977
+ cookable=False,
1978
+ freezable=False,
1979
+ types=("fruit"),
1980
+ ),
1981
+ apricot=dict(
1982
+ aigen=dict(
1983
+ scale=0.7,
1984
+ ),
1985
+ graspable=True,
1986
+ washable=True,
1987
+ microwavable=False,
1988
+ cookable=False,
1989
+ freezable=False,
1990
+ types=("fruit"),
1991
+ ),
1992
+ beet=dict(
1993
+ aigen=dict(),
1994
+ graspable=True,
1995
+ washable=True,
1996
+ microwavable=False,
1997
+ cookable=True,
1998
+ freezable=False,
1999
+ types=("vegetable"),
2000
+ ),
2001
+ radish=dict(
2002
+ aigen=dict(
2003
+ scale=1.0,
2004
+ ),
2005
+ graspable=True,
2006
+ washable=True,
2007
+ microwavable=False,
2008
+ cookable=False,
2009
+ freezable=False,
2010
+ types=("vegetable"),
2011
+ ),
2012
+ salsa=dict(
2013
+ aigen=dict(
2014
+ scale=1.15,
2015
+ ),
2016
+ graspable=True,
2017
+ washable=False,
2018
+ microwavable=False,
2019
+ cookable=False,
2020
+ freezable=False,
2021
+ types=("packaged_food"),
2022
+ ),
2023
+ artichoke=dict(
2024
+ aigen=dict(
2025
+ scale=1.35,
2026
+ ),
2027
+ graspable=True,
2028
+ washable=True,
2029
+ microwavable=False,
2030
+ cookable=True,
2031
+ freezable=False,
2032
+ types=("vegetable"),
2033
+ ),
2034
+ scone=dict(
2035
+ aigen=dict(
2036
+ scale=1.35,
2037
+ ),
2038
+ graspable=True,
2039
+ washable=False,
2040
+ microwavable=False,
2041
+ cookable=False,
2042
+ freezable=False,
2043
+ types=("pastry", "bread_food"),
2044
+ ),
2045
+ hamburger=dict(
2046
+ aigen=dict(
2047
+ scale=1.35,
2048
+ ),
2049
+ graspable=True,
2050
+ washable=False,
2051
+ microwavable=True,
2052
+ cookable=False,
2053
+ freezable=False,
2054
+ types=("cooked_food"),
2055
+ ),
2056
+ raspberry=dict(
2057
+ aigen=dict(
2058
+ scale=0.85,
2059
+ ),
2060
+ graspable=False,
2061
+ washable=True,
2062
+ microwavable=False,
2063
+ cookable=False,
2064
+ freezable=True,
2065
+ types=("fruit"),
2066
+ ),
2067
+ tacos=dict(
2068
+ aigen=dict(
2069
+ scale=1.0,
2070
+ ),
2071
+ graspable=True,
2072
+ washable=False,
2073
+ microwavable=True,
2074
+ cookable=False,
2075
+ freezable=False,
2076
+ types=("cooked_food"),
2077
+ ),
2078
+ vinegar=dict(
2079
+ aigen=dict(
2080
+ scale=1.4,
2081
+ ),
2082
+ graspable=True,
2083
+ washable=False,
2084
+ microwavable=False,
2085
+ cookable=False,
2086
+ freezable=False,
2087
+ types=("packaged_food", "condiment"),
2088
+ ),
2089
+ zucchini=dict(
2090
+ aigen=dict(
2091
+ scale=1.35,
2092
+ ),
2093
+ graspable=True,
2094
+ washable=True,
2095
+ microwavable=True,
2096
+ cookable=True,
2097
+ freezable=True,
2098
+ types=("vegetable"),
2099
+ ),
2100
+ pork_loin=dict(
2101
+ aigen=dict(),
2102
+ graspable=True,
2103
+ washable=True,
2104
+ microwavable=True,
2105
+ cookable=True,
2106
+ freezable=True,
2107
+ types=("meat"),
2108
+ ),
2109
+ pork_chop=dict(
2110
+ aigen=dict(
2111
+ scale=1.25,
2112
+ ),
2113
+ graspable=True,
2114
+ washable=True,
2115
+ microwavable=True,
2116
+ cookable=True,
2117
+ freezable=True,
2118
+ types=("meat"),
2119
+ ),
2120
+ sausage=dict(
2121
+ aigen=dict(
2122
+ scale=1.45,
2123
+ ),
2124
+ graspable=True,
2125
+ washable=True,
2126
+ microwavable=True,
2127
+ cookable=True,
2128
+ freezable=True,
2129
+ types=("meat"),
2130
+ ),
2131
+ coconut=dict(
2132
+ aigen=dict(
2133
+ scale=2.0,
2134
+ ),
2135
+ graspable=False,
2136
+ washable=True,
2137
+ microwavable=False,
2138
+ cookable=False,
2139
+ freezable=False,
2140
+ types=("fruit"),
2141
+ ),
2142
+ cauliflower=dict(
2143
+ aigen=dict(
2144
+ scale=1.5,
2145
+ ),
2146
+ graspable=False,
2147
+ washable=True,
2148
+ microwavable=True,
2149
+ cookable=True,
2150
+ freezable=True,
2151
+ types=("vegetable"),
2152
+ ),
2153
+ lollipop=dict(
2154
+ aigen=dict(),
2155
+ graspable=False,
2156
+ washable=False,
2157
+ microwavable=False,
2158
+ cookable=False,
2159
+ freezable=False,
2160
+ types=("sweets"),
2161
+ ),
2162
+ salami=dict(
2163
+ aigen=dict(
2164
+ scale=1.5,
2165
+ ),
2166
+ graspable=True,
2167
+ washable=True,
2168
+ microwavable=True,
2169
+ cookable=True,
2170
+ freezable=True,
2171
+ types=("meat"),
2172
+ ),
2173
+ butter_stick=dict(
2174
+ aigen=dict(
2175
+ scale=1.3,
2176
+ ),
2177
+ graspable=True,
2178
+ washable=False,
2179
+ microwavable=True,
2180
+ cookable=True,
2181
+ freezable=True,
2182
+ types=("dairy"),
2183
+ ),
2184
+ can_opener=dict(
2185
+ aigen=dict(
2186
+ scale=1.5,
2187
+ ),
2188
+ graspable=False,
2189
+ washable=True,
2190
+ microwavable=False,
2191
+ cookable=False,
2192
+ freezable=False,
2193
+ types=("tool"),
2194
+ ),
2195
+ tofu=dict(
2196
+ aigen=dict(),
2197
+ graspable=True,
2198
+ washable=True,
2199
+ microwavable=False,
2200
+ cookable=True,
2201
+ freezable=True,
2202
+ types=(),
2203
+ ),
2204
+ pineapple=dict(
2205
+ aigen=dict(
2206
+ scale=2.0,
2207
+ ),
2208
+ graspable=False,
2209
+ washable=True,
2210
+ microwavable=False,
2211
+ cookable=False,
2212
+ freezable=True,
2213
+ types=("fruit"),
2214
+ ),
2215
+ skewers=dict(
2216
+ aigen=dict(
2217
+ scale=1.75,
2218
+ ),
2219
+ graspable=True,
2220
+ washable=True,
2221
+ microwavable=True,
2222
+ cookable=True,
2223
+ freezable=False,
2224
+ types=("meat", "cooked_food"),
2225
+ ),
2226
+ lid=dict(
2227
+ types=("receptacle"),
2228
+ graspable=False,
2229
+ washable=True,
2230
+ microwavable=False,
2231
+ cookable=False,
2232
+ freezable=False,
2233
+ infinigen=dict(
2234
+ scale=1.80,
2235
+ ),
2236
+ ),
2237
+ jar=dict(
2238
+ infinigen=dict(
2239
+ scale=1.00,
2240
+ ),
2241
+ graspable=True,
2242
+ washable=False,
2243
+ microwavable=False,
2244
+ cookable=False,
2245
+ freezable=True,
2246
+ types=("packaged_food"),
2247
+ ),
2248
+ chopstick=dict(
2249
+ types=("utensil"),
2250
+ graspable=False,
2251
+ washable=True,
2252
+ microwavable=True,
2253
+ cookable=True,
2254
+ freezable=False,
2255
+ infinigen=dict(
2256
+ scale=1.75,
2257
+ ),
2258
+ ),
2259
+ basket=dict(
2260
+ types=("receptacle"),
2261
+ graspable=False,
2262
+ washable=True,
2263
+ microwavable=False,
2264
+ cookable=False,
2265
+ freezable=False,
2266
+ infinigen=dict(
2267
+ scale=2.0,
2268
+ ),
2269
+ sketchfab=dict(
2270
+ scale=0.7,
2271
+ exclude=[
2272
+ "basket_5", # too narrow
2273
+ ],
2274
+ ),
2275
+ lightwheel=dict(
2276
+ exclude=[
2277
+ "Basket038", # odd shape
2278
+ ],
2279
+ ),
2280
+ ),
2281
+ tiered_basket=dict(
2282
+ types=("tiered_basket"),
2283
+ graspable=False,
2284
+ washable=True,
2285
+ microwavable=False,
2286
+ cookable=False,
2287
+ freezable=False,
2288
+ sketchfab=dict(
2289
+ scale=1.0,
2290
+ density=5000,
2291
+ solimp=(0.95, 0.98, 0.001),
2292
+ solref=(0.004, 1),
2293
+ ),
2294
+ lightwheel=dict(
2295
+ density=5000,
2296
+ solimp=(0.95, 0.98, 0.001),
2297
+ solref=(0.004, 1),
2298
+ exclude=[
2299
+ "TieredBasket008", # too complicated spawn region
2300
+ "TieredBasket011", # no space on the top layer
2301
+ "TieredBasket023", # no space on the top layer
2302
+ ],
2303
+ ),
2304
+ ),
2305
+ tiered_shelf=dict(
2306
+ types=("tiered_shelf"),
2307
+ graspable=False,
2308
+ washable=True,
2309
+ microwavable=False,
2310
+ cookable=False,
2311
+ freezable=False,
2312
+ # sketchfab=dict(
2313
+ # scale=1.0,
2314
+ # exclude=[
2315
+ # "tiered_shelf_0", # unstable
2316
+ # "tiered_shelf_1", # too high
2317
+ # "tiered_shelf_2", # too high
2318
+ # "tiered_shelf_3", # missing texture
2319
+ # "tiered_shelf_4", # too high
2320
+ # ],
2321
+ # density=5000,
2322
+ # solimp=(0.95, 0.98, 0.001),
2323
+ # solref=(0.004, 1),
2324
+ # ),
2325
+ lightwheel=dict(
2326
+ density=5000,
2327
+ solimp=(0.95, 0.98, 0.001),
2328
+ solref=(0.004, 1),
2329
+ exclude=[
2330
+ "TieredShelf004", # too high
2331
+ ],
2332
+ ),
2333
+ ),
2334
+ plate_rack=dict(
2335
+ types=("receptacle"),
2336
+ graspable=False,
2337
+ washable=True,
2338
+ microwavable=False,
2339
+ cookable=False,
2340
+ freezable=False,
2341
+ infinigen=dict(
2342
+ scale=1.50,
2343
+ ),
2344
+ ),
2345
+ large_shelf=dict(
2346
+ types=("receptacle"),
2347
+ graspable=False,
2348
+ washable=False,
2349
+ microwavable=False,
2350
+ cookable=False,
2351
+ freezable=False,
2352
+ infinigen=dict(
2353
+ scale=6.0,
2354
+ ),
2355
+ ),
2356
+ cell_shelf=dict(
2357
+ types=("receptacle"),
2358
+ graspable=False,
2359
+ washable=False,
2360
+ microwavable=False,
2361
+ cookable=False,
2362
+ freezable=False,
2363
+ infinigen=dict(
2364
+ scale=6.0,
2365
+ ),
2366
+ ),
2367
+ laptop=dict(
2368
+ types=("laptop"),
2369
+ graspable=True,
2370
+ washable=True,
2371
+ microwavable=False,
2372
+ cookable=False,
2373
+ freezable=False,
2374
+ sketchfab=dict(
2375
+ scale=1.0,
2376
+ ),
2377
+ ),
2378
+ )
2379
+
2380
+
2381
+ def get_cats_by_type(types, obj_registries=None):
2382
+ """
2383
+ Retrieves a list of item keys from the global `OBJ_CATEGORIES` dictionary based on the specified types.
2384
+
2385
+ Args:
2386
+ types (list): A list of valid types to filter items by. Only items with a matching type will be included.
2387
+ obj_registries (list): only consider categories belonging to these object registries
2388
+
2389
+ Returns:
2390
+ list: A list of keys from `OBJ_CATEGORIES` where the item's types intersect with the provided `types`.
2391
+ """
2392
+ types = set(types)
2393
+
2394
+ res = []
2395
+ for key, val in OBJ_CATEGORIES.items():
2396
+ # check if category is in one of valid object registries
2397
+ if obj_registries is not None:
2398
+ if isinstance(obj_registries, str):
2399
+ obj_registries = [obj_registries]
2400
+ if any([reg in val for reg in obj_registries]) is False:
2401
+ continue
2402
+
2403
+ if "types" in val:
2404
+ cat_types = val["types"]
2405
+ else:
2406
+ cat_types = list(val.values())[0].types
2407
+ if isinstance(cat_types, str):
2408
+ cat_types = [cat_types]
2409
+ cat_types = set(cat_types)
2410
+ # Access the "types" key in the dictionary using the correct syntax
2411
+ if len(cat_types.intersection(types)) > 0:
2412
+ res.append(key)
2413
+
2414
+ return res
2415
+
2416
+
2417
+ ### define all object categories ###
2418
+ OBJ_GROUPS = dict(
2419
+ all=list(OBJ_CATEGORIES.keys()),
2420
+ )
2421
+
2422
+ for k in OBJ_CATEGORIES:
2423
+ OBJ_GROUPS[k] = [k]
2424
+
2425
+ all_types = set()
2426
+ # populate all_types
2427
+ for cat, cat_meta_dict in OBJ_CATEGORIES.items():
2428
+ # types are common to both so we only need to examine one
2429
+ cat_types = cat_meta_dict["types"]
2430
+ if isinstance(cat_types, str):
2431
+ cat_types = [cat_types]
2432
+ all_types = all_types.union(cat_types)
2433
+
2434
+ for t in all_types:
2435
+ OBJ_GROUPS[t] = get_cats_by_type(types=[t])
2436
+
2437
+ OBJ_GROUPS["food"] = get_cats_by_type(
2438
+ [
2439
+ "vegetable",
2440
+ "fruit",
2441
+ "sweets",
2442
+ "dairy",
2443
+ "meat",
2444
+ "bread_food",
2445
+ "pastry",
2446
+ "cooked_food",
2447
+ ]
2448
+ )
2449
+ OBJ_GROUPS["in_container"] = get_cats_by_type(
2450
+ [
2451
+ "toy",
2452
+ "vegetable",
2453
+ "fruit",
2454
+ "sweets",
2455
+ "dairy",
2456
+ "meat",
2457
+ "bread_food",
2458
+ "pastry",
2459
+ "cooked_food",
2460
+ "drink",
2461
+ ]
2462
+ )
2463
+
2464
+ # custom groups
2465
+ OBJ_GROUPS["container"] = ["plate"] # , "bowl"]
2466
+ OBJ_GROUPS["kettle"] = ["kettle_electric", "kettle_non_electric"]
2467
+ OBJ_GROUPS["cookware"] = ["pan", "pot", "kettle_non_electric"]
2468
+ OBJ_GROUPS["pots_and_pans"] = ["pan", "pot"]
2469
+ OBJ_GROUPS["food_set1"] = [
2470
+ "apple",
2471
+ "baguette",
2472
+ "banana",
2473
+ "carrot",
2474
+ "cheese",
2475
+ "cucumber",
2476
+ "egg",
2477
+ "lemon",
2478
+ "orange",
2479
+ "potato",
2480
+ ]
2481
+ OBJ_GROUPS["group1"] = ["apple", "carrot", "banana", "bowl", "can"]
2482
+ OBJ_GROUPS["container_set2"] = ["plate", "bowl"]
2483
+
2484
+
2485
+ def get_all_obj_cats(
2486
+ groups: List[str] = None, registries: List[str] = None, attrs: List[str] = None
2487
+ ) -> List[str]:
2488
+ """Get all object categories for given groups, registries, and attributes."""
2489
+ if groups is None:
2490
+ groups = OBJ_GROUPS.keys()
2491
+ if registries is None:
2492
+ registries = {"objaverse", "sketchfab", "lightwheel"}
2493
+ if attrs is None:
2494
+ attrs = []
2495
+
2496
+ res = []
2497
+ for group in groups:
2498
+ for obj_cat in OBJ_GROUPS[group]:
2499
+ if any(
2500
+ registry in OBJ_CATEGORIES[obj_cat]
2501
+ and len(OBJ_CATEGORIES[obj_cat][registry].mjcf_paths) > 0
2502
+ and all(
2503
+ getattr(OBJ_CATEGORIES[obj_cat][registry], attr, False)
2504
+ for attr in attrs
2505
+ )
2506
+ for registry in registries
2507
+ ):
2508
+ res.append(obj_cat)
2509
+ return res
third_party/robocasa/robocasa/models/objects/objects.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import xml.etree.ElementTree as ET
4
+
5
+ import mujoco
6
+ import numpy as np
7
+ import robosuite
8
+ import robosuite.utils.transform_utils as T
9
+ from robosuite.models.objects import MujocoXMLObject
10
+ from robosuite.utils.mjcf_utils import array_to_string, string_to_array
11
+ from robosuite.environments.robot_env import RobotEnv
12
+
13
+
14
+ class MJCFObject(MujocoXMLObject):
15
+ """
16
+ Blender object with support for changing the scaling
17
+ """
18
+
19
+ def __init__(
20
+ self,
21
+ name,
22
+ mjcf_path,
23
+ scale=1.0,
24
+ solimp=(0.998, 0.998, 0.001),
25
+ solref=(0.001, 1),
26
+ density=100,
27
+ friction=(0.95, 0.3, 0.1),
28
+ margin=None,
29
+ rgba=None,
30
+ priority=None,
31
+ static=False,
32
+ ):
33
+ # get scale in x, y, z
34
+ if isinstance(scale, float):
35
+ scale = [scale, scale, scale]
36
+ elif isinstance(scale, tuple) or isinstance(scale, list):
37
+ assert len(scale) == 3
38
+ scale = tuple(scale)
39
+ else:
40
+ raise Exception("got invalid scale: {}".format(scale))
41
+ scale = np.array(scale)
42
+
43
+ self.solimp = solimp
44
+ self.solref = solref
45
+ self.density = density
46
+ self.friction = friction
47
+ self.margin = margin
48
+
49
+ self.priority = priority
50
+
51
+ self.rgba = rgba
52
+
53
+ # read default xml
54
+ xml_path = mjcf_path
55
+ folder = os.path.dirname(xml_path)
56
+ tree = ET.parse(xml_path)
57
+ root = tree.getroot()
58
+
59
+ # write modified xml (and make sure to postprocess any paths just in case)
60
+ xml_str = ET.tostring(root, encoding="utf8").decode("utf8")
61
+ xml_str = self.postprocess_model_xml(xml_str)
62
+ time_str = str(time.time()).replace(".", "_")
63
+ new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid()))
64
+ f = open(new_xml_path, "w")
65
+ f.write(xml_str)
66
+ f.close()
67
+
68
+ # initialize object with new xml we wrote
69
+ super().__init__(
70
+ fname=new_xml_path,
71
+ name=name,
72
+ joints=None if static else [dict(type="free", damping="0.0005")],
73
+ obj_type="all",
74
+ duplicate_collision_geoms=False,
75
+ scale=scale,
76
+ )
77
+
78
+ self.spawns = []
79
+ self._disabled_spawns = set()
80
+ for s in self.worldbody.findall("./body/body/geom"):
81
+ geom_name = s.get("name")
82
+ if geom_name and geom_name.startswith(
83
+ "{}spawn_".format(self.naming_prefix)
84
+ ):
85
+ self.spawns.append(s)
86
+
87
+ # clean up xml - we don't need it anymore
88
+ if os.path.exists(new_xml_path):
89
+ os.remove(new_xml_path)
90
+
91
+ def postprocess_model_xml(self, xml_str):
92
+ """
93
+ New version of postprocess model xml that only replaces robosuite file paths if necessary (otherwise
94
+ there is an error with the "max" operation)
95
+ """
96
+
97
+ path = os.path.split(robosuite.__file__)[0]
98
+ path_split = path.split("/")
99
+
100
+ # replace mesh and texture file paths
101
+ tree = ET.fromstring(xml_str)
102
+ root = tree
103
+ asset = root.find("asset")
104
+ meshes = asset.findall("mesh")
105
+ textures = asset.findall("texture")
106
+ all_elements = meshes + textures
107
+
108
+ for elem in all_elements:
109
+ old_path = elem.get("file")
110
+ if old_path is None:
111
+ continue
112
+
113
+ old_path_split = old_path.split("/")
114
+ # maybe replace all paths to robosuite assets
115
+ check_lst = [
116
+ loc for loc, val in enumerate(old_path_split) if val == "robosuite"
117
+ ]
118
+ if len(check_lst) > 0:
119
+ ind = max(check_lst) # last occurrence index
120
+ new_path_split = path_split + old_path_split[ind + 1 :]
121
+ new_path = "/".join(new_path_split)
122
+ elem.set("file", new_path)
123
+
124
+ return ET.tostring(root, encoding="utf8").decode("utf8")
125
+
126
+ def _get_geoms(self, root, _parent=None):
127
+ """
128
+ Helper function to recursively search through element tree starting at @root and returns
129
+ a list of (parent, child) tuples where the child is a geom element
130
+
131
+ Args:
132
+ root (ET.Element): Root of xml element tree to start recursively searching through
133
+
134
+ _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set
135
+ during the recursive call
136
+
137
+ Returns:
138
+ list: array of (parent, child) tuples where the child element is a geom type
139
+ """
140
+ geom_pairs = super(MJCFObject, self)._get_geoms(root=root, _parent=_parent)
141
+
142
+ # modify geoms according to the attributes
143
+ for i, (parent, element) in enumerate(geom_pairs):
144
+ element.set("solref", array_to_string(self.solref))
145
+ element.set("solimp", array_to_string(self.solimp))
146
+ element.set("density", str(self.density))
147
+ element.set("friction", array_to_string(self.friction))
148
+ if self.margin is not None:
149
+ element.set("margin", str(self.margin))
150
+
151
+ if (self.rgba is not None) and (element.get("group") == "1"):
152
+ element.set("rgba", array_to_string(self.rgba))
153
+
154
+ if self.priority is not None:
155
+ # set high priorit
156
+ element.set("priority", str(self.priority))
157
+
158
+ return geom_pairs
159
+
160
+ def get_joint(self, joint_name: str):
161
+ _, _, joints = self._get_elements_by_name(
162
+ geom_names=[], body_names=[], joint_names=[joint_name]
163
+ )
164
+ return joints[joint_name]
165
+
166
+ @property
167
+ def horizontal_radius(self):
168
+ horizontal_radius_site = self.worldbody.find(
169
+ "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix)
170
+ )
171
+ site_values = string_to_array(horizontal_radius_site.get("pos"))
172
+ return np.linalg.norm(site_values[0:2])
173
+
174
+ def get_bbox_points(self, trans=None, rot=None) -> list[np.ndarray]:
175
+ """
176
+ Get the full 8 bounding box points of the object
177
+ rot: a rotation matrix
178
+ """
179
+ bottom_offset = self.bottom_offset
180
+ top_offset = self.top_offset
181
+ horizontal_radius_site = self.worldbody.find(
182
+ "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix)
183
+ )
184
+ horiz_radius = string_to_array(horizontal_radius_site.get("pos"))[:2]
185
+ return self._get_bbox_points(
186
+ bottom_offset=bottom_offset,
187
+ top_offset=top_offset,
188
+ radius=horiz_radius,
189
+ trans=trans,
190
+ rot=rot,
191
+ )
192
+
193
+ @staticmethod
194
+ def _get_bbox_points(
195
+ bottom_offset, top_offset, radius, trans=None, rot=None
196
+ ) -> list[np.ndarray]:
197
+ """
198
+ Helper function to get the full 8 bounding box points of the object.
199
+ """
200
+ center = np.mean([bottom_offset, top_offset], axis=0)
201
+ half_size = [radius[0], radius[1], top_offset[2] - center[2]]
202
+
203
+ bbox_offsets = [
204
+ center + half_size * np.array([-1, -1, -1]), # p0
205
+ center + half_size * np.array([1, -1, -1]), # px
206
+ center + half_size * np.array([-1, 1, -1]), # py
207
+ center + half_size * np.array([-1, -1, 1]), # pz
208
+ center + half_size * np.array([1, 1, 1]),
209
+ center + half_size * np.array([-1, 1, 1]),
210
+ center + half_size * np.array([1, -1, 1]),
211
+ center + half_size * np.array([1, 1, -1]),
212
+ ]
213
+
214
+ if trans is None:
215
+ trans = np.array([0, 0, 0])
216
+ if rot is not None:
217
+ rot = T.quat2mat(rot)
218
+ else:
219
+ rot = np.eye(3)
220
+
221
+ points = [(np.matmul(rot, p) + trans) for p in bbox_offsets]
222
+ return points
223
+
224
+ @staticmethod
225
+ def get_spawn_bottom_offset(site: ET.Element) -> np.array:
226
+ """
227
+ Get bottom offset of the spawn zone.
228
+ """
229
+ site_pos = string_to_array(site.get("pos"))
230
+ site_size = (
231
+ string_to_array(site.get("size"))
232
+ if site.get("type") == "box"
233
+ else np.zeros(3)
234
+ )
235
+ return site_pos - np.array([0, 0, site_size[-1]])
236
+
237
+ def get_random_spawn(
238
+ self, rng, exclude_disabled: bool = False
239
+ ) -> tuple[int, ET.Element]:
240
+ """
241
+ Get random spawn site.
242
+ """
243
+ options = [o for o in range(0, len(self.spawns))]
244
+ if exclude_disabled:
245
+ options = [o for o in options if o not in self._disabled_spawns]
246
+ spawn_id = rng.choice(options)
247
+ return spawn_id, self.spawns[spawn_id]
248
+
249
+ def set_spawn_active(self, spawn_id: int, active: bool):
250
+ """
251
+ Update the activity state of a spawn site. Disabled sites are excluded from random sampling.
252
+ """
253
+ if active and spawn_id in self._disabled_spawns:
254
+ self._disabled_spawns.remove(spawn_id)
255
+ elif not active:
256
+ self._disabled_spawns.add(spawn_id)
257
+
258
+ def closest_spawn_id(
259
+ self, env: RobotEnv, obj: "MJCFObject", max_distance: float = 1.0
260
+ ) -> int:
261
+ if len(self.spawns) == 0:
262
+ return -1
263
+ if not env.check_contact(self, obj):
264
+ return -1
265
+ obj_pos = env.sim.data.body_xpos[env.sim.model.body_name2id(obj.root_body)]
266
+ distances = []
267
+ for spawn_id in range(len(self.spawns)):
268
+ spawn_pos = env.sim.data.get_geom_xpos(self.spawns[spawn_id].get("name"))
269
+ distance = np.linalg.norm(spawn_pos - obj_pos)
270
+ distances.append((spawn_id, distance))
271
+ distances = sorted(distances, key=lambda item: item[1])
272
+ obj_geom_ids = [env.sim.model.geom_name2id(g) for g in obj.contact_geoms]
273
+ for spawn_id, distance in distances:
274
+ spawn_geom_id = env.sim.model.geom_name2id(
275
+ self.spawns[spawn_id].get("name")
276
+ )
277
+ for obj_geom_id in obj_geom_ids:
278
+ real_distance = mujoco.mj_geomDistance(
279
+ m=env.sim.model._model,
280
+ d=env.sim.data._data,
281
+ geom1=spawn_geom_id,
282
+ geom2=obj_geom_id,
283
+ distmax=max_distance,
284
+ fromto=None,
285
+ )
286
+ if real_distance <= 0:
287
+ return spawn_id
288
+ if real_distance >= max_distance:
289
+ return -1
290
+ return -1
third_party/robocasa/robocasa/models/objects/xml_objects.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import xml.etree.ElementTree as ET
4
+ import numpy as np
5
+ from robosuite.models.objects import MujocoXMLObject
6
+ from robosuite.utils.mjcf_utils import array_to_string, find_elements, string_to_array
7
+ import robocasa
8
+
9
+ XML_ASSETS_BASE_PATH = os.path.join(robocasa.__path__[0], "models/assets/gear_kitchen")
10
+
11
+
12
+ class BlenderObject(MujocoXMLObject):
13
+ """
14
+ Blender object with support for changing the scaling
15
+ """
16
+
17
+ def __init__(
18
+ self,
19
+ name,
20
+ mjcf_path,
21
+ scale=1.0,
22
+ solimp=(0.998, 0.998, 0.001),
23
+ solref=(0.001, 1),
24
+ density=100,
25
+ friction=(0.95, 0.3, 0.1),
26
+ margin=None,
27
+ rgba=None,
28
+ ):
29
+ # get scale in x, y, z
30
+ if isinstance(scale, float):
31
+ scale = [scale, scale, scale]
32
+ elif isinstance(scale, tuple) or isinstance(scale, list):
33
+ assert len(scale) == 3
34
+ scale = tuple(scale)
35
+ else:
36
+ raise Exception("got invalid scale: {}".format(scale))
37
+ scale = np.array(scale)
38
+
39
+ self.solimp = solimp
40
+ self.solref = solref
41
+ self.density = density
42
+ self.friction = friction
43
+ self.margin = margin
44
+
45
+ self.rgba = rgba
46
+
47
+ # read default xml
48
+ xml_path = mjcf_path
49
+ folder = os.path.dirname(xml_path)
50
+ tree = ET.parse(xml_path)
51
+ root = tree.getroot()
52
+
53
+ # modify mesh scales
54
+ asset = root.find("asset")
55
+ meshes = asset.findall("mesh")
56
+ for mesh in meshes:
57
+ # if a scale already exists, multiply the scales
58
+ scale_to_set = scale
59
+ existing_scale = mesh.get("scale")
60
+ if existing_scale is not None:
61
+ scale_to_set = string_to_array(existing_scale) * scale
62
+ mesh.set("scale", array_to_string(scale_to_set))
63
+
64
+ # modify sites for collision (assumes we can just scale up the locations - may or may not work)
65
+ for n in ["bottom_site", "top_site", "horizontal_radius_site"]:
66
+ site = root.find("worldbody/body/site[@name='{}']".format(n))
67
+ pos = string_to_array(site.get("pos"))
68
+ pos = scale * pos
69
+ site.set("pos", array_to_string(pos))
70
+
71
+ # write modified xml (and make sure to postprocess any paths just in case)
72
+ xml_str = ET.tostring(root, encoding="utf8").decode("utf8")
73
+ # xml_str = postprocess_model_xml(xml_str)
74
+ time_str = str(time.time()).replace(".", "_")
75
+ new_xml_path = os.path.join(folder, "{}_{}.xml".format(time_str, os.getpid()))
76
+ f = open(new_xml_path, "w")
77
+ f.write(xml_str)
78
+ f.close()
79
+ # print(f"Write to {new_xml_path}")
80
+
81
+ # initialize object with new xml we wrote
82
+ super().__init__(
83
+ fname=new_xml_path,
84
+ name=name,
85
+ joints=[dict(type="free", damping="0.0005")],
86
+ obj_type="all",
87
+ duplicate_collision_geoms=False,
88
+ )
89
+
90
+ # clean up xml - we don't need it anymore
91
+ if os.path.exists(new_xml_path):
92
+ os.remove(new_xml_path)
93
+
94
+ def _get_geoms(self, root, _parent=None):
95
+ """
96
+ Helper function to recursively search through element tree starting at @root and returns
97
+ a list of (parent, child) tuples where the child is a geom element
98
+
99
+ Args:
100
+ root (ET.Element): Root of xml element tree to start recursively searching through
101
+ _parent (ET.Element): Parent of the root element tree. Should not be used externally; only set
102
+ during the recursive call
103
+
104
+ Returns:
105
+ list: array of (parent, child) tuples where the child element is a geom type
106
+ """
107
+ geom_pairs = super(BlenderObject, self)._get_geoms(root=root, _parent=_parent)
108
+
109
+ # modify geoms according to the attributes
110
+ for i, (parent, element) in enumerate(geom_pairs):
111
+ element.set("solref", array_to_string(self.solref))
112
+ element.set("solimp", array_to_string(self.solimp))
113
+ element.set("density", str(self.density))
114
+ element.set("friction", array_to_string(self.friction))
115
+ if self.margin is not None:
116
+ element.set("margin", str(self.margin))
117
+
118
+ if (self.rgba is not None) and (element.get("group") == "1"):
119
+ element.set("rgba", array_to_string(self.rgba))
120
+
121
+ return geom_pairs
122
+
123
+
124
+ class CoffeeMachinePodObject(MujocoXMLObject):
125
+ """
126
+ Coffee pod object (used in Coffee task).
127
+ """
128
+
129
+ def __init__(self, name, margin=1.0):
130
+ self._horizontal_radius_margin = margin
131
+ super().__init__(
132
+ os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_pod.xml"),
133
+ # name=name, joints=[dict(type="free", damping="0.0005")],
134
+ name=name,
135
+ joints=[dict(type="free")],
136
+ obj_type="all",
137
+ duplicate_collision_geoms=True,
138
+ )
139
+
140
+ @property
141
+ def horizontal_radius(self):
142
+ horizontal_radius_site = self.worldbody.find(
143
+ "./body/site[@name='{}horizontal_radius_site']".format(self.naming_prefix)
144
+ )
145
+ return (
146
+ self._horizontal_radius_margin
147
+ * string_to_array(horizontal_radius_site.get("pos"))[0]
148
+ )
149
+
150
+
151
+ class CoffeeMachineBodyObject(MujocoXMLObject):
152
+ """
153
+ Coffee machine body piece (used in Coffee task). Note that the piece is rigid (no joint is added).
154
+ """
155
+
156
+ def __init__(self, name):
157
+ super().__init__(
158
+ os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_body.xml"),
159
+ name=name,
160
+ joints=None,
161
+ obj_type="all",
162
+ duplicate_collision_geoms=True,
163
+ )
164
+
165
+
166
+ class CoffeeMachineLidObject(MujocoXMLObject):
167
+ """
168
+ Coffee machine lid piece (used in Coffee task).
169
+ """
170
+
171
+ def __init__(self, name):
172
+ super().__init__(
173
+ os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_lid.xml"),
174
+ name=name,
175
+ joints=None,
176
+ obj_type="all",
177
+ duplicate_collision_geoms=True,
178
+ )
179
+
180
+
181
+ class CoffeeMachineBaseObject(MujocoXMLObject):
182
+ """
183
+ Coffee machine base piece (used in Coffee task). Note that the piece is rigid (no joint is added).
184
+ """
185
+
186
+ def __init__(self, name):
187
+ super().__init__(
188
+ os.path.join(XML_ASSETS_BASE_PATH, "objects/coffee_base.xml"),
189
+ name=name,
190
+ joints=None,
191
+ obj_type="all",
192
+ duplicate_collision_geoms=True,
193
+ )
194
+
195
+
196
+ class DrawerObject(MujocoXMLObject):
197
+ """
198
+ Custom version of cabinet object that differs from BUDs. It has manually specified top, bottom, and horizontal sites.
199
+ """
200
+
201
+ def __init__(self, name, joints=None):
202
+
203
+ # original cabinet xml
204
+ # path_to_cabinet_xml = os.path.join(robosuite_task_zoo.__path__[0], "models/hammer_place/cabinet.xml")
205
+
206
+ # our custom cabinet xml - names the drawer bottom geom for easy contact checking
207
+ # path_to_cabinet_xml = os.path.join(mimicgen.__path__[0], "envs/robosuite/assets/cabinet.xml")
208
+ path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet.xml")
209
+
210
+ # path to modified xml from Danfei's student
211
+ # path_to_cabinet_xml = os.path.join(XML_ASSETS_BASE_PATH, "objects/cabinet1.xml")
212
+
213
+ super().__init__(
214
+ path_to_cabinet_xml,
215
+ name=name,
216
+ joints=None,
217
+ obj_type="all",
218
+ duplicate_collision_geoms=True,
219
+ )
220
+
221
+ # NOTE: had to manually set these to get placement sampler working okay
222
+ @property
223
+ def bottom_offset(self):
224
+ return np.array([0, 0, -0.065])
225
+
226
+ @property
227
+ def top_offset(self):
228
+ return np.array([0, 0, 0.065])
229
+
230
+ @property
231
+ def horizontal_radius(self):
232
+ return 0.15
233
+
234
+ @property
235
+ def body_size(self):
236
+ return (0.5, 0.4, 0.3)
237
+
238
+
239
+ class LongDrawerObject(MujocoXMLObject):
240
+ """
241
+ Drawer that has longer platform for easier grasping of objects inside.
242
+ """
243
+
244
+ def __init__(self, name, joints=None):
245
+
246
+ # our custom cabinet xml - has some longer geoms for the drawer platform
247
+ path_to_cabinet_xml = os.path.join(
248
+ XML_ASSETS_BASE_PATH, "objects/drawer_long.xml"
249
+ )
250
+
251
+ super().__init__(
252
+ path_to_cabinet_xml,
253
+ name=name,
254
+ joints=None,
255
+ obj_type="all",
256
+ duplicate_collision_geoms=True,
257
+ )
258
+
259
+ # NOTE: had to manually set these to get placement sampler working okay
260
+ @property
261
+ def bottom_offset(self):
262
+ return np.array([0, 0, -0.065])
263
+
264
+ @property
265
+ def top_offset(self):
266
+ return np.array([0, 0, 0.065])
267
+
268
+ @property
269
+ def horizontal_radius(self):
270
+ # TODO: this might need to change now
271
+ return 0.15
third_party/robocasa/robocasa/models/robots/__init__.py ADDED
@@ -0,0 +1,748 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mujoco
2
+ import numpy as np
3
+
4
+ from robosuite.controllers.parts.generic.joint_pos import JointPositionController
5
+ from robosuite.controllers.parts.arm.osc import OperationalSpaceController
6
+ from robosuite.controllers.parts.gripper.simple_grip import SimpleGripController
7
+ from robosuite.controllers.composite.composite_controller import HybridMobileBase
8
+ from robosuite.models.grippers import (
9
+ PandaGripper,
10
+ InspireLeftHand,
11
+ InspireRightHand,
12
+ FourierLeftHand,
13
+ FourierRightHand,
14
+ )
15
+
16
+ from .manipulators import *
17
+
18
+
19
+ # This function returns in the order of the gripper XML's joints.
20
+ def unformat_gripper_space(gripper, formatted_action):
21
+ formatted_action = np.array(formatted_action)
22
+ if isinstance(gripper, InspireLeftHand) or isinstance(gripper, InspireRightHand):
23
+ action = formatted_action[[0, 2, 4, 6, 8, 11]]
24
+ elif isinstance(gripper, FourierLeftHand) or isinstance(gripper, FourierRightHand):
25
+ action = formatted_action[[0, 1, 4, 6, 8, 10]]
26
+ elif isinstance(gripper, PandaGripper):
27
+ action = formatted_action
28
+ else:
29
+ raise TypeError
30
+ return action
31
+
32
+
33
+ def _reconstruct_latest_action_gr1_impl(robot, verbose=False):
34
+ action_dict = {}
35
+ cc = robot.composite_controller
36
+ pf = robot.robot_model.naming_prefix
37
+
38
+ for part_name, controller in cc.part_controllers.items():
39
+ if isinstance(controller, JointPositionController):
40
+ assert controller.input_type == "absolute"
41
+ act = controller.goal_qpos
42
+ elif isinstance(controller, SimpleGripController):
43
+ assert not controller.use_action_scaling
44
+ act = unformat_gripper_space(cc.grippers[part_name], controller.goal_qvel)
45
+ else:
46
+ raise TypeError
47
+ action_dict[f"{pf}{part_name}"] = act
48
+
49
+ if verbose:
50
+ print("Actions:", [(k, len(action_dict[k])) for k in action_dict])
51
+
52
+ return action_dict
53
+
54
+
55
+ def _reconstruct_latest_action_panda_impl(robot, action, verbose=False):
56
+ action_dict = {}
57
+ cc = robot.composite_controller
58
+ pf = robot.robot_model.naming_prefix
59
+
60
+ for part_name, controller in cc.part_controllers.items():
61
+ start_idx, end_idx = cc._action_split_indexes[part_name]
62
+ act = action[start_idx:end_idx]
63
+ # split action deeper for OSC
64
+ action_dict[f"{pf}{part_name}"] = act
65
+
66
+ if verbose:
67
+ print("Actions:", [(k, len(action_dict[k])) for k in action_dict])
68
+
69
+ return action_dict
70
+
71
+
72
+ # This function tries to get all joints value, but sometimes we want to keep original action
73
+ # The function must be called after robot.control()
74
+ def reconstruct_latest_actions(env, actions=None, verbose=False):
75
+ if actions is None:
76
+ actions = np.zeros(env.action_dim)
77
+ action_dict = {}
78
+ cutoff = 0
79
+ for robot in env.robots:
80
+ cc = robot.composite_controller
81
+ pf = robot.robot_model.naming_prefix
82
+ robot_action = actions[cutoff : cutoff + robot.action_dim]
83
+ cutoff += robot.action_dim
84
+ if "GR1" in robot.name:
85
+ action_dict.update(_reconstruct_latest_action_gr1_impl(robot))
86
+ elif "Panda" in robot.name:
87
+ action_dict.update(
88
+ _reconstruct_latest_action_panda_impl(robot, robot_action)
89
+ )
90
+ else:
91
+ raise ValueError(f"Unknown robot name: {robot.name}")
92
+ if isinstance(cc, HybridMobileBase):
93
+ action_dict[f"{pf}base_mode"] = robot_action[-1]
94
+
95
+ if verbose:
96
+ print("Actions:", [(k, len(action_dict[k])) for k in action_dict])
97
+
98
+ return action_dict
99
+
100
+
101
+ def gather_robot_observations(env, verbose=False):
102
+ observations = {}
103
+
104
+ for robot_id, robot in enumerate(env.robots):
105
+ sim = robot.sim
106
+ gripper_names = {
107
+ robot.get_gripper_name(arm): robot.gripper[arm] for arm in robot.arms
108
+ }
109
+ for part_name, indexes in robot._ref_joints_indexes_dict.items():
110
+ qpos_values = []
111
+ for joint_id in indexes:
112
+ qpos_addr = sim.model.jnt_qposadr[joint_id]
113
+ # https://mujoco.readthedocs.io/en/stable/APIreference/APItypes.html#mjtjoint
114
+ joint_type = sim.model.jnt_type[joint_id]
115
+ if joint_type == mujoco.mjtJoint.mjJNT_FREE:
116
+ qpos_size = 7 # Free joint has 7 DOFs
117
+ elif joint_type == mujoco.mjtJoint.mjJNT_BALL:
118
+ qpos_size = 4 # Ball joint has 4 DOFs (quaternion)
119
+ else:
120
+ qpos_size = 1 # Revolute or prismatic joint has 1 DOF
121
+ qpos_values = np.append(
122
+ qpos_values, sim.data.qpos[qpos_addr : qpos_addr + qpos_size]
123
+ )
124
+ if part_name in gripper_names.keys():
125
+ gripper = gripper_names[part_name]
126
+ # Reverse the order to match the real robot
127
+ qpos_values = unformat_gripper_space(gripper, qpos_values)[::-1]
128
+ if len(qpos_values) > 0:
129
+ observations[f"robot{robot_id}_{part_name}"] = qpos_values
130
+
131
+ if verbose:
132
+ print("States:", [(k, len(observations[k])) for k in observations])
133
+
134
+ return observations
135
+
136
+
137
+ from gymnasium import spaces
138
+
139
+
140
+ class RobotKeyConverter:
141
+ @classmethod
142
+ def get_camera_config(cls):
143
+ raise NotImplementedError
144
+
145
+ @classmethod
146
+ def map_obs(cls, input_obs):
147
+ raise NotImplementedError
148
+
149
+ @classmethod
150
+ def map_action(cls, input_action):
151
+ raise NotImplementedError
152
+
153
+ @classmethod
154
+ def unmap_action(cls, input_action):
155
+ raise NotImplementedError
156
+
157
+ @classmethod
158
+ def get_metadata(cls, name):
159
+ raise NotImplementedError
160
+
161
+ @classmethod
162
+ def map_obs_in_eval(cls, input_obs):
163
+ output_obs = {}
164
+ mapped_obs = cls.map_obs(input_obs)
165
+ for k, v in mapped_obs.items():
166
+ assert k.startswith("hand.") or k.startswith("body.")
167
+ output_obs["state." + k[5:]] = v
168
+ return output_obs
169
+
170
+ @classmethod
171
+ def get_missing_keys_in_dumping_dataset(cls):
172
+ return {}
173
+
174
+ @classmethod
175
+ def convert_to_float64(cls, input):
176
+ for k, v in input.items():
177
+ if isinstance(v, np.ndarray) and v.dtype == np.float32:
178
+ input[k] = v.astype(np.float64)
179
+ return input
180
+
181
+ @classmethod
182
+ def deduce_observation_space(cls, env):
183
+ obs = (
184
+ env.viewer._get_observations(force_update=True)
185
+ if env.viewer_get_obs
186
+ else env._get_observations(force_update=True)
187
+ )
188
+ obs.update(gather_robot_observations(env))
189
+ obs = cls.map_obs(obs)
190
+ observation_space = spaces.Dict()
191
+
192
+ for k, v in obs.items():
193
+ if k.startswith("hand.") or k.startswith("body."):
194
+ observation_space["state." + k[5:]] = spaces.Box(
195
+ low=-1, high=1, shape=(len(v),), dtype=np.float32
196
+ )
197
+ else:
198
+ raise ValueError(f"Unknown key: {k}")
199
+
200
+ return observation_space
201
+
202
+ @classmethod
203
+ def deduce_action_space(cls, env):
204
+ action = cls.map_action(reconstruct_latest_actions(env))
205
+ action_space = spaces.Dict()
206
+ for k, v in action.items():
207
+ if isinstance(v, np.int64):
208
+ action_space["action." + k[5:]] = spaces.Discrete(2)
209
+ elif isinstance(v, np.ndarray):
210
+ action_space["action." + k[5:]] = spaces.Box(
211
+ low=-1, high=1, shape=(len(v),), dtype=np.float32
212
+ )
213
+ else:
214
+ raise ValueError(f"Unknown type: {type(v)}")
215
+ return action_space
216
+
217
+
218
+ class GR1ArmsOnlyKeyConverter(RobotKeyConverter):
219
+ @classmethod
220
+ def get_camera_config(cls):
221
+ mapped_names = ["video.ego_view_pad_res256_freq20"]
222
+ camera_names = [
223
+ "egoview",
224
+ ]
225
+ camera_widths, camera_heights = 1280, 800
226
+ return mapped_names, camera_names, camera_widths, camera_heights
227
+
228
+ @classmethod
229
+ def map_obs(cls, input_obs):
230
+ output_obs = type(input_obs)()
231
+ output_obs = {
232
+ "hand.right_hand": input_obs["robot0_right_gripper"],
233
+ "hand.left_hand": input_obs["robot0_left_gripper"],
234
+ "body.right_arm": input_obs["robot0_right"],
235
+ "body.left_arm": input_obs["robot0_left"],
236
+ }
237
+ return output_obs
238
+
239
+ @classmethod
240
+ def map_action(cls, input_action):
241
+ output_action = type(input_action)()
242
+ output_action = {
243
+ "hand.left_hand": input_action["robot0_left_gripper"],
244
+ "hand.right_hand": input_action["robot0_right_gripper"],
245
+ "body.left_arm": input_action["robot0_left"],
246
+ "body.right_arm": input_action["robot0_right"],
247
+ }
248
+ return output_action
249
+
250
+ @classmethod
251
+ def unmap_action(cls, input_action):
252
+ output_action = type(input_action)()
253
+ output_action = {
254
+ "robot0_left_gripper": input_action["action.left_hand"],
255
+ "robot0_right_gripper": input_action["action.right_hand"],
256
+ "robot0_left": input_action["action.left_arm"],
257
+ "robot0_right": input_action["action.right_arm"],
258
+ }
259
+ return output_action
260
+
261
+ @classmethod
262
+ def get_missing_keys_in_dumping_dataset(cls):
263
+ return {
264
+ "body.waist": np.zeros(3, dtype=np.float64),
265
+ "body.neck": np.zeros(3, dtype=np.float64),
266
+ "body.right_leg": np.zeros(6, dtype=np.float64),
267
+ "body.left_leg": np.zeros(6, dtype=np.float64),
268
+ }
269
+
270
+ @classmethod
271
+ def get_metadata(cls, name):
272
+ return {
273
+ "absolute": True,
274
+ "rotation_type": None,
275
+ }
276
+
277
+
278
+ class GR1ArmsAndWaistKeyConverter(RobotKeyConverter):
279
+ @classmethod
280
+ def get_camera_config(cls):
281
+ mapped_names = ["video.ego_view_pad_res256_freq20"]
282
+ camera_names = [
283
+ "egoview",
284
+ ]
285
+ camera_widths, camera_heights = 1280, 800
286
+ return mapped_names, camera_names, camera_widths, camera_heights
287
+
288
+ @classmethod
289
+ def map_obs(cls, input_obs):
290
+ output_obs = type(input_obs)()
291
+ output_obs = {
292
+ "hand.right_hand": input_obs["robot0_right_gripper"],
293
+ "hand.left_hand": input_obs["robot0_left_gripper"],
294
+ "body.right_arm": input_obs["robot0_right"],
295
+ "body.left_arm": input_obs["robot0_left"],
296
+ "body.waist": input_obs["robot0_torso"],
297
+ }
298
+ return output_obs
299
+
300
+ @classmethod
301
+ def map_action(cls, input_action):
302
+ output_action = type(input_action)()
303
+ output_action = {
304
+ "hand.left_hand": input_action["robot0_left_gripper"],
305
+ "hand.right_hand": input_action["robot0_right_gripper"],
306
+ "body.left_arm": input_action["robot0_left"],
307
+ "body.right_arm": input_action["robot0_right"],
308
+ "body.waist": input_action["robot0_torso"],
309
+ }
310
+ return output_action
311
+
312
+ @classmethod
313
+ def unmap_action(cls, input_action):
314
+ output_action = type(input_action)()
315
+ output_action = {
316
+ "robot0_left_gripper": input_action["action.left_hand"],
317
+ "robot0_right_gripper": input_action["action.right_hand"],
318
+ "robot0_left": input_action["action.left_arm"],
319
+ "robot0_right": input_action["action.right_arm"],
320
+ "robot0_torso": input_action["action.waist"],
321
+ }
322
+ return output_action
323
+
324
+ @classmethod
325
+ def get_missing_keys_in_dumping_dataset(cls):
326
+ return {
327
+ "body.neck": np.zeros(3, dtype=np.float64),
328
+ "body.right_leg": np.zeros(6, dtype=np.float64),
329
+ "body.left_leg": np.zeros(6, dtype=np.float64),
330
+ }
331
+
332
+ @classmethod
333
+ def get_metadata(cls, name):
334
+ return {
335
+ "absolute": True,
336
+ "rotation_type": None,
337
+ }
338
+
339
+
340
+ class GR1FixedLowerBodyKeyConverter(RobotKeyConverter):
341
+ @classmethod
342
+ def get_camera_config(cls):
343
+ mapped_names = ["video.agentview_pad_res256_freq20"]
344
+ camera_names = [
345
+ "agentview",
346
+ ]
347
+ camera_widths, camera_heights = 1280, 800
348
+ return mapped_names, camera_names, camera_widths, camera_heights
349
+
350
+ @classmethod
351
+ def map_obs(cls, input_obs):
352
+ output_obs = type(input_obs)()
353
+ output_obs = {
354
+ "hand.right_hand": input_obs["robot0_right_gripper"],
355
+ "hand.left_hand": input_obs["robot0_left_gripper"],
356
+ "body.right_arm": input_obs["robot0_right"],
357
+ "body.left_arm": input_obs["robot0_left"],
358
+ "body.waist": input_obs["robot0_torso"],
359
+ "body.neck": input_obs["robot0_head"],
360
+ }
361
+ return output_obs
362
+
363
+ @classmethod
364
+ def map_action(cls, input_action):
365
+ output_action = type(input_action)()
366
+ output_action = {
367
+ "hand.left_hand": input_action["robot0_left_gripper"],
368
+ "hand.right_hand": input_action["robot0_right_gripper"],
369
+ "body.left_arm": input_action["robot0_left"],
370
+ "body.right_arm": input_action["robot0_right"],
371
+ "body.waist": input_action["robot0_torso"],
372
+ "body.neck": input_action["robot0_head"],
373
+ }
374
+ return output_action
375
+
376
+ @classmethod
377
+ def unmap_action(cls, input_action):
378
+ output_action = type(input_action)()
379
+ output_action = {
380
+ "robot0_left_gripper": input_action["action.left_hand"],
381
+ "robot0_right_gripper": input_action["action.right_hand"],
382
+ "robot0_left": input_action["action.left_arm"],
383
+ "robot0_right": input_action["action.right_arm"],
384
+ "robot0_torso": input_action["action.waist"],
385
+ "robot0_head": input_action["action.neck"],
386
+ }
387
+ return output_action
388
+
389
+ @classmethod
390
+ def get_missing_keys_in_dumping_dataset(cls):
391
+ return {
392
+ "body.right_leg": np.zeros(6, dtype=np.float64),
393
+ "body.left_leg": np.zeros(6, dtype=np.float64),
394
+ }
395
+
396
+ @classmethod
397
+ def get_metadata(cls, name):
398
+ return {
399
+ "absolute": True,
400
+ "rotation_type": None,
401
+ }
402
+
403
+
404
+ class PandaOmronKeyConverter(RobotKeyConverter):
405
+ @classmethod
406
+ def get_camera_config(cls):
407
+ mapped_names = [
408
+ "video.res256_image_side_0",
409
+ "video.res256_image_side_1",
410
+ "video.res256_image_wrist_0",
411
+ ]
412
+ camera_names = [
413
+ "robot0_agentview_left",
414
+ "robot0_agentview_right",
415
+ "robot0_eye_in_hand",
416
+ ]
417
+ camera_widths, camera_heights = 512, 512
418
+ return mapped_names, camera_names, camera_widths, camera_heights
419
+
420
+ @classmethod
421
+ def map_obs(cls, input_obs):
422
+ output_obs = type(input_obs)()
423
+ output_obs = {
424
+ "hand.gripper_qpos": input_obs["robot0_gripper_qpos"],
425
+ "body.base_position": input_obs["robot0_base_pos"],
426
+ "body.base_rotation": input_obs["robot0_base_quat"],
427
+ "body.end_effector_position_relative": input_obs["robot0_base_to_eef_pos"],
428
+ "body.end_effector_rotation_relative": input_obs["robot0_base_to_eef_quat"],
429
+ }
430
+ return output_obs
431
+
432
+ @classmethod
433
+ def map_action(cls, input_action):
434
+ output_action = type(input_action)()
435
+ output_action = {
436
+ "hand.gripper_close": (
437
+ np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1)
438
+ ),
439
+ "body.end_effector_position": input_action["robot0_right"][..., 0:3],
440
+ "body.end_effector_rotation": input_action["robot0_right"][..., 3:6],
441
+ "body.base_motion": np.concatenate(
442
+ (
443
+ input_action["robot0_base"],
444
+ input_action["robot0_torso"],
445
+ ),
446
+ axis=-1,
447
+ ),
448
+ "body.control_mode": (
449
+ np.int64(0) if input_action["robot0_base_mode"] < 0 else np.int64(1)
450
+ ),
451
+ }
452
+ return output_action
453
+
454
+ @classmethod
455
+ def unmap_action(cls, input_action):
456
+ output_action = type(input_action)()
457
+ output_action = {
458
+ "robot0_right_gripper": (
459
+ -1.0 if input_action["action.gripper_close"] < 0.5 else 1.0
460
+ ),
461
+ "robot0_right": np.concatenate(
462
+ (
463
+ input_action["action.end_effector_position"],
464
+ input_action["action.end_effector_rotation"],
465
+ ),
466
+ axis=-1,
467
+ ),
468
+ "robot0_base": input_action["action.base_motion"][..., 0:3],
469
+ "robot0_torso": input_action["action.base_motion"][..., 3:4],
470
+ "robot0_base_mode": (
471
+ -1.0 if input_action["action.control_mode"] < 0.5 else 1.0
472
+ ),
473
+ }
474
+ return output_action
475
+
476
+ @classmethod
477
+ def get_metadata(cls, name):
478
+ from gr00t.data.schema import RotationType
479
+
480
+ if name in [
481
+ "body.base_position",
482
+ "body.end_effector_position_relative",
483
+ "body.end_effector_position",
484
+ ]:
485
+ return {
486
+ "absolute": False,
487
+ "rotation_type": None,
488
+ }
489
+ elif name in ["body.base_rotation", "body.end_effector_rotation_relative"]:
490
+ return {
491
+ "absolute": False,
492
+ "rotation_type": RotationType.QUATERNION,
493
+ }
494
+ elif name in ["body.end_effector_rotation"]:
495
+ return {
496
+ "absolute": False,
497
+ "rotation_type": RotationType.AXIS_ANGLE,
498
+ }
499
+ else:
500
+ return {
501
+ "absolute": True,
502
+ "rotation_type": None,
503
+ }
504
+
505
+
506
+ class PandaPandaKeyConverter(RobotKeyConverter):
507
+ @classmethod
508
+ def get_camera_config(cls):
509
+ mapped_names = [
510
+ "video.agentview_pad_res256_freq20",
511
+ "video.robot0_eye_in_hand_pad_res256_freq20",
512
+ "video.robot1_eye_in_hand_pad_res256_freq20",
513
+ ]
514
+ camera_names = [
515
+ "agentview",
516
+ "robot0_eye_in_hand",
517
+ "robot1_eye_in_hand",
518
+ ]
519
+ camera_widths, camera_heights = 1280, 800
520
+ return mapped_names, camera_names, camera_widths, camera_heights
521
+
522
+ @classmethod
523
+ def map_obs(cls, input_obs):
524
+ output_obs = type(input_obs)()
525
+ output_obs = {
526
+ "hand.right_gripper_qpos": input_obs["robot0_right_gripper"],
527
+ "hand.left_gripper_qpos": input_obs["robot1_right_gripper"],
528
+ "body.right_arm_eef_pos": input_obs["robot0_eef_pos"],
529
+ "body.right_arm_eef_quat": input_obs["robot0_eef_quat"],
530
+ "body.right_arm_joint_pos": input_obs["robot0_joint_pos"],
531
+ "body.left_arm_eef_pos": input_obs["robot1_eef_pos"],
532
+ "body.left_arm_eef_quat": input_obs["robot1_eef_quat"],
533
+ "body.left_arm_joint_pos": input_obs["robot1_joint_pos"],
534
+ }
535
+ return output_obs
536
+
537
+ @classmethod
538
+ def map_action(cls, input_action):
539
+ output_action = type(input_action)()
540
+ output_action = {
541
+ "hand.right_gripper_close": (
542
+ np.int64(0) if input_action["robot0_right_gripper"] < 0 else np.int64(1)
543
+ ),
544
+ "hand.left_gripper_close": (
545
+ np.int64(0) if input_action["robot1_right_gripper"] < 0 else np.int64(1)
546
+ ),
547
+ "body.right_arm_eef_pos": input_action["robot0_right"][..., 0:3],
548
+ "body.right_arm_eef_rot": input_action["robot0_right"][..., 3:6],
549
+ "body.left_arm_eef_pos": input_action["robot1_right"][..., 0:3],
550
+ "body.left_arm_eef_rot": input_action["robot1_right"][..., 3:6],
551
+ }
552
+ return output_action
553
+
554
+ @classmethod
555
+ def unmap_action(cls, input_action):
556
+ output_action = type(input_action)()
557
+ output_action = {
558
+ "robot0_right_gripper": (
559
+ -1.0 if input_action["action.right_gripper_close"] < 0.5 else 1.0
560
+ ),
561
+ "robot1_right_gripper": (
562
+ -1.0 if input_action["action.left_gripper_close"] < 0.5 else 1.0
563
+ ),
564
+ "robot0_right": np.concatenate(
565
+ (
566
+ input_action["action.right_arm_eef_pos"],
567
+ input_action["action.right_arm_eef_rot"],
568
+ ),
569
+ axis=-1,
570
+ ),
571
+ "robot1_right": np.concatenate(
572
+ (
573
+ input_action["action.left_arm_eef_pos"],
574
+ input_action["action.left_arm_eef_rot"],
575
+ ),
576
+ axis=-1,
577
+ ),
578
+ }
579
+ return output_action
580
+
581
+ @classmethod
582
+ def get_metadata(cls, name):
583
+ from gr00t.data.schema import RotationType
584
+
585
+ if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]:
586
+ return {
587
+ "absolute": False,
588
+ "rotation_type": None,
589
+ }
590
+ elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]:
591
+ return {
592
+ "absolute": False,
593
+ "rotation_type": RotationType.QUATERNION,
594
+ }
595
+ elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]:
596
+ return {
597
+ "absolute": False,
598
+ "rotation_type": RotationType.AXIS_ANGLE,
599
+ }
600
+ else:
601
+ return {
602
+ "absolute": True,
603
+ "rotation_type": None,
604
+ }
605
+
606
+
607
+ class PandaDexRHPandaDexRHKeyConverter(RobotKeyConverter):
608
+ @classmethod
609
+ def get_camera_config(cls):
610
+ mapped_names = [
611
+ "video.agentview_pad_res256_freq20",
612
+ "video.robot0_eye_in_hand_pad_res256_freq20",
613
+ "video.robot1_eye_in_hand_pad_res256_freq20",
614
+ ]
615
+ camera_names = [
616
+ "agentview",
617
+ "robot0_eye_in_hand",
618
+ "robot1_eye_in_hand",
619
+ ]
620
+ camera_widths, camera_heights = 1280, 800
621
+ return mapped_names, camera_names, camera_widths, camera_heights
622
+
623
+ @classmethod
624
+ def map_obs(cls, input_obs):
625
+ output_obs = type(input_obs)()
626
+ output_obs = {
627
+ "hand.right_hand": input_obs["robot0_right_gripper"],
628
+ "hand.left_hand": input_obs["robot1_right_gripper"],
629
+ "body.right_arm_eef_pos": input_obs["robot0_eef_pos"],
630
+ "body.right_arm_eef_quat": input_obs["robot0_eef_quat"],
631
+ "body.right_arm_joint_pos": input_obs["robot0_joint_pos"],
632
+ "body.left_arm_eef_pos": input_obs["robot1_eef_pos"],
633
+ "body.left_arm_eef_quat": input_obs["robot1_eef_quat"],
634
+ "body.left_arm_joint_pos": input_obs["robot1_joint_pos"],
635
+ }
636
+ return output_obs
637
+
638
+ @classmethod
639
+ def map_action(cls, input_action):
640
+ output_action = type(input_action)()
641
+ output_action = {
642
+ "hand.right_hand": input_action["robot0_right_gripper"],
643
+ "hand.left_hand": input_action["robot1_right_gripper"],
644
+ "body.right_arm_eef_pos": input_action["robot0_right"][0:3],
645
+ "body.right_arm_eef_rot": input_action["robot0_right"][3:6],
646
+ "body.left_arm_eef_pos": input_action["robot1_right"][0:3],
647
+ "body.left_arm_eef_rot": input_action["robot1_right"][3:6],
648
+ }
649
+ return output_action
650
+
651
+ @classmethod
652
+ def unmap_action(cls, input_action):
653
+ output_action = type(input_action)()
654
+ output_action = {
655
+ "robot0_right_gripper": input_action["action.right_hand"],
656
+ "robot1_right_gripper": input_action["action.left_hand"],
657
+ "robot0_right": np.concatenate(
658
+ (
659
+ input_action["action.right_arm_eef_pos"],
660
+ input_action["action.right_arm_eef_rot"],
661
+ ),
662
+ axis=-1,
663
+ ),
664
+ "robot1_right": np.concatenate(
665
+ (
666
+ input_action["action.left_arm_eef_pos"],
667
+ input_action["action.left_arm_eef_rot"],
668
+ ),
669
+ axis=-1,
670
+ ),
671
+ }
672
+ return output_action
673
+
674
+ @classmethod
675
+ def get_metadata(cls, name):
676
+ from gr00t.data.schema import RotationType
677
+
678
+ if name in ["body.right_arm_eef_pos", "body.left_arm_eef_pos"]:
679
+ return {
680
+ "absolute": False,
681
+ "rotation_type": None,
682
+ }
683
+ elif name in ["body.right_arm_eef_quat", "body.right_arm_eef_quat"]:
684
+ return {
685
+ "absolute": False,
686
+ "rotation_type": RotationType.QUATERNION,
687
+ }
688
+ elif name in ["body.right_arm_eef_rot", "body.left_arm_eef_rot"]:
689
+ return {
690
+ "absolute": False,
691
+ "rotation_type": RotationType.AXIS_ANGLE,
692
+ }
693
+ else:
694
+ return {
695
+ "absolute": True,
696
+ "rotation_type": None,
697
+ }
698
+
699
+
700
+ # The values are only used in groot dataset embodiment tag and env name
701
+ GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY = {
702
+ "GR1ArmsOnly": "gr1_arms_only_fourier_hands",
703
+ "GR1ArmsOnlyInspireHands": "gr1_arms_only_inspire_hands",
704
+ "GR1ArmsOnlyFourierHands": "gr1_arms_only_fourier_hands",
705
+ }
706
+ GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST = {
707
+ "GR1ArmsAndWaistFourierHands": "gr1_arms_waist_fourier_hands",
708
+ }
709
+ GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY = {
710
+ "GR1FixedLowerBody": "gr1_fixed_lower_body_fourier_hands",
711
+ "GR1FixedLowerBodyInspireHands": "gr1_fixed_lower_body_inspire_hands",
712
+ "GR1FixedLowerBodyFourierHands": "gr1_fixed_lower_body_fourier_hands",
713
+ }
714
+ GROOT_ROBOCASA_ENVS_PANDA = {
715
+ "PandaMobile": "panda_mobile",
716
+ "PandaOmron": "panda_omron",
717
+ }
718
+ GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER = {
719
+ "Panda_Panda": "bimanual_panda_parallel_gripper",
720
+ }
721
+ GROOT_ROBOCASA_ENVS_BIMANUAL_HAND = {
722
+ "PandaDexRH_PandaDexLH": "bimanual_panda_inspire_hand",
723
+ }
724
+ GROOT_ROBOCASA_ENVS_ROBOTS = {
725
+ **GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY,
726
+ **GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST,
727
+ **GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY,
728
+ **GROOT_ROBOCASA_ENVS_PANDA,
729
+ **GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER,
730
+ **GROOT_ROBOCASA_ENVS_BIMANUAL_HAND,
731
+ }
732
+
733
+
734
+ def make_key_converter(robots_name):
735
+ if robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY:
736
+ return GR1ArmsOnlyKeyConverter
737
+ elif robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST:
738
+ return GR1ArmsAndWaistKeyConverter
739
+ elif robots_name in GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY:
740
+ return GR1FixedLowerBodyKeyConverter
741
+ elif robots_name in GROOT_ROBOCASA_ENVS_PANDA:
742
+ return PandaOmronKeyConverter
743
+ elif robots_name in GROOT_ROBOCASA_ENVS_BIMANUAL_GRIPPER:
744
+ return PandaPandaKeyConverter
745
+ elif robots_name in GROOT_ROBOCASA_ENVS_BIMANUAL_HAND:
746
+ return PandaDexRHPandaDexRHKeyConverter
747
+ else:
748
+ raise ValueError(f"Unknown robot name: {robots_name}")
third_party/robocasa/robocasa/models/robots/manipulators/README.md ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Robot Integration Guide
2
+
3
+ This guide explains how to integrate a new robot into the Robocasa framework.
4
+
5
+ ## MJCF File Requirements
6
+ Location: [`robocasa/models/assets/robots/`](robocasa/models/robots)
7
+
8
+ ### MJCF Structure Requirements
9
+ - The MJCF file must have a single root element containing all other elements (`<worldbody>`, `<asset>`, etc.)
10
+ - The robot's kinematic tree must start from a `<body name="base">` element that contains a freejoint and is placed directly under `<worldbody>`
11
+ - Joint definitions for the right arm must precede those of the left arm in the XML structure
12
+ - End effector attachments (grippers) are only supported on bodies named `<body name="right_eef">`
13
+
14
+ ### Base Mounting Configuration
15
+ When operating in fixed-base mode, the body connected to the base joint will be anchored to the world frame. So choose this mounting point carefully, typically at the robot's pelvis/torso, to ensure proper fixed-base behavior.
16
+
17
+ ## Controller Configuration
18
+ Location: [`robocasa/examples/third_party_controllers/`](robocasa/examples/third_party_controllers/)
19
+
20
+
21
+ ### Configuration Requirements
22
+ 1. Implement whole-body control configuration (excluding leg components for now)
23
+ 2. Configure and tune `ik_posture_weight`
24
+ - Remember to add "robot0_" prefix to all parameters
25
+
26
+
27
+ ## Robot Registry Updates
28
+ Location: [`robocasa/models/robots/manipulators/`](robocasa/models/robots/manipulators/)
29
+
30
+ ### Required Function Updates
31
+ Take a look at the existing robot class definitions for examples.
32
+ Remember to update the following functions with new robot's specifications:
33
+ 1. `update_joints()`
34
+ - Add joint names in correct order
35
+ - Maintain right-before-left convention
36
+
37
+ 2. `update_actuators()`
38
+ - Add actuator names
39
+ - Ensure order matches joint configuration
40
+
third_party/robocasa/robocasa/models/robots/manipulators/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ from .gr1_robot import (
2
+ GR1FixedLowerBodyInspireHands,
3
+ GR1FixedLowerBodyFourierHands,
4
+ GR1ArmsOnlyInspireHands,
5
+ GR1ArmsOnlyFourierHands,
6
+ GR1ArmsAndWaistFourierHands,
7
+ )
third_party/robocasa/robocasa/models/robots/manipulators/gr1_robot.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from robosuite.robots import register_robot_class
4
+ from robosuite.models.robots import GR1
5
+ from robosuite.models.robots.manipulators.gr1_robot import (
6
+ GR1FixedLowerBody,
7
+ GR1ArmsOnly,
8
+ )
9
+
10
+
11
+ @register_robot_class("LeggedRobot")
12
+ class GR1FixedLowerBodyInspireHands(GR1FixedLowerBody):
13
+ @property
14
+ def default_gripper(self):
15
+ return {"right": "InspireRightHand", "left": "InspireLeftHand"}
16
+
17
+
18
+ @register_robot_class("LeggedRobot")
19
+ class GR1FixedLowerBodyFourierHands(GR1FixedLowerBody):
20
+ @property
21
+ def default_gripper(self):
22
+ return {"right": "FourierRightHand", "left": "FourierLeftHand"}
23
+
24
+
25
+ @register_robot_class("LeggedRobot")
26
+ class GR1ArmsOnlyInspireHands(GR1ArmsOnly):
27
+ @property
28
+ def default_gripper(self):
29
+ return {"right": "InspireRightHand", "left": "InspireLeftHand"}
30
+
31
+
32
+ @register_robot_class("LeggedRobot")
33
+ class GR1ArmsOnlyFourierHands(GR1ArmsOnly):
34
+ @property
35
+ def default_gripper(self):
36
+ return {"right": "FourierRightHand", "left": "FourierLeftHand"}
37
+
38
+
39
+ @register_robot_class("LeggedRobot")
40
+ class GR1ArmsAndWaist(GR1):
41
+ def __init__(self, idn=0):
42
+ super().__init__(idn=idn)
43
+ self._remove_joint_actuation("leg")
44
+ self._remove_joint_actuation("head")
45
+ self._remove_free_joint()
46
+
47
+ @property
48
+ def init_qpos(self):
49
+ init_qpos = np.array([0.0] * 17)
50
+ right_arm_init = np.array([0.0, -0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
51
+ left_arm_init = np.array([0.0, 0.1, 0.0, -1.57, 0.0, 0.0, 0.0])
52
+ init_qpos[3:10] = right_arm_init
53
+ init_qpos[10:17] = left_arm_init
54
+ return init_qpos
55
+
56
+
57
+ @register_robot_class("LeggedRobot")
58
+ class GR1ArmsAndWaistFourierHands(GR1ArmsAndWaist):
59
+ pass
third_party/robocasa/robocasa/models/scenes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .tabletop_arena import TabletopArena
third_party/robocasa/robocasa/models/scenes/scene_builder.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import yaml
3
+ from robosuite.utils.mjcf_utils import array_to_string as a2s
4
+ from robosuite.utils.mjcf_utils import string_to_array as s2a
5
+
6
+ from robocasa.models.scenes.scene_registry import (
7
+ get_tabletop_layout_path,
8
+ get_style_path,
9
+ )
10
+ from robocasa.models.scenes.scene_utils import *
11
+ from robocasa.models.fixtures import *
12
+
13
+ # fixture string to class
14
+ FIXTURES = dict(
15
+ single_cabinet=SingleCabinet,
16
+ drawer=Drawer,
17
+ counter=Counter,
18
+ microwave=Microwave,
19
+ wall=Wall,
20
+ floor=Floor,
21
+ paper_towel=Accessory,
22
+ plant=Accessory,
23
+ toaster=Toaster,
24
+ # needs some additional work
25
+ # slide_cabinet=SlideCabinet,
26
+ )
27
+ # fixtures that are attached to other fixtures, disables positioning system in this script
28
+ FIXTURES_INTERIOR = dict(
29
+ )
30
+
31
+ ALL_SIDES = ["left", "right", "front", "back", "bottom", "top"]
32
+
33
+
34
+ def check_syntax(fixture):
35
+ """
36
+ Checks that specifications of a fixture follows syntax rules
37
+ """
38
+
39
+ if fixture["type"] != "stack" and fixture["type"] not in FIXTURES:
40
+ raise ValueError(
41
+ 'Invalid value for fixture type: "{}".'.format(fixture["type"])
42
+ )
43
+
44
+ if "config_name" in fixture and "default_config_name" in fixture:
45
+ raise ValueError('Cannot specify both "config_name" and "default_config_name"')
46
+
47
+ if "align_to" in fixture or "side" in fixture or "alignment" in fixture:
48
+ if not ("align_to" in fixture and "side" in fixture):
49
+ raise ValueError(
50
+ 'Both or neither of "align_to" and ' '"side" need to be specified.'
51
+ )
52
+ if "pos" in fixture:
53
+ raise ValueError("Cannot specify both relative and absolute positions.")
54
+
55
+ # check alignment and side arguments are compatible
56
+ if "alignment" in fixture:
57
+ for keywords in AXES_KEYWORDS.values():
58
+ if fixture["side"] in keywords:
59
+ # check that neither keyword is used for alignment
60
+ if (
61
+ keywords[0] in fixture["alignment"]
62
+ or keywords[1] in fixture["alignment"]
63
+ ):
64
+ raise ValueError(
65
+ 'Cannot set alignment to "{}" when aligning to the "{}" side'.format(
66
+ fixture["alignment"], fixture["side"]
67
+ )
68
+ )
69
+
70
+ # check if side is valid
71
+ if fixture["side"] not in ALL_SIDES:
72
+ raise ValueError(
73
+ '"{}" is not a valid side for alignment'.format(fixture["side"])
74
+ )
75
+
76
+
77
+ def create_tabletop_fixtures(layout_id, style_id, rng=None):
78
+ """
79
+ Initializes fixtures based on the given layout yaml file and style type
80
+
81
+ Args:
82
+ layout_id (int or TabletopLayoutType): layout of the tabletop to load
83
+
84
+ style_id (int or StyleType): style of the tabletop to load
85
+
86
+ rng (np.random.Generator): random number generator used for initializing fixture state
87
+ """
88
+
89
+ try:
90
+ style = int(style)
91
+ except:
92
+ pass
93
+
94
+ return create_fixtures_from_yaml(
95
+ get_tabletop_layout_path(layout_id), get_style_path(style_id), rng
96
+ )
97
+
98
+
99
+ def create_fixtures_from_yaml(layout_yaml_path, style_yaml_path, rng=None):
100
+ """
101
+ Initializes fixtures based on the given layout yaml file and style type
102
+
103
+ Args:
104
+ layout_yaml_path (str): path to the layout yaml file
105
+
106
+ style_yaml_path (str): path to the style yaml file
107
+
108
+ rng (np.random.Generator): random number generator used for initializing fixture state
109
+ """
110
+
111
+ # load style
112
+ with open(style_yaml_path, "r") as f:
113
+ style = yaml.safe_load(f)
114
+
115
+ # load arena
116
+ with open(layout_yaml_path, "r") as f:
117
+ arena_config = yaml.safe_load(f)
118
+
119
+ # contains all fixtures with updated configs
120
+ arena = list()
121
+
122
+ # Update each fixture config. First iterate through groups: subparts of the arena that can be
123
+ # rotated and displaced together. example: island group, right group, room group, etc
124
+ for group_name, group_config in arena_config.items():
125
+ group_fixtures = list()
126
+ # each group is further divded into similar subcollections of fixtures
127
+ # ex: main group counter accessories, main group top cabinets, etc
128
+ for k, fixture_list in group_config.items():
129
+ # these values are rotations/displacements that are applied to all fixtures in the group
130
+ if k in ["group_origin", "group_z_rot", "group_pos"]:
131
+ continue
132
+ elif type(fixture_list) != list:
133
+ raise ValueError('"{}" is not a valid argument for groups'.format(k))
134
+
135
+ # add suffix to support different groups
136
+ for fxtr_config in fixture_list:
137
+ fxtr_config["name"] += "_" + group_name
138
+ # update fixture names for alignment, interior objects, etc.
139
+ for k in ATTACH_ARGS + ["align_to", "stack_fixtures", "size"]:
140
+ if k in fxtr_config:
141
+ if isinstance(fxtr_config[k], list):
142
+ for i in range(len(fxtr_config[k])):
143
+ if isinstance(fxtr_config[k][i], str):
144
+ fxtr_config[k][i] += "_" + group_name
145
+ else:
146
+ if isinstance(fxtr_config[k], str):
147
+ fxtr_config[k] += "_" + group_name
148
+
149
+ group_fixtures.extend(fixture_list)
150
+
151
+ # update group rotation/displacement if necessary
152
+ if "group_origin" in group_config:
153
+ for fxtr_config in group_fixtures:
154
+ # do not update the rotation of the walls/floor
155
+ if fxtr_config["type"] in ["wall", "floor"]:
156
+ continue
157
+ fxtr_config["group_origin"] = group_config["group_origin"]
158
+ fxtr_config["group_pos"] = group_config["group_pos"]
159
+ fxtr_config["group_z_rot"] = group_config["group_z_rot"]
160
+
161
+ # addto overall fixture list
162
+ arena.extend(group_fixtures)
163
+
164
+ # maps each fixture name to its object class
165
+ fixtures = dict()
166
+ # maps each fixture name to its configuration
167
+ configs = dict()
168
+ # names of composites, delete from fixtures before returning
169
+ composites = list()
170
+
171
+ # initialize each fixture in the arena by processing config
172
+ for fixture_config in arena:
173
+ check_syntax(fixture_config)
174
+ fixture_name = fixture_config["name"]
175
+
176
+ # stack of fixtures, handled separately
177
+ if fixture_config["type"] == "stack":
178
+ stack = FixtureStack(
179
+ fixture_config,
180
+ fixtures,
181
+ configs,
182
+ style,
183
+ default_texture=None,
184
+ rng=rng,
185
+ )
186
+ fixtures[fixture_name] = stack
187
+ configs[fixture_name] = fixture_config
188
+ composites.append(fixture_name)
189
+ continue
190
+
191
+ # load style information and update config to include it
192
+ default_config = load_style_config(style, fixture_config)
193
+ if default_config is not None:
194
+ for k, v in fixture_config.items():
195
+ default_config[k] = v
196
+ fixture_config = default_config
197
+
198
+ # set fixture type
199
+ fixture_config["type"] = FIXTURES[fixture_config["type"]]
200
+
201
+ # pre-processing for fixture size
202
+ size = fixture_config.get("size", None)
203
+ if isinstance(size, list):
204
+ for i in range(len(size)):
205
+ elem = size[i]
206
+ if isinstance(elem, str):
207
+ ref_fxtr = fixtures[elem]
208
+ size[i] = ref_fxtr.size[i]
209
+
210
+ # initialize fixture
211
+ fixture = initialize_fixture(fixture_config, fixtures, rng=rng)
212
+ fixtures[fixture_name] = fixture
213
+ configs[fixture_name] = fixture_config
214
+
215
+ # update fixture position
216
+ if fixture_config["type"] not in FIXTURES_INTERIOR.values():
217
+ # relative positioning
218
+ if "align_to" in fixture_config:
219
+ pos = get_relative_position(
220
+ fixture,
221
+ fixture_config,
222
+ fixtures[fixture_config["align_to"]],
223
+ configs[fixture_config["align_to"]],
224
+ )
225
+
226
+ elif "stack_on" in fixture_config:
227
+ stack_on = fixtures[fixture_config["stack_on"]]
228
+
229
+ # account for off-centered objects
230
+ stack_on_center = stack_on.center
231
+
232
+ # infer unspecified axes of position
233
+ pos = fixture_config["pos"]
234
+ if pos[0] is None:
235
+ pos[0] = stack_on.pos[0] + stack_on_center[0]
236
+ if pos[1] is None:
237
+ pos[1] = stack_on.pos[1] + stack_on_center[1]
238
+
239
+ # calculate height of fixture
240
+ pos[2] = stack_on.pos[2] + stack_on.size[2] / 2 + fixture.size[2] / 2
241
+ pos[2] += stack_on_center[2]
242
+ else:
243
+ # absolute position
244
+ pos = fixture_config.get("pos", None)
245
+ if pos is not None and type(fixture) not in [Wall, Floor]:
246
+ fixture.set_pos(pos)
247
+
248
+ # composites are non-MujocoObjects, must remove
249
+ for composite in composites:
250
+ del fixtures[composite]
251
+
252
+ # update the rotation and postion of each fixture based on their group
253
+ for name, fixture in fixtures.items():
254
+ # check if updates are necessary
255
+ config = configs[name]
256
+ if "group_origin" not in config:
257
+ continue
258
+
259
+ # TODO: add default for group origin?
260
+ # rotate about this coordinate (around the z-axis)
261
+ origin = config["group_origin"]
262
+ pos = config["group_pos"]
263
+ z_rot = config["group_z_rot"]
264
+ displacement = [pos[0] - origin[0], pos[1] - origin[1]]
265
+
266
+ if type(fixture) not in [Wall, Floor]:
267
+ dx = fixture.pos[0] - origin[0]
268
+ dy = fixture.pos[1] - origin[1]
269
+ dx_rot = dx * np.cos(z_rot) - dy * np.sin(z_rot)
270
+ dy_rot = dx * np.sin(z_rot) + dy * np.cos(z_rot)
271
+
272
+ x_rot = origin[0] + dx_rot
273
+ y_rot = origin[1] + dy_rot
274
+ z = fixture.pos[2]
275
+ pos_new = [x_rot + displacement[0], y_rot + displacement[1], z]
276
+
277
+ # account for previous z-axis rotation
278
+ rot_prev = fixture._obj.get("euler")
279
+ if rot_prev is not None:
280
+ # TODO: switch to quaternion since euler rotations are ambiguous
281
+ rot_new = s2a(rot_prev)
282
+ rot_new[2] += z_rot
283
+ else:
284
+ rot_new = [0, 0, z_rot]
285
+
286
+ fixture._obj.set("pos", a2s(pos_new))
287
+ fixture._obj.set("euler", a2s(rot_new))
288
+
289
+ return fixtures
third_party/robocasa/robocasa/models/scenes/scene_registry.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from enum import IntEnum
3
+ from robosuite.utils.mjcf_utils import xml_path_completion
4
+ import robocasa
5
+
6
+
7
+ class TabletopLayoutType(IntEnum):
8
+ """
9
+ Enum for available tabletop layouts in RoboCasa environment
10
+ """
11
+
12
+ TABLETOP = 0
13
+ CLUTTERED_TABLETOP = 1
14
+ TABLETOP_WITH_MICROWAVE = 2
15
+ TABLETOP_COTRAIN = 3
16
+ TABLETOP_WITH_DRAWER = 4
17
+ TABLETOP_WITH_CABINET = 5
18
+
19
+ # negative values correspond to groups (see TABLETOP_LAYOUT_GROUPS_TO_IDS)
20
+ ALL = -1
21
+
22
+
23
+ TABLETOP_LAYOUT_GROUPS_TO_IDS = {
24
+ -1: list(range(len(TabletopLayoutType) - 1)), # all
25
+ }
26
+
27
+
28
+ class StyleType(IntEnum):
29
+ """
30
+ Enums for available styles in RoboCasa environment
31
+ """
32
+
33
+ INDUSTRIAL = 0
34
+ SCANDANAVIAN = 1
35
+ COASTAL = 2
36
+ MODERN_1 = 3
37
+ MODERN_2 = 4
38
+ TRADITIONAL_1 = 5
39
+ TRADITIONAL_2 = 6
40
+ FARMHOUSE = 7
41
+ RUSTIC = 8
42
+ MEDITERRANEAN = 9
43
+ TRANSITIONAL_1 = 10
44
+ TRANSITIONAL_2 = 11
45
+
46
+ # negative values correspond to groups
47
+ ALL = -1
48
+
49
+
50
+ STYLE_GROUPS_TO_IDS = {
51
+ -1: list(range(12)), # all
52
+ }
53
+
54
+
55
+ def get_tabletop_layout_path(layout_id):
56
+ """
57
+ Get corresponding blueprint filepath (yaml) for a layout
58
+
59
+ Args:
60
+ layout_id (int or TabletopLayoutType): layout id (int or enum)
61
+
62
+ Return:
63
+ str: yaml path for specified layout
64
+ """
65
+ if isinstance(layout_id, int):
66
+ layout_int_to_name = dict(
67
+ map(lambda item: (item.value, item.name.lower()), TabletopLayoutType)
68
+ )
69
+ layout_name = layout_int_to_name[layout_id]
70
+ elif isinstance(layout_id, TabletopLayoutType):
71
+ layout_name = layout_id.name.lower()
72
+ else:
73
+ raise ValueError
74
+
75
+ # special case: if name starts with one letter, capitalize it
76
+ if layout_name[1] == "_":
77
+ layout_name = layout_name.capitalize()
78
+
79
+ return xml_path_completion(
80
+ f"scenes/tabletop_layouts/{layout_name}.yaml",
81
+ root=robocasa.models.assets_root,
82
+ )
83
+
84
+
85
+ def get_style_path(style_id):
86
+ """
87
+ Get corresponding blueprint filepath (yaml) for a style
88
+
89
+ Args:
90
+ style_id (int or StyleType): style id (int or enum)
91
+
92
+ Return:
93
+ str: yaml path for specified style
94
+ """
95
+ if isinstance(style_id, int):
96
+ style_int_to_name = dict(
97
+ map(lambda item: (item.value, item.name.lower()), StyleType)
98
+ )
99
+ style_name = style_int_to_name[style_id]
100
+ elif isinstance(style_id, StyleType):
101
+ style_name = style_id.name.lower()
102
+ else:
103
+ raise ValueError
104
+
105
+ return xml_path_completion(
106
+ f"scenes/kitchen_styles/{style_name}.yaml",
107
+ root=robocasa.models.assets_root,
108
+ )
109
+
110
+
111
+ def unpack_tabletop_layout_ids(layout_ids):
112
+ if layout_ids is None:
113
+ layout_ids = TabletopLayoutType.ALL
114
+
115
+ if not isinstance(layout_ids, list):
116
+ layout_ids = [layout_ids]
117
+
118
+ layout_ids = [int(id) for id in layout_ids]
119
+
120
+ all_layout_ids = []
121
+ for id in layout_ids:
122
+ if id < 0:
123
+ all_layout_ids += TABLETOP_LAYOUT_GROUPS_TO_IDS[id]
124
+ else:
125
+ all_layout_ids.append(id)
126
+ return list(OrderedDict.fromkeys(all_layout_ids))
127
+
128
+
129
+ def unpack_style_ids(style_ids):
130
+ if style_ids is None:
131
+ style_ids = StyleType.ALL
132
+
133
+ if not isinstance(style_ids, list):
134
+ style_ids = [style_ids]
135
+
136
+ style_ids = [int(id) for id in style_ids]
137
+
138
+ all_style_ids = []
139
+ for id in style_ids:
140
+ if id < 0:
141
+ all_style_ids += STYLE_GROUPS_TO_IDS[id]
142
+ else:
143
+ all_style_ids.append(id)
144
+ return list(OrderedDict.fromkeys(all_style_ids))
third_party/robocasa/robocasa/models/scenes/scene_utils.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+ from copy import deepcopy
3
+ import yaml
4
+ from robosuite.utils.mjcf_utils import xml_path_completion
5
+
6
+ import robocasa
7
+
8
+
9
+ # second keyword corresponds to positive end of axis
10
+ AXES_KEYWORDS = {0: ["left", "right"], 1: ["front", "back"], 2: ["bottom", "top"]}
11
+
12
+ # arguments not to be passed into fixture classes when initializing
13
+ IGNORE_ARGS = [
14
+ "name",
15
+ "align_to",
16
+ "side",
17
+ "alignment",
18
+ "type",
19
+ "center",
20
+ "offset",
21
+ "group_origin",
22
+ "group_pos",
23
+ "group_z_rot",
24
+ "stack_height",
25
+ "stack_fixtures",
26
+ ]
27
+
28
+ # arguments used to point to other fixtures
29
+ ATTACH_ARGS = ["interior_obj", "stack_on", "attach_to"]
30
+
31
+
32
+ def initialize_fixture(config, cur_fixtures, rng=None):
33
+ """
34
+ initializes a fixture object based on the given configuration
35
+ ignores positional arguments as it is changed later
36
+
37
+ Args:
38
+ config (dict): dictionary containing the fixture configuration.
39
+ Serves as the arguments to initialize the fixture
40
+
41
+ cur_fixtures (dict): dictionary containing the current fixtures
42
+ """
43
+
44
+ config = deepcopy(config)
45
+ name, class_type = config["name"], config["type"]
46
+
47
+ # set size if stack_height is specified:
48
+ if config.get("stack_height", None) is not None:
49
+ stack_height = config["stack_height"]
50
+ stack_fixtures = config["stack_fixtures"]
51
+ curr_height = 0
52
+ for fxtr in stack_fixtures:
53
+ curr_height += cur_fixtures[fxtr].size[2]
54
+ config["size"][2] = stack_height - curr_height
55
+
56
+ # these fields should not be passed in when initializing the fixture
57
+ for field in IGNORE_ARGS:
58
+ if field in config:
59
+ del config[field]
60
+
61
+ if "pos" not in config:
62
+ # need position to initialize fixture, adjusted later fo relative positioning
63
+ config["pos"] = [0.0, 0.0, 0.0]
64
+
65
+ # update fixture pointers
66
+ for k in ATTACH_ARGS:
67
+ if k in config:
68
+ config[k] = cur_fixtures[config[k]]
69
+
70
+ config["rng"] = rng
71
+ fixture = class_type(name=name, **config)
72
+ # print(class_type, name, type(fixture))
73
+ return fixture
74
+
75
+
76
+ def load_style_config(style, fixture_config):
77
+ """
78
+ Loads the style information for a given fixture. Style information can consist of
79
+ which xml to use if there are multiple instances of a fixture, which texture to apply,
80
+ which subcomponents to apply (panels/handles for a cab), etc.
81
+
82
+ Args:
83
+ style (dict): dictionary containing the style information for each fixture type
84
+
85
+ fixture_config (dict): dictionary containing the fixture configuration
86
+ """
87
+ # accounts for the different types of cabinets
88
+ fixture_type = fixture_config["type"]
89
+
90
+ # cabinets, shelves, drawers, and boxes use the same default configurations
91
+ if "cabinet" in fixture_type or "drawer" in fixture_type or "box" in fixture_type:
92
+ fixture_type = "cabinet"
93
+
94
+ # if fixture_type not in style:
95
+ # raise ValueError("Did not specify fixture type \"{}\" in chosen style".format(fixture_type))
96
+ fixture_style = style.get(fixture_type, "default")
97
+
98
+ yaml_path = xml_path_completion(
99
+ f"fixtures/fixture_registry/{fixture_type}.yaml",
100
+ root=robocasa.models.assets_root,
101
+ )
102
+ with open(yaml_path, "r") as f:
103
+ default_configs = yaml.safe_load(f)
104
+
105
+ # find which configuration to use
106
+ if type(fixture_style) == dict and "config_name" not in fixture_config:
107
+ if "default_config_name" in fixture_config:
108
+ config_ids = fixture_style.get(
109
+ fixture_config["default_config_name"], fixture_style["default"]
110
+ )
111
+ del fixture_config["default_config_name"]
112
+ else:
113
+ config_ids = fixture_style["default"]
114
+ elif "default_config_name" in fixture_config:
115
+ raise ValueError('Specified "default_config_name" but no default config found')
116
+
117
+ elif "config_name" in fixture_config:
118
+ config_ids = fixture_config["config_name"]
119
+ del fixture_config["config_name"]
120
+ else:
121
+ config_ids = fixture_style
122
+
123
+ # search for config by name
124
+ config = default_configs["default"]
125
+ if not isinstance(config_ids, list):
126
+ config_ids = [config_ids]
127
+ for cfg_id in config_ids:
128
+ if cfg_id in default_configs:
129
+ # add additional arguments based on default config
130
+ additional_config = default_configs[cfg_id]
131
+ for k, v in additional_config.items():
132
+ config[k] = v
133
+ else:
134
+ raise ValueError(
135
+ 'Did not find style that matches "{}" for '
136
+ 'fixture type "{}"'.format(cfg_id, fixture_type)
137
+ )
138
+ return config
139
+
140
+
141
+ def get_relative_position(fixture, config, prev_fxtr, prev_fxtr_config):
142
+ """
143
+ Calculates the position of `fixture` based on a specified side
144
+ and alignment relative to `prev_fixture`
145
+
146
+ This assumes that the fixtures are properly centered!
147
+ """
148
+
149
+ side = config["side"].lower()
150
+ alignment = config["alignment"].lower() if "alignment" in config else "center"
151
+ size = fixture.size
152
+ prev_pos, prev_size = prev_fxtr.pos, prev_fxtr.size
153
+
154
+ # for fixtures that are not perfectly centered (e.g. stoves)
155
+ prev_pos += prev_fxtr.origin_offset
156
+
157
+ # place fixtures next to each others
158
+ for axis, keywords in AXES_KEYWORDS.items():
159
+ if side not in keywords:
160
+ continue
161
+ pos = deepcopy(prev_pos)
162
+ if side == keywords[1]:
163
+ pos[axis] = prev_pos[axis] + prev_size[axis] / 2 + size[axis] / 2
164
+ elif side == keywords[0]:
165
+ pos[axis] = prev_pos[axis] - prev_size[axis] / 2 - size[axis] / 2
166
+
167
+ # align such that the specified faces are flush
168
+ # alignment - side compatibility is checked in check_syntax()
169
+ for axis, keywords in AXES_KEYWORDS.items():
170
+ if keywords[0] in alignment:
171
+ pos[axis] = prev_pos[axis] - prev_size[axis] / 2 + size[axis] / 2
172
+ elif keywords[1] in alignment:
173
+ pos[axis] = prev_pos[axis] + prev_size[axis] / 2 - size[axis] / 2
174
+
175
+ if "offset" in config:
176
+ pos += config["offset"]
177
+
178
+ # for fixtures that are not perfectly centered (e.g. stoves)
179
+ pos -= fixture.origin_offset
180
+ return pos
third_party/robocasa/robocasa/models/scenes/tabletop_arena.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from robosuite.models.arenas import Arena
2
+ from robosuite.utils.mjcf_utils import xml_path_completion
3
+
4
+ import robocasa
5
+ from robocasa.models.scenes.scene_builder import create_tabletop_fixtures
6
+
7
+
8
+ # base class for tabletop scenes
9
+ class TabletopArena(Arena):
10
+ """
11
+ Tabletop arena class holding all of the fixtures
12
+
13
+ Args:
14
+ layout_id (int or TabletopLayoutType): layout of the tabletop to load
15
+
16
+ style_id (int or StyleType): style of the tabletop to load
17
+
18
+ rng (np.random.Generator): random number generator used for initializing
19
+ fixture state in the TabletopArena
20
+ """
21
+
22
+ def __init__(self, layout_id, style_id, rng=None):
23
+ super().__init__(
24
+ xml_path_completion(
25
+ "arenas/empty_tabletop_arena.xml", root=robocasa.models.assets_root
26
+ )
27
+ )
28
+ self.fixtures = create_tabletop_fixtures(
29
+ layout_id=layout_id,
30
+ style_id=style_id,
31
+ rng=rng,
32
+ )
33
+
34
+ def get_fixture_cfgs(self):
35
+ """
36
+ Returns config data for all fixtures in the arena
37
+
38
+ Returns:
39
+ list: list of fixture configurations
40
+ """
41
+ fixture_cfgs = []
42
+ for name, fxtr in self.fixtures.items():
43
+ cfg = {}
44
+ cfg["name"] = name
45
+ cfg["model"] = fxtr
46
+ cfg["type"] = "fixture"
47
+ if hasattr(fxtr, "_placement"):
48
+ cfg["placement"] = fxtr._placement
49
+
50
+ fixture_cfgs.append(cfg)
51
+
52
+ return fixture_cfgs
third_party/robocasa/robocasa/scripts/demo_task.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import gymnasium as gym
4
+ import numpy as np
5
+ import pytest
6
+ from pathlib import Path
7
+ from gymnasium import spaces
8
+
9
+ import robocasa # noqa: F401
10
+ import robosuite # noqa: F401
11
+ from robocasa.utils.gym_utils import GrootRoboCasaEnv # noqa: F401
12
+ from gr00t.eval.wrappers.video_recording_wrapper import (
13
+ VideoRecorder,
14
+ VideoRecordingWrapper,
15
+ )
16
+
17
+
18
+ def demo_robocasa_digital_cousin_env(env_id, video_dir):
19
+ env = gym.make(env_id, enable_render=True)
20
+ video_recorder = VideoRecorder.create_h264(
21
+ fps=10,
22
+ codec="h264",
23
+ input_pix_fmt="rgb24",
24
+ crf=22,
25
+ thread_type="FRAME",
26
+ thread_count=1,
27
+ )
28
+ env = VideoRecordingWrapper(
29
+ env,
30
+ video_recorder,
31
+ video_dir=Path(video_dir),
32
+ )
33
+
34
+ # raw obs from env is in float64, convert to float32
35
+ obs, _ = env.reset()
36
+ for _ in range(20):
37
+ action = env.action_space.sample()
38
+ obs, _, _, _, _ = env.step(action)
39
+ env.render()
40
+ env.close()
41
+
42
+
43
+ if __name__ == "__main__":
44
+ env_id = sys.argv[1]
45
+ video_dir = os.path.join(os.getcwd(), "video")
46
+ os.makedirs(video_dir, exist_ok=True)
47
+ demo_robocasa_digital_cousin_env(env_id, video_dir=video_dir)
third_party/robocasa/robocasa/scripts/download_groot_assets.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import dataclasses
3
+ import enum
4
+ import json
5
+ import logging
6
+ import os
7
+ from pathlib import Path
8
+ from typing import Optional
9
+ import urllib.request
10
+
11
+ from download_kitchen_assets import download_kitchen_assets as download
12
+
13
+ DEFAULT_ASSETS_VERSION = "1b018839a6da865dffecd3185fe054211bc71270"
14
+ REPO_ID = "nvidia/PhysicalAI-DigitalCousin-Assets"
15
+ API_URL = f"https://huggingface.co/api/datasets/{REPO_ID}"
16
+ SOURCE_URL = f"https://huggingface.co/datasets/{REPO_ID}"
17
+
18
+
19
+ class Registry(enum.Enum):
20
+ SKETCHFAB = "sketchfab"
21
+ LIGHTWHEEL = "lightwheel"
22
+
23
+
24
+ @dataclasses.dataclass(frozen=True)
25
+ class DownloadConfig:
26
+ registries: set[Registry]
27
+
28
+ @classmethod
29
+ def from_args(cls, registry_names: Optional[list[str]] = None) -> "DownloadConfig":
30
+ valid_registries = (
31
+ {r for r in Registry if r.value in registry_names}
32
+ if registry_names
33
+ else set(Registry)
34
+ )
35
+ return cls(registries=valid_registries)
36
+
37
+
38
+ def get_available_registries(revision: str) -> set[Registry]:
39
+ url = f"{API_URL}?revision={revision}"
40
+ with urllib.request.urlopen(url) as resp:
41
+ resp = json.load(resp)
42
+ tree = resp["siblings"]
43
+ stems = {Path(item["rfilename"]).stem for item in tree}
44
+ return {r for r in Registry if r.value in stems}
45
+
46
+
47
+ def get_groot_asset_registry(
48
+ download_config: DownloadConfig, version: Optional[str]
49
+ ) -> dict:
50
+ logging.info(
51
+ f"Initiating download for the specified assets: {', '.join(r.value for r in download_config.registries)}..."
52
+ )
53
+
54
+ if version:
55
+ logging.info(f"Initiating download for assets at revision '{version}'...")
56
+ else:
57
+ version = DEFAULT_ASSETS_VERSION
58
+ logging.info(
59
+ f"No revision specified; proceeding with the default version '{version}'..."
60
+ )
61
+
62
+ available_registries = get_available_registries(version)
63
+ registry = {}
64
+ for r in download_config.registries:
65
+ if r not in available_registries:
66
+ logging.warning(
67
+ f"Requested registry '{r.value}' is not available at revision '{version}', skipping..."
68
+ )
69
+ continue
70
+ registry[r.value] = dict(
71
+ message=f"Downloading {r.value} assets",
72
+ url=f"{SOURCE_URL}/resolve/{version}/{r.value}.zip",
73
+ folder=os.path.join(
74
+ os.path.dirname(__file__), f"../models/assets/objects/{r.value}"
75
+ ),
76
+ check_folder_exists=False,
77
+ )
78
+ return registry
79
+
80
+
81
+ def download_groot_assets(
82
+ download_config: DownloadConfig,
83
+ version: str,
84
+ bypass: bool,
85
+ update_registry: bool = False,
86
+ ):
87
+ import download_kitchen_assets
88
+
89
+ groot_asset_registry = get_groot_asset_registry(
90
+ download_config=download_config, version=version
91
+ )
92
+ if update_registry:
93
+ download_kitchen_assets.DOWNLOAD_ASSET_REGISTRY.update(groot_asset_registry)
94
+ else:
95
+ download_kitchen_assets.DOWNLOAD_ASSET_REGISTRY = groot_asset_registry
96
+ download(bypass=bypass)
97
+
98
+
99
+ if __name__ == "__main__":
100
+ parser = argparse.ArgumentParser()
101
+ parser.add_argument(
102
+ "-y",
103
+ "--yes",
104
+ action="store_true",
105
+ help="Download assets directly without prompting to screen",
106
+ )
107
+ parser.add_argument(
108
+ "-a",
109
+ "--assets",
110
+ nargs="*",
111
+ help="Specify a list of asset names to download (leave empty to download all assets)",
112
+ )
113
+ parser.add_argument(
114
+ "-r",
115
+ "--revision",
116
+ help="Specify the release tag or revision number of the assets to download",
117
+ )
118
+ parser.add_argument(
119
+ "-v",
120
+ "--verbose",
121
+ action="store_true",
122
+ help="Print verbose output",
123
+ )
124
+ args = parser.parse_args()
125
+
126
+ if args.verbose:
127
+ logging.getLogger().setLevel(logging.INFO)
128
+ cfg = DownloadConfig.from_args(args.assets)
129
+
130
+ download_groot_assets(
131
+ download_config=cfg,
132
+ version=args.revision,
133
+ bypass=args.yes,
134
+ update_registry=False,
135
+ )
third_party/robocasa/robocasa/scripts/download_kitchen_assets.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import sys
4
+ import time
5
+ import urllib.request
6
+ from pathlib import Path
7
+ from zipfile import ZipFile
8
+
9
+ from termcolor import colored
10
+ from tqdm import tqdm
11
+
12
+ DOWNLOAD_ASSET_REGISTRY = dict(
13
+ textures=dict(
14
+ message="Downloading environment textures",
15
+ url="https://utexas.box.com/shared/static/otdsyfjontk17jdp24bkhy2hgalofbh4.zip",
16
+ folder=os.path.join(os.path.dirname(__file__), "../models/assets/textures"),
17
+ check_folder_exists=False,
18
+ ),
19
+ fixtures=dict(
20
+ message="Downloading fixtures",
21
+ url="https://utexas.box.com/shared/static/pobhbsjyacahg2mx8x4rm5fkz3wlmyzp.zip",
22
+ folder=os.path.join(os.path.dirname(__file__), "../models/assets/fixtures"),
23
+ check_folder_exists=False,
24
+ ),
25
+ objaverse=dict(
26
+ message="Downloading objaverse objects",
27
+ url="https://utexas.box.com/shared/static/ejt1kc2v5vhae1rl4k5697i4xvpbjcox.zip",
28
+ folder=os.path.join(
29
+ os.path.dirname(__file__), "../models/assets/objects/objaverse"
30
+ ),
31
+ check_folder_exists=False,
32
+ ),
33
+ aigen_objs=dict(
34
+ message="Downloading AI-generated objects",
35
+ url="https://utexas.box.com/shared/static/os3hrui06lasnuvwqpmwn0wcrduh6jg3.zip",
36
+ folder=os.path.join(
37
+ os.path.dirname(__file__), "../models/assets/objects/aigen_objs"
38
+ ),
39
+ check_folder_exists=False,
40
+ ),
41
+ generative_textures=dict(
42
+ message="Downloading AI-generated environment textures",
43
+ url="https://utexas.box.com/shared/static/gf9nkadvfrowkb9lmkcx58jwt4d6c1g3.zip",
44
+ folder=os.path.join(
45
+ os.path.dirname(__file__), "../models/assets/generative_textures"
46
+ ),
47
+ check_folder_exists=False,
48
+ ),
49
+ )
50
+
51
+
52
+ class DownloadProgressBar(tqdm):
53
+ def update_to(self, b=1, bsize=1, tsize=None):
54
+ if tsize is not None:
55
+ self.total = tsize
56
+ self.update(b * bsize - self.n)
57
+
58
+
59
+ def url_is_alive(url):
60
+ """
61
+ Checks that a given URL is reachable.
62
+ From https://gist.github.com/dehowell/884204.
63
+
64
+ Args:
65
+ url (str): url string
66
+
67
+ Returns:
68
+ is_alive (bool): True if url is reachable, False otherwise
69
+ """
70
+ request = urllib.request.Request(url)
71
+ request.get_method = lambda: "HEAD"
72
+
73
+ try:
74
+ urllib.request.urlopen(request)
75
+ return True
76
+ except urllib.request.HTTPError:
77
+ return False
78
+
79
+
80
+ def download_url(url, download_dir, fname=None, check_overwrite=True):
81
+ """
82
+ First checks that @url is reachable, then downloads the file
83
+ at that url into the directory specified by @download_dir.
84
+ Prints a progress bar during the download using tqdm.
85
+
86
+ Modified from https://github.com/tqdm/tqdm#hooks-and-callbacks, and
87
+ https://stackoverflow.com/a/53877507.
88
+
89
+ Args:
90
+ url (str): url string
91
+ download_dir (str): path to directory where file should be downloaded
92
+ check_overwrite (bool): if True, will sanity check the download fpath to make sure a file of that name
93
+ doesn't already exist there
94
+ """
95
+
96
+ # check if url is reachable. We need the sleep to make sure server doesn't reject subsequent requests
97
+ # assert url_is_alive(url), "@download_url got unreachable url: {}".format(url)
98
+ # time.sleep(0.5)
99
+
100
+ if fname is None:
101
+ # infer filename from url link
102
+ fname = url.split("/")[-1]
103
+ file_to_write = os.path.join(download_dir, fname)
104
+
105
+ # If we're checking overwrite and the path already exists,
106
+ # we ask the user to verify that they want to overwrite the file
107
+ if check_overwrite and os.path.exists(file_to_write):
108
+ user_response = input(
109
+ f"Warning: file {file_to_write} already exists. Overwrite? y/n "
110
+ )
111
+ assert user_response.lower() in {
112
+ "yes",
113
+ "y",
114
+ }, f"Did not receive confirmation. Aborting download."
115
+
116
+ print(colored(f"Downloading to {file_to_write}", "yellow"))
117
+
118
+ with DownloadProgressBar(unit="B", unit_scale=True, miniters=1, desc=fname) as t:
119
+ urllib.request.urlretrieve(url, filename=file_to_write, reporthook=t.update_to)
120
+
121
+
122
+ def download_and_extract_zip(
123
+ url,
124
+ folder,
125
+ check_folder_exists=True,
126
+ prompt_before_download=False,
127
+ message="Downloading...",
128
+ ):
129
+ assert url.endswith(".zip")
130
+
131
+ download_dir = os.path.abspath(os.path.join(folder, os.pardir))
132
+ Path(download_dir).mkdir(parents=True, exist_ok=True)
133
+
134
+ download_path = os.path.join(
135
+ download_dir, "{}.zip".format(os.path.basename(folder))
136
+ )
137
+
138
+ print(colored(message, "yellow"))
139
+
140
+ # extract files
141
+ if check_folder_exists and os.path.exists(folder):
142
+ ans = input("{} already exists! \noverwrite? (y/n) ".format(folder))
143
+
144
+ if ans == "y":
145
+ print(colored("Proceeding.", "yellow"))
146
+ else:
147
+ print(colored("Skipping.\n", "yellow"))
148
+ return
149
+
150
+ if prompt_before_download:
151
+ ans = input(
152
+ "Assets to be downloaded may be a few Gb. Proceed? (y/n) ".format(folder)
153
+ )
154
+
155
+ if ans == "y":
156
+ print(colored("Proceeding.", "yellow"))
157
+ else:
158
+ print(colored("Skipping.\n", "yellow"))
159
+ return
160
+
161
+ download_success = False
162
+ for i in range(3):
163
+ try:
164
+ download_url(
165
+ url=url,
166
+ download_dir=download_dir,
167
+ fname=os.path.basename(download_path),
168
+ check_overwrite=False,
169
+ )
170
+ download_success = True
171
+ break
172
+ except:
173
+ print("Error downloading after try #{}".format(i + 1))
174
+
175
+ if download_success is False:
176
+ print("Failed to download. Try again...")
177
+ return
178
+
179
+ print(colored("Extracting...", "yellow"))
180
+ with ZipFile(download_path, "r") as zip_ref:
181
+ # Extracting all the members of the zip
182
+ # into a specific location.
183
+ zip_ref.extractall(path=download_dir)
184
+
185
+ # delete zip file
186
+ os.remove(download_path)
187
+
188
+ print(colored("Done.\n", "yellow"))
189
+
190
+
191
+ def download_kitchen_assets(bypass=False):
192
+ if bypass:
193
+ ans = "y"
194
+ else:
195
+ ans = input("The script will download ~5 Gb of data. Proceed? (y/n) ")
196
+ if ans == "y":
197
+ print("Proceeding...")
198
+ else:
199
+ print("Aborting.")
200
+ return
201
+
202
+ for ds_name, config in DOWNLOAD_ASSET_REGISTRY.items():
203
+ if ds_name == "aigen_objs":
204
+ continue # skip for now, too large to download initially
205
+ download_and_extract_zip(**config)
206
+
207
+
208
+ if __name__ == "__main__":
209
+ parser = argparse.ArgumentParser()
210
+ parser.add_argument(
211
+ "-y",
212
+ "--yes",
213
+ action="store_true",
214
+ help="Download assets directly without prompting to screen",
215
+ )
216
+ args = parser.parse_args()
217
+
218
+ download_kitchen_assets(args.yes)
third_party/robocasa/robocasa/scripts/download_tabletop_assets.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from download_groot_assets import (
4
+ download_groot_assets,
5
+ DownloadConfig,
6
+ DEFAULT_ASSETS_VERSION,
7
+ Registry,
8
+ )
9
+
10
+
11
+ def download_dc_assets(bypass: bool):
12
+ cfg = DownloadConfig(registries={Registry.SKETCHFAB, Registry.LIGHTWHEEL})
13
+ download_groot_assets(
14
+ download_config=cfg,
15
+ version=DEFAULT_ASSETS_VERSION,
16
+ bypass=bypass,
17
+ update_registry=True,
18
+ )
19
+
20
+
21
+ if __name__ == "__main__":
22
+ parser = argparse.ArgumentParser()
23
+ parser.add_argument(
24
+ "-y",
25
+ "--yes",
26
+ action="store_true",
27
+ help="Download assets directly without prompting to screen",
28
+ )
29
+ args = parser.parse_args()
30
+ download_dc_assets(args.yes)
third_party/robocasa/robocasa/scripts/playback_dataset.py ADDED
@@ -0,0 +1,643 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import cv2
3
+ import datetime
4
+ import json
5
+ import os
6
+ import hashlib
7
+ import random
8
+ import shutil
9
+ import sys
10
+ import time
11
+
12
+ import h5py
13
+ import imageio
14
+ import numpy as np
15
+ import robocasa
16
+ import robosuite
17
+ import robosuite.utils.transform_utils as T
18
+ from concurrent.futures import ProcessPoolExecutor, as_completed
19
+ from functools import partial
20
+ from itertools import product
21
+ from termcolor import colored
22
+ from tqdm import tqdm
23
+
24
+
25
+ def playback_trajectory_with_env(
26
+ args,
27
+ f,
28
+ ep,
29
+ env,
30
+ initial_state,
31
+ states,
32
+ actions=None,
33
+ render=False,
34
+ video_writer=None,
35
+ video_skip=5,
36
+ camera_names=None,
37
+ first=False,
38
+ verbose=False,
39
+ ):
40
+ """
41
+ Helper function to playback a single trajectory using the simulator environment.
42
+ If @actions are not None, it will play them open-loop after loading the initial state.
43
+ Otherwise, @states are loaded one by one.
44
+
45
+ Args:
46
+ args (argparse.Namespace): command line arguments
47
+ f (hdf5 file): hdf5 file object
48
+ ep (str): episode name
49
+ env (instance of EnvBase): environment
50
+ initial_state (dict): initial simulation state to load
51
+ states (np.array): array of simulation states to load
52
+ actions (np.array): if provided, play actions back open-loop instead of using @states
53
+ render (bool): if True, render on-screen
54
+ video_writer (imageio writer): video writer
55
+ video_skip (int): determines rate at which environment frames are written to video
56
+ camera_names (list): determines which camera(s) are used for rendering. Pass more than
57
+ one to output a video with multiple camera views concatenated horizontally.
58
+ first (bool): if True, only use the first frame of each episode.
59
+ verbose (bool): if True, print additional information
60
+ """
61
+ write_video = video_writer is not None
62
+ video_count = 0
63
+ assert not (render and write_video)
64
+
65
+ # load the initial state
66
+ ## this reset call doesn't seem necessary.
67
+ ## seems ok to remove but haven't fully tested it.
68
+ ## removing for now
69
+ # env.reset()
70
+
71
+ if verbose:
72
+ ep_meta = json.loads(initial_state["ep_meta"])
73
+ lang = ep_meta.get("lang", None)
74
+ if lang is not None:
75
+ print(colored(f"Instruction: {lang}", "green"))
76
+ print(colored("Spawning environment...", "yellow"))
77
+ reset_to(env, initial_state)
78
+
79
+ traj_len = states.shape[0]
80
+ action_playback = actions is not None
81
+ if action_playback:
82
+ assert states.shape[0] == actions.shape[0]
83
+
84
+ if render is False:
85
+ print(colored("Running episode...", "yellow"))
86
+
87
+ if args.num_frames is None:
88
+ start_frame = 0
89
+ end_frame = traj_len
90
+ else:
91
+ start_frame = random.randrange(traj_len - min(args.num_frames, traj_len) + 1)
92
+ end_frame = start_frame + min(args.num_frames, traj_len)
93
+ for i in tqdm(range(start_frame, end_frame)):
94
+ start = time.time()
95
+
96
+ if action_playback:
97
+ env.step(actions[i])
98
+ if i < traj_len - 1:
99
+ # check whether the actions deterministically lead to the same recorded states
100
+ state_playback = np.array(env.sim.get_state().flatten())
101
+ if not np.all(np.equal(states[i + 1], state_playback)):
102
+ err = np.linalg.norm(states[i + 1] - state_playback)
103
+ if verbose or i == traj_len - 2:
104
+ print(
105
+ colored(
106
+ "warning: playback diverged by {} at step {}".format(
107
+ err, i
108
+ ),
109
+ "yellow",
110
+ )
111
+ )
112
+ else:
113
+ reset_to(env, {"states": states[i]})
114
+
115
+ # on-screen render
116
+ if render:
117
+ if env.viewer is None:
118
+ env.initialize_renderer()
119
+
120
+ # so that mujoco viewer renders
121
+ env.viewer.update()
122
+
123
+ max_fr = 60
124
+ elapsed = time.time() - start
125
+ diff = 1 / max_fr - elapsed
126
+ if diff > 0:
127
+ time.sleep(diff)
128
+
129
+ # video render
130
+ if write_video:
131
+ if video_count % video_skip == 0:
132
+ video_img = []
133
+ for cam_name in camera_names:
134
+ im = env.sim.render(
135
+ height=args.render_height,
136
+ width=args.render_width,
137
+ camera_name=cam_name,
138
+ )[::-1]
139
+ video_img.append(im)
140
+ video_img = np.concatenate(
141
+ video_img, axis=1
142
+ ) # concatenate horizontally
143
+ video_writer.append_data(video_img)
144
+ video_count += 1
145
+
146
+ if first:
147
+ break
148
+
149
+ if render:
150
+ env.viewer.close()
151
+ env.viewer = None
152
+
153
+
154
+ def playback_trajectory_with_obs(
155
+ traj_grp,
156
+ video_writer,
157
+ video_skip=5,
158
+ image_names=None,
159
+ first=False,
160
+ ):
161
+ """
162
+ This function reads all "rgb" observations in the dataset trajectory and
163
+ writes them into a video.
164
+
165
+ Args:
166
+ traj_grp (hdf5 file group): hdf5 group which corresponds to the dataset trajectory to playback
167
+ video_writer (imageio writer): video writer
168
+ video_skip (int): determines rate at which environment frames are written to video
169
+ image_names (list): determines which image observations are used for rendering. Pass more than
170
+ one to output a video with multiple image observations concatenated horizontally.
171
+ first (bool): if True, only use the first frame of each episode.
172
+ """
173
+ assert (
174
+ image_names is not None
175
+ ), "error: must specify at least one image observation to use in @image_names"
176
+ video_count = 0
177
+
178
+ traj_len = traj_grp["obs/{}".format(image_names[0] + "_image")].shape[0]
179
+ for i in range(traj_len):
180
+ if video_count % video_skip == 0:
181
+ # concatenate image obs together
182
+ im = [traj_grp["obs/{}".format(k + "_image")][i] for k in image_names]
183
+ frame = np.concatenate(im, axis=1)
184
+ video_writer.append_data(frame)
185
+ video_count += 1
186
+
187
+ if first:
188
+ break
189
+
190
+
191
+ def get_env_metadata_from_dataset(dataset_path, ds_format="robomimic"):
192
+ """
193
+ Retrieves env metadata from dataset.
194
+
195
+ Args:
196
+ dataset_path (str): path to dataset
197
+
198
+ Returns:
199
+ env_meta (dict): environment metadata. Contains 3 keys:
200
+
201
+ :`'env_name'`: name of environment
202
+ :`'type'`: type of environment, should be a value in EB.EnvType
203
+ :`'env_kwargs'`: dictionary of keyword arguments to pass to environment constructor
204
+ """
205
+ dataset_path = os.path.expanduser(dataset_path)
206
+ try:
207
+ f = h5py.File(dataset_path, "r")
208
+ except Exception as e:
209
+ print(f"Error opening file {args.dataset}: {e}")
210
+ sys.exit(1)
211
+ if ds_format == "robomimic":
212
+ env_meta = json.loads(f["data"].attrs["env_args"])
213
+ else:
214
+ raise ValueError
215
+ f.close()
216
+ return env_meta
217
+
218
+
219
+ class ObservationKeyToModalityDict(dict):
220
+ """
221
+ Custom dictionary class with the sole additional purpose of automatically registering new "keys" at runtime
222
+ without breaking. This is mainly for backwards compatibility, where certain keys such as "latent", "actions", etc.
223
+ are used automatically by certain models (e.g.: VAEs) but were never specified by the user externally in their
224
+ config. Thus, this dictionary will automatically handle those keys by implicitly associating them with the low_dim
225
+ modality.
226
+ """
227
+
228
+ def __getitem__(self, item):
229
+ # If a key doesn't already exist, warn the user and add default mapping
230
+ if item not in self.keys():
231
+ print(
232
+ f"ObservationKeyToModalityDict: {item} not found,"
233
+ f" adding {item} to mapping with assumed low_dim modality!"
234
+ )
235
+ self.__setitem__(item, "low_dim")
236
+ return super(ObservationKeyToModalityDict, self).__getitem__(item)
237
+
238
+
239
+ def reset_to(env, state):
240
+ """
241
+ Reset to a specific simulator state.
242
+
243
+ Args:
244
+ state (dict): current simulator state that contains one or more of:
245
+ - states (np.ndarray): initial state of the mujoco environment
246
+ - model (str): mujoco scene xml
247
+
248
+ Returns:
249
+ observation (dict): observation dictionary after setting the simulator state (only
250
+ if "states" is in @state)
251
+ """
252
+ should_ret = False
253
+ if "model" in state:
254
+ if state.get("ep_meta", None) is not None:
255
+ # set relevant episode information
256
+ ep_meta = json.loads(state["ep_meta"])
257
+ else:
258
+ ep_meta = {}
259
+ if hasattr(env, "set_attrs_from_ep_meta"): # older versions had this function
260
+ env.set_attrs_from_ep_meta(ep_meta)
261
+ elif hasattr(env, "set_ep_meta"): # newer versions
262
+ env.set_ep_meta(ep_meta)
263
+ # this reset is necessary.
264
+ # while the call to env.reset_from_xml_string does call reset,
265
+ # that is only a "soft" reset that doesn't actually reload the model.
266
+ env.reset()
267
+ robosuite_version_id = int(robosuite.__version__.split(".")[1])
268
+ if robosuite_version_id <= 3:
269
+ from robosuite.utils.mjcf_utils import postprocess_model_xml
270
+
271
+ xml = postprocess_model_xml(state["model"])
272
+ else:
273
+ # v1.4 and above use the class-based edit_model_xml function
274
+ xml = env.edit_model_xml(state["model"])
275
+
276
+ env.reset_from_xml_string(xml)
277
+ env.sim.reset()
278
+ # hide teleop visualization after restoring from model
279
+ # env.sim.model.site_rgba[env.eef_site_id] = np.array([0., 0., 0., 0.])
280
+ # env.sim.model.site_rgba[env.eef_cylinder_id] = np.array([0., 0., 0., 0.])
281
+ if "states" in state:
282
+ env.sim.set_state_from_flattened(state["states"])
283
+ env.sim.forward()
284
+ should_ret = True
285
+
286
+ # update state as needed
287
+ if hasattr(env, "update_sites"):
288
+ # older versions of environment had update_sites function
289
+ env.update_sites()
290
+ if hasattr(env, "update_state"):
291
+ # later versions renamed this to update_state
292
+ env.update_state()
293
+
294
+ # if should_ret:
295
+ # # only return obs if we've done a forward call - otherwise the observations will be garbage
296
+ # return get_observation()
297
+ return None
298
+
299
+
300
+ def make_env_from_args(args):
301
+ # # need to make sure ObsUtils knows which observations are images, but it doesn't matter
302
+ # # for playback since observations are unused. Pass a dummy spec here.
303
+ # dummy_spec = dict(
304
+ # obs=dict(
305
+ # low_dim=["robot0_eef_pos"],
306
+ # rgb=[],
307
+ # ),
308
+ # )
309
+ # initialize_obs_utils_with_obs_specs(obs_modality_specs=dummy_spec)
310
+
311
+ env_meta = get_env_metadata_from_dataset(dataset_path=args.dataset)
312
+ if args.use_abs_actions:
313
+ env_meta["env_kwargs"]["controller_configs"][
314
+ "control_delta"
315
+ ] = False # absolute action space
316
+
317
+ env_kwargs = env_meta["env_kwargs"]
318
+ env_kwargs["env_name"] = env_meta["env_name"]
319
+ env_kwargs["has_renderer"] = False
320
+ env_kwargs["renderer"] = "mjviewer"
321
+ env_kwargs["has_offscreen_renderer"] = not args.render
322
+ env_kwargs["use_camera_obs"] = False
323
+
324
+ if args.verbose:
325
+ print(
326
+ colored(
327
+ "Initializing environment for {}...".format(env_kwargs["env_name"]),
328
+ "yellow",
329
+ )
330
+ )
331
+ if "env_lang" in env_kwargs:
332
+ env_kwargs.pop("env_lang")
333
+ env = robosuite.make(**env_kwargs)
334
+ return env
335
+
336
+
337
+ # Three components when processing a demo:
338
+ # 1. Load the dataset into the variable `f`: This step ensures that the necessary data for the demo,
339
+ # such as states, actions, and metadata, is available for playback.
340
+ # 2. Initialize a video writer: If video output is required, this step sets up the writer to save
341
+ # the playback as a video file.
342
+ # 3. Create the environment `env` (optional): This step initializes the simulation environment, which
343
+ # is essential for rendering and interacting with the demo data.
344
+ def process_demo(args, ep):
345
+ print(colored("\nPlaying back episode: {}".format(ep), "yellow"))
346
+
347
+ # maybe dump video
348
+ write_video = args.render is not True
349
+ video_writer = None
350
+ if write_video:
351
+ ep_path = args.video_path[:-4] + "_" + ep + ".mp4"
352
+ video_writer = imageio.get_writer(ep_path, fps=20)
353
+
354
+ try:
355
+ f = h5py.File(args.dataset, "r")
356
+ except Exception as e:
357
+ print(f"Error opening file {args.dataset}: {e}")
358
+ sys.exit(1)
359
+
360
+ if args.use_obs:
361
+ playback_trajectory_with_obs(
362
+ traj_grp=f["data/{}".format(ep)],
363
+ video_writer=video_writer,
364
+ video_skip=args.video_skip,
365
+ image_names=args.render_image_names,
366
+ first=args.first,
367
+ )
368
+ if write_video:
369
+ print(colored(f"Saved video to {ep_path}", "green"))
370
+ video_writer.close()
371
+ f.close()
372
+ return
373
+
374
+ # create environment only if not playing back with observations
375
+ env = make_env_from_args(args)
376
+
377
+ def make_ik_indicator_invisible(str_xml):
378
+ import xml.etree.ElementTree as ET
379
+
380
+ raw_xml = ET.fromstring(str_xml)
381
+ for site in raw_xml.findall(".//site"):
382
+ name = site.get("name", "")
383
+ if "pinch_spheres" in name:
384
+ print(
385
+ colored(
386
+ "make site invisible: {}".format(name),
387
+ "yellow",
388
+ )
389
+ )
390
+ site.set("rgba", "0 0 0 0")
391
+ return ET.tostring(raw_xml)
392
+
393
+ # prepare initial state to reload from
394
+ states = f["data/{}/states".format(ep)][()]
395
+ initial_state = dict(states=states[0])
396
+ initial_state["model"] = make_ik_indicator_invisible(
397
+ f["data/{}".format(ep)].attrs["model_file"]
398
+ )
399
+ if args.use_current_env_model:
400
+ initial_state["model"] = env.sim.model.get_xml()
401
+ initial_state["ep_meta"] = f["data/{}".format(ep)].attrs.get("ep_meta", None)
402
+
403
+ if args.extend_states:
404
+ states = np.concatenate((states, [states[-1]] * 50))
405
+
406
+ # supply actions if using open-loop action playback
407
+ actions = None
408
+ assert not (
409
+ args.use_actions and args.use_abs_actions
410
+ ) # cannot use both relative and absolute actions
411
+ if args.use_actions:
412
+ actions = f["data/{}/actions".format(ep)][()]
413
+ elif args.use_abs_actions:
414
+ actions = f["data/{}/actions_abs".format(ep)][()] # absolute actions
415
+
416
+ playback_trajectory_with_env(
417
+ args=args,
418
+ f=f,
419
+ ep=ep,
420
+ env=env,
421
+ initial_state=initial_state,
422
+ states=states,
423
+ actions=actions,
424
+ render=args.render,
425
+ video_writer=video_writer,
426
+ video_skip=args.video_skip,
427
+ camera_names=args.render_image_names,
428
+ first=args.first,
429
+ verbose=args.verbose,
430
+ )
431
+
432
+ if write_video:
433
+ print(colored(f"Saved video to {ep_path}", "green"))
434
+ video_writer.close()
435
+
436
+ f.close()
437
+ env.close()
438
+
439
+
440
+ def playback_dataset(args):
441
+ # some arg checking
442
+ write_video = args.render is not True
443
+ if args.video_path is None:
444
+ args.video_path = args.dataset.split(".hdf5")[0] + ".mp4"
445
+ if args.use_actions:
446
+ args.video_path = args.dataset.split(".hdf5")[0] + "_use_actions.mp4"
447
+ elif args.use_abs_actions:
448
+ args.video_path = args.dataset.split(".hdf5")[0] + "_use_abs_actions.mp4"
449
+ assert not (args.render and write_video) # either on-screen or video but not both
450
+
451
+ # Auto-fill camera rendering info if not specified
452
+ if args.render_image_names is None:
453
+ # We fill in the automatic values
454
+ env_meta = get_env_metadata_from_dataset(dataset_path=args.dataset)
455
+ args.render_image_names = "robot0_agentview_center"
456
+
457
+ if args.render:
458
+ # on-screen rendering can only support one camera
459
+ assert len(args.render_image_names) == 1
460
+
461
+ if args.use_obs:
462
+ assert write_video, "playback with observations can only write to video"
463
+ assert (
464
+ not args.use_actions and not args.use_abs_actions
465
+ ), "playback with observations is offline and does not support action playback"
466
+
467
+ try:
468
+ f = h5py.File(args.dataset, "r")
469
+ except Exception as e:
470
+ print(f"Error opening file {args.dataset}: {e}")
471
+ sys.exit(1)
472
+
473
+ # list of all demonstration episodes (sorted in increasing number order)
474
+ if args.filter_key is not None:
475
+ print("using filter key: {}".format(args.filter_key))
476
+ demos = [
477
+ elem.decode("utf-8")
478
+ for elem in np.array(f["mask/{}".format(args.filter_key)])
479
+ ]
480
+ elif "data" in f.keys():
481
+ demos = list(f["data"].keys())
482
+
483
+ inds = np.argsort([int(elem[5:]) for elem in demos])
484
+ demos = [demos[i] for i in inds]
485
+
486
+ # maybe reduce the number of demonstrations to playback
487
+ if args.n is not None:
488
+ random.shuffle(demos)
489
+ demos = demos[: args.n]
490
+
491
+ if args.num_parallel_jobs == 1:
492
+ # reuse the same environment for all demos
493
+ for ep in tqdm(demos):
494
+ process_demo(args, ep)
495
+ else:
496
+ with ProcessPoolExecutor(max_workers=args.num_parallel_jobs) as executor:
497
+ process_demo_with_args = partial(process_demo, args)
498
+ futures = {executor.submit(process_demo_with_args, ep): ep for ep in demos}
499
+ for future in tqdm(as_completed(futures), total=len(futures)):
500
+ ep = futures[future]
501
+ try:
502
+ result = (
503
+ future.result()
504
+ ) # Raises any exception that occurred during execution
505
+ except Exception as e:
506
+ print(f"[ERROR] Episode {ep}: {e}")
507
+
508
+ f.close()
509
+
510
+
511
+ if __name__ == "__main__":
512
+ parser = argparse.ArgumentParser()
513
+ parser.add_argument(
514
+ "--dataset",
515
+ type=str,
516
+ help="path to hdf5 dataset",
517
+ )
518
+ parser.add_argument(
519
+ "--filter_key",
520
+ type=str,
521
+ default=None,
522
+ help="(optional) filter key, to select a subset of trajectories in the file",
523
+ )
524
+
525
+ # number of trajectories to playback. If omitted, playback all of them.
526
+ parser.add_argument(
527
+ "--n",
528
+ type=int,
529
+ default=None,
530
+ help="(optional) stop after n trajectories are played",
531
+ )
532
+
533
+ parser.add_argument(
534
+ "--num_parallel_jobs",
535
+ type=int,
536
+ default=1,
537
+ help="(optional) number of parallel jobs to use for playback",
538
+ )
539
+
540
+ parser.add_argument(
541
+ "--num_frames",
542
+ type=int,
543
+ default=None,
544
+ help="(optional) number of frames to playback",
545
+ )
546
+
547
+ # Use image observations instead of doing playback using the simulator env.
548
+ parser.add_argument(
549
+ "--use-obs",
550
+ action="store_true",
551
+ help="visualize trajectories with dataset image observations instead of simulator",
552
+ )
553
+
554
+ # Playback stored dataset actions open-loop instead of loading from simulation states.
555
+ parser.add_argument(
556
+ "--use-actions",
557
+ action="store_true",
558
+ help="use open-loop action playback instead of loading sim states",
559
+ )
560
+
561
+ # Playback stored dataset absolute actions open-loop instead of loading from simulation states.
562
+ parser.add_argument(
563
+ "--use-abs-actions",
564
+ action="store_true",
565
+ help="use open-loop action playback with absolute position actions instead of loading sim states",
566
+ )
567
+
568
+ # Whether to render playback to screen
569
+ parser.add_argument(
570
+ "--render",
571
+ action="store_true",
572
+ help="on-screen rendering",
573
+ )
574
+
575
+ # Dump a video of the dataset playback to the specified path
576
+ parser.add_argument(
577
+ "--video_path",
578
+ type=str,
579
+ default=None,
580
+ help="(optional) render trajectories to this video file path",
581
+ )
582
+
583
+ # How often to write video frames during the playback
584
+ parser.add_argument(
585
+ "--video_skip",
586
+ type=int,
587
+ default=1,
588
+ help="render frames to video every n steps",
589
+ )
590
+
591
+ # camera names to render, or image observations to use for writing to video
592
+ parser.add_argument(
593
+ "--render_image_names",
594
+ type=str,
595
+ nargs="+",
596
+ default=[
597
+ "egoview",
598
+ ],
599
+ help="(optional) camera name(s) / image observation(s) to use for rendering on-screen or to video. Default is"
600
+ "None, which corresponds to a predefined camera for each env type",
601
+ )
602
+
603
+ parser.add_argument(
604
+ "--render_height",
605
+ type=int,
606
+ default=512,
607
+ help="(optional) height of rendered video frames",
608
+ )
609
+
610
+ parser.add_argument(
611
+ "--render_width",
612
+ type=int,
613
+ default=512,
614
+ help="(optional) width of rendered video frames",
615
+ )
616
+
617
+ # Only use the first frame of each episode
618
+ parser.add_argument(
619
+ "--first",
620
+ action="store_true",
621
+ help="use first frame of each episode",
622
+ )
623
+
624
+ parser.add_argument(
625
+ "--extend_states",
626
+ action="store_true",
627
+ help="play last step of episodes for 50 extra frames",
628
+ )
629
+
630
+ parser.add_argument(
631
+ "--verbose",
632
+ action="store_true",
633
+ help="log additional information",
634
+ )
635
+
636
+ parser.add_argument(
637
+ "--use_current_env_model",
638
+ action="store_true",
639
+ help="use the current environment model instead of the one stored in the dataset",
640
+ )
641
+
642
+ args = parser.parse_args()
643
+ playback_dataset(args)
third_party/robocasa/robocasa/utils/camera_utils.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Collection of constants for cameras / robots / etc
3
+ in kitchen environments
4
+ """
5
+
6
+ # default free cameras for different kitchen layouts
7
+ LAYOUT_CAMS = {
8
+ 0: dict(
9
+ lookat=[2.26593463, -1.00037131, 1.38769295],
10
+ distance=3.0505089839567323,
11
+ azimuth=90.71563812375285,
12
+ elevation=-12.63948837207208,
13
+ ),
14
+ 1: dict(
15
+ lookat=[2.66147999, -1.00162429, 1.2425155],
16
+ distance=3.7958766287746255,
17
+ azimuth=89.75784013699234,
18
+ elevation=-15.177406642875091,
19
+ ),
20
+ 2: dict(
21
+ lookat=[3.02344359, -1.48874618, 1.2412914],
22
+ distance=3.6684844368165512,
23
+ azimuth=51.67880851867874,
24
+ elevation=-13.302619131542388,
25
+ ),
26
+ # 3: dict(
27
+ # lookat=[11.44842548, -11.47664723, 11.24115989],
28
+ # distance=43.923271794728187,
29
+ # azimuth=227.12928449329333,
30
+ # elevation=-16.495686334624907,
31
+ # ),
32
+ 4: dict(
33
+ lookat=[1.6, -1.0, 1.0],
34
+ distance=5,
35
+ azimuth=89.70301806083651,
36
+ elevation=-18.02177994296577,
37
+ ),
38
+ }
39
+
40
+ DEFAULT_LAYOUT_CAM = {
41
+ "lookat": [2.25, -1, 1.05312667],
42
+ "distance": 5,
43
+ "azimuth": 89.70301806083651,
44
+ "elevation": -18.02177994296577,
45
+ }
46
+
47
+ CAM_CONFIGS = dict(
48
+ robot0_agentview_center=dict(
49
+ pos=[-0.6, 0.0, 1.15],
50
+ quat=[
51
+ 0.636945903301239,
52
+ 0.3325185477733612,
53
+ -0.3199238181114197,
54
+ -0.6175596117973328,
55
+ ],
56
+ parent_body="mobilebase0_support",
57
+ ),
58
+ robot0_agentview_left=dict(
59
+ pos=[-0.5, 0.35, 1.05],
60
+ quat=[0.55623853, 0.29935253, -0.37678665, -0.6775092],
61
+ camera_attribs=dict(fovy="60"),
62
+ parent_body="mobilebase0_support",
63
+ ),
64
+ robot0_agentview_right=dict(
65
+ pos=[-0.5, -0.35, 1.05],
66
+ quat=[
67
+ 0.6775091886520386,
68
+ 0.3767866790294647,
69
+ -0.2993525564670563,
70
+ -0.55623859167099,
71
+ ],
72
+ camera_attribs=dict(fovy="60"),
73
+ parent_body="mobilebase0_support",
74
+ ),
75
+ robot0_frontview=dict(
76
+ pos=[-0.50, 0, 0.95],
77
+ quat=[
78
+ 0.6088936924934387,
79
+ 0.3814677894115448,
80
+ -0.3673907518386841,
81
+ -0.5905545353889465,
82
+ ],
83
+ camera_attribs=dict(fovy="60"),
84
+ parent_body="mobilebase0_support",
85
+ ),
86
+ robot0_eye_in_hand=dict(
87
+ pos=[0.05, 0, 0],
88
+ quat=[0, 0.707107, 0.707107, 0],
89
+ parent_body="robot0_right_hand",
90
+ ),
91
+ )
third_party/robocasa/robocasa/utils/config_utils.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import os
3
+ import pathlib
4
+ import robosuite
5
+ from robosuite.controllers import load_composite_controller_config
6
+
7
+
8
+ def is_stale_controller_config(config: dict):
9
+ """
10
+ Checks if a controller config is in the format from robosuite versions <= 1.4.1.
11
+ Does not check for config validity, only the format type.
12
+ Args:
13
+ config (dict): Controller configuration
14
+ Returns:
15
+ bool: True if the config is in the old format, False otherwise
16
+ """
17
+
18
+ OLD_CONTROLLER_TYPES = [
19
+ "JOINT_VELOCITY",
20
+ "JOINT_TORQUE",
21
+ "JOINT_POSITION",
22
+ "OSC_POSITION",
23
+ "OSC_POSE",
24
+ "IK_POSE",
25
+ ]
26
+ if (
27
+ "body_parts" not in config or "body_parts_controller_configs" not in config
28
+ ) and "type" in config:
29
+ return config["type"] in OLD_CONTROLLER_TYPES
30
+ return False
31
+
32
+
33
+ def refactor_composite_controller_config(controller_config, robot_type, arms):
34
+ """
35
+ Checks if a controller config is in the format from robosuite versions <= 1.4.1.
36
+ If this is the case, converts the controller config to the new composite controller
37
+ config format in robosuite versions >= 1.5. If the robot has a default
38
+ controller config use that and override the arms with the old controller config.
39
+ If not just use the old controller config for arms.
40
+ Args:
41
+ old_controller_config (dict): Old controller config
42
+ Returns:
43
+ dict: New controller config
44
+ """
45
+ if not is_stale_controller_config(controller_config):
46
+ return controller_config
47
+
48
+ config_dir = pathlib.Path(robosuite.__file__).parent / "controllers/config/robots/"
49
+ name = robot_type.lower()
50
+ configs = os.listdir(config_dir)
51
+ if f"default_{name}.json" in configs:
52
+ new_controller_config = load_composite_controller_config(robot=name)
53
+ else:
54
+ new_controller_config = {}
55
+ new_controller_config["type"] = "BASIC"
56
+ new_controller_config["body_parts"] = {}
57
+
58
+ for arm in arms:
59
+ new_arm_config = copy.deepcopy(controller_config)
60
+ if "gripper" not in new_arm_config:
61
+ new_arm_config["gripper"] = {"type": "GRIP"}
62
+ new_controller_config["body_parts"][arm] = new_arm_config
63
+ return new_controller_config
third_party/robocasa/robocasa/utils/cotrain_utils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Utility functions and constants for co-training with real robot.
3
+ """
4
+ from robosuite.models.robots.manipulators.gr1_robot import GR1
5
+
6
+ # Initial pose configuration for co-training with real robot
7
+ COTRAIN_REAL_MATCHED_ROBOT_INITIAL_POSE = {
8
+ GR1: {
9
+ "robot0_r_shoulder_pitch": -0.22963779,
10
+ "robot0_r_shoulder_roll": -0.38363408,
11
+ "robot0_r_shoulder_yaw": 0.14360377,
12
+ "robot0_r_elbow_pitch": -1.5289252,
13
+ "robot0_r_wrist_yaw": -0.2897802,
14
+ "robot0_r_wrist_roll": -0.07134621,
15
+ "robot0_r_wrist_pitch": -0.04550289,
16
+ "robot0_l_shoulder_pitch": -0.10933163,
17
+ "robot0_l_shoulder_roll": 0.43292055,
18
+ "robot0_l_shoulder_yaw": -0.15983289,
19
+ "robot0_l_elbow_pitch": -1.48233023,
20
+ "robot0_l_wrist_yaw": 0.2359135,
21
+ "robot0_l_wrist_roll": 0.26184522,
22
+ "robot0_l_wrist_pitch": 0.00830735,
23
+ }
24
+ }
third_party/robocasa/robocasa/utils/dexmg_utils.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class DexMGConfigHelper:
2
+ """
3
+ Helper class for multi-inheritance scenarios, specifically designed to support task configuration
4
+ and environment interaction in robotic manipulation tasks.
5
+
6
+ Example Usage:
7
+ This class is intended to be used in multi-inheritance cases such as:
8
+ class PnPCounterToSink(Kitchen, DexMGConfigHelper)
9
+ which will automatically generate a new configuration class:
10
+ class PnPCounterToSink_Config(MG_Config)
11
+
12
+ Behavior:
13
+ 1. In the implementation of the MG_RoboSuiteHumanoidGeneric class:
14
+ - `self.env` will be an instance of PnPCounterToSink, enabling access to:
15
+ - `self.env.get_object()` to retrieve key objects.
16
+ - `self.env.get_subtask_term_signals()` to obtain signal information.
17
+ 2. In the implementation of PnPCounterToSink_Config:
18
+ - `self.task_config()` delegates to `PnPCounterToSink.task_config`, which defines
19
+ subtask divisions based on objects and signals.
20
+
21
+ Attributes:
22
+ subclasses (list): A list storing tuples of subclass names and their respective classes.
23
+ """
24
+
25
+ class AttrDict(dict):
26
+ def __getattr__(self, key):
27
+ if key not in self:
28
+ self[
29
+ key
30
+ ] = (
31
+ DexMGConfigHelper.AttrDict()
32
+ ) # Create a new AttrDict if key doesn't exist
33
+ return self[key]
34
+
35
+ def __setattr__(self, key, value):
36
+ self[key] = value
37
+
38
+ def to_dict(self):
39
+ """Recursively converts AttrDict to a normal dictionary"""
40
+ return {
41
+ key: (
42
+ value.to_dict()
43
+ if isinstance(value, DexMGConfigHelper.AttrDict)
44
+ else value
45
+ )
46
+ for key, value in self.items()
47
+ }
48
+
49
+ subclasses = []
50
+
51
+ def __init_subclass__(cls, **kwargs):
52
+ """
53
+ Automatically registers each subclass of DexMGConfigHelper.
54
+
55
+ Args:
56
+ cls: The subclass being registered.
57
+ kwargs: Additional keyword arguments.
58
+ """
59
+ super().__init_subclass__(**kwargs)
60
+ DexMGConfigHelper.subclasses.append((cls.__name__, cls))
61
+
62
+ def __init__(self):
63
+ """
64
+ Initialize a DexMGConfigHelper instance.
65
+ Note: This is an abstract class and should not be instantiated directly.
66
+ """
67
+ pass
68
+
69
+ # Misc functions copied from dexmimicgen.mimicgen.env_interfaces.robosuite_humanoid
70
+ def get_grippers(self):
71
+ """
72
+ Get grippers for the environment.
73
+ """
74
+ return self.robots[0].gripper["right"], self.robots[0].gripper["left"]
75
+
76
+ def get_object(self):
77
+ """
78
+ Retrieve a key object required for the task.
79
+ This method must be implemented in subclasses.
80
+
81
+ Raises:
82
+ NotImplementedError: If the method is not overridden in a subclass.
83
+ """
84
+ raise NotImplementedError
85
+
86
+ def get_subtask_term_signals(self):
87
+ """
88
+ Retrieve signals used to define subtask termination conditions.
89
+ This method must be implemented in subclasses.
90
+
91
+ Raises:
92
+ NotImplementedError: If the method is not overridden in a subclass.
93
+ """
94
+ raise NotImplementedError
95
+
96
+ @staticmethod
97
+ def task_config():
98
+ """
99
+ Define the configuration for dividing a task into subtasks.
100
+ This method must be implemented in subclasses.
101
+
102
+ Raises:
103
+ NotImplementedError: If the method is not overridden in a subclass.
104
+ """
105
+ raise NotImplementedError
third_party/robocasa/robocasa/utils/gym_utils/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .gymnasium_basic import RoboCasaEnv # noqa: F401
2
+ from .gymnasium_groot import GrootRoboCasaEnv # noqa: F401
3
+
4
+ # from .gymnasium_gearbc import GearBCRoboCasaEnv # noqa: F401
third_party/robocasa/robocasa/utils/gym_utils/gymnasium_basic.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime, uuid
2
+ from copy import deepcopy
3
+ import gymnasium as gym
4
+ import numpy as np
5
+ import os
6
+ import robocasa # we need this to register environments # noqa: F401
7
+ import robosuite
8
+ from gymnasium import spaces
9
+ from robocasa.environments.tabletop.tabletop import Tabletop
10
+ from robocasa.models.robots import (
11
+ GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY,
12
+ GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST,
13
+ GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY,
14
+ gather_robot_observations,
15
+ make_key_converter,
16
+ )
17
+ from robosuite.controllers import load_composite_controller_config
18
+ from robosuite.controllers.parts.arm.osc import OperationalSpaceController
19
+ from robosuite.controllers.composite.composite_controller import HybridMobileBase
20
+ from robosuite.environments.base import REGISTERED_ENVS
21
+
22
+
23
+ ALLOWED_LANGUAGE_CHARSET = (
24
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:"
25
+ )
26
+
27
+
28
+ def create_env_robosuite(
29
+ env_name,
30
+ # robosuite-related configs
31
+ robots="PandaOmron",
32
+ controller_configs=None,
33
+ camera_names=[
34
+ "egoview",
35
+ "robot0_eye_in_left_hand",
36
+ "robot0_eye_in_right_hand",
37
+ ],
38
+ camera_widths=128,
39
+ camera_heights=128,
40
+ enable_render=True,
41
+ seed=None,
42
+ # robocasa-related configs
43
+ obj_instance_split=None,
44
+ generative_textures=None,
45
+ randomize_cameras=False,
46
+ layout_and_style_ids=None,
47
+ layout_ids=None,
48
+ style_ids=None,
49
+ ):
50
+ if controller_configs is None:
51
+ controller_configs = load_composite_controller_config(
52
+ controller=None,
53
+ robot=robots if isinstance(robots, str) else robots[0],
54
+ )
55
+ env_kwargs = dict(
56
+ env_name=env_name,
57
+ robots=robots,
58
+ controller_configs=controller_configs,
59
+ camera_names=camera_names,
60
+ camera_widths=camera_widths,
61
+ camera_heights=camera_heights,
62
+ has_renderer=False,
63
+ has_offscreen_renderer=enable_render,
64
+ ignore_done=True,
65
+ use_object_obs=True,
66
+ use_camera_obs=enable_render,
67
+ camera_depths=False,
68
+ seed=seed,
69
+ translucent_robot=False,
70
+ )
71
+ env_class = REGISTERED_ENVS[env_name]
72
+
73
+ env = robosuite.make(**env_kwargs)
74
+ return env, env_kwargs
75
+
76
+
77
+ class RoboCasaEnv(gym.Env):
78
+ def __init__(
79
+ self,
80
+ env_name=None,
81
+ robots_name=None,
82
+ camera_names=None,
83
+ camera_widths=None,
84
+ camera_heights=None,
85
+ enable_render=True,
86
+ dump_rollout_dataset_dir=None,
87
+ **kwargs, # Accept additional kwargs
88
+ ):
89
+ self.key_converter = make_key_converter(robots_name)
90
+ (
91
+ _,
92
+ camera_names,
93
+ default_camera_widths,
94
+ default_camera_heights,
95
+ ) = self.key_converter.get_camera_config()
96
+
97
+ if camera_widths is None:
98
+ camera_widths = default_camera_widths
99
+ if camera_heights is None:
100
+ camera_heights = default_camera_heights
101
+
102
+ controller_configs = load_composite_controller_config(
103
+ controller=None,
104
+ robot=robots_name.split("_")[0],
105
+ )
106
+ if (
107
+ robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_ONLY
108
+ or robots_name in GROOT_ROBOCASA_ENVS_GR1_ARMS_AND_WAIST
109
+ or robots_name in GROOT_ROBOCASA_ENVS_GR1_FIXED_LOWER_BODY
110
+ ):
111
+ controller_configs["type"] = "BASIC"
112
+ controller_configs["composite_controller_specific_configs"] = {}
113
+ controller_configs["control_delta"] = False
114
+
115
+ self.env, self.env_kwargs = create_env_robosuite(
116
+ env_name=env_name,
117
+ robots=robots_name.split("_"),
118
+ controller_configs=controller_configs,
119
+ camera_names=camera_names,
120
+ camera_widths=camera_widths,
121
+ camera_heights=camera_heights,
122
+ enable_render=enable_render,
123
+ **kwargs, # Forward kwargs to create_env_robosuite
124
+ )
125
+
126
+ # TODO: the following info should be output by grootrobocasa
127
+ self.camera_names = camera_names
128
+ self.camera_widths = camera_widths
129
+ self.camera_heights = camera_heights
130
+ self.enable_render = enable_render
131
+ self.render_obs_key = f"{camera_names[0]}_image"
132
+ self.render_cache = None
133
+
134
+ # setup spaces
135
+ action_space = spaces.Dict()
136
+ for robot in self.env.robots:
137
+ cc = robot.composite_controller
138
+ pf = robot.robot_model.naming_prefix
139
+ for part_name, controller in cc.part_controllers.items():
140
+ min_value, max_value = -1, 1
141
+ start_idx, end_idx = cc._action_split_indexes[part_name]
142
+ shape = [end_idx - start_idx]
143
+ this_space = spaces.Box(
144
+ low=min_value, high=max_value, shape=shape, dtype=np.float32
145
+ )
146
+ action_space[f"{pf}{part_name}"] = this_space
147
+ if isinstance(cc, HybridMobileBase):
148
+ this_space = spaces.Discrete(2)
149
+ action_space[f"{pf}base_mode"] = this_space
150
+
151
+ action_space = spaces.Dict(action_space)
152
+ self.action_space = action_space
153
+
154
+ obs = (
155
+ self.env.viewer._get_observations(force_update=True)
156
+ if self.env.viewer_get_obs
157
+ else self.env._get_observations(force_update=True)
158
+ )
159
+ obs.update(gather_robot_observations(self.env))
160
+ observation_space = spaces.Dict()
161
+ for obs_name, obs_value in obs.items():
162
+ shape = list(obs_value.shape)
163
+ if obs_name.endswith("_image"):
164
+ continue
165
+ min_value, max_value = -1, 1
166
+ this_space = spaces.Box(
167
+ low=min_value, high=max_value, shape=shape, dtype=np.float32
168
+ )
169
+ observation_space[obs_name] = this_space
170
+
171
+ for camera_name in camera_names:
172
+ shape = [camera_heights, camera_widths, 3]
173
+ this_space = spaces.Box(low=0, high=255, shape=shape, dtype=np.uint8)
174
+ observation_space[f"{camera_name}_image"] = this_space
175
+
176
+ observation_space["language"] = spaces.Text(
177
+ max_length=256, charset=ALLOWED_LANGUAGE_CHARSET
178
+ )
179
+
180
+ self.observation_space = observation_space
181
+
182
+ self.dump_rollout_dataset_dir = dump_rollout_dataset_dir
183
+ self.groot_exporter = None
184
+ self.np_exporter = None
185
+
186
+ def get_basic_observation(self, raw_obs):
187
+ raw_obs.update(gather_robot_observations(self.env))
188
+
189
+ # Image are in (H, W, C), flip it upside down
190
+ def process_img(img):
191
+ return np.copy(img[::-1, :, :])
192
+
193
+ for obs_name, obs_value in raw_obs.items():
194
+ if obs_name.endswith("_image"):
195
+ # image observations
196
+ raw_obs[obs_name] = process_img(obs_value)
197
+ else:
198
+ # non-image observations
199
+ raw_obs[obs_name] = obs_value.astype(np.float32)
200
+
201
+ # Return black image if rendering is disabled
202
+ if not self.enable_render:
203
+ for name in self.camera_names:
204
+ raw_obs[f"{name}_image"] = np.zeros(
205
+ (self.camera_heights, self.camera_widths, 3), dtype=np.uint8
206
+ )
207
+
208
+ self.render_cache = raw_obs[self.render_obs_key]
209
+ raw_obs["language"] = self.env.get_ep_meta().get("lang", "")
210
+
211
+ return raw_obs
212
+
213
+ def reset(self, seed=None, options=None):
214
+ np.random.seed(seed)
215
+ raw_obs = self.env.reset()
216
+ # return obs
217
+ obs = self.get_basic_observation(raw_obs)
218
+
219
+ info = {}
220
+ info["success"] = False
221
+ info["grasp_distractor_obj"] = False
222
+
223
+ return obs, info
224
+
225
+ def step(self, action_dict):
226
+ env_action = []
227
+ for robot in self.env.robots:
228
+ cc = robot.composite_controller
229
+ pf = robot.robot_model.naming_prefix
230
+ action = np.zeros(cc.action_limits[0].shape)
231
+ for part_name, controller in cc.part_controllers.items():
232
+ start_idx, end_idx = cc._action_split_indexes[part_name]
233
+ act = action_dict.pop(f"{pf}{part_name}")
234
+ action[start_idx:end_idx] = act
235
+ if isinstance(cc, HybridMobileBase):
236
+ action[-1] = action_dict.pop(f"{pf}base_mode")
237
+ env_action.append(action)
238
+
239
+ assert len(action_dict) == 0, f"Unprocessed actions: {action_dict}"
240
+ env_action = np.concatenate(env_action)
241
+
242
+ raw_obs, reward, done, info = self.env.step(env_action)
243
+
244
+ obs = self.get_basic_observation(raw_obs)
245
+
246
+ truncated = False
247
+
248
+ info["success"] = reward > 0
249
+ info["grasp_distractor_obj"] = False
250
+ if hasattr(self, "_check_grasp_distractor_obj"):
251
+ info["grasp_distractor_obj"] = self._check_grasp_distractor_obj()
252
+
253
+ return obs, reward, done, truncated, info
254
+
255
+ def render(self):
256
+ if self.render_cache is None:
257
+ raise RuntimeError("Must run reset or step before render.")
258
+ return self.render_cache
259
+
260
+ def close(self):
261
+ self.env.close()
third_party/robocasa/robocasa/utils/gym_utils/gymnasium_gearbc.py ADDED
@@ -0,0 +1,184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any, Dict
3
+
4
+ import cv2
5
+ import numpy as np
6
+ from gymnasium import spaces
7
+ from gymnasium.envs.registration import register
8
+
9
+ from robocasa.models.robots import GROOT_ROBOCASA_ENVS_ROBOTS
10
+ from .gymnasium_basic import (
11
+ REGISTERED_ENVS,
12
+ RoboCasaEnv,
13
+ )
14
+
15
+ ALLOWED_LANGUAGE_CHARSET = (
16
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:"
17
+ )
18
+ FINAL_IMAGE_RESOLUTION = (224, 224)
19
+
20
+
21
+ class GearBCRoboCasaEnv(RoboCasaEnv):
22
+ def __init__(self, *args, **kwargs):
23
+ super().__init__(*args, **kwargs)
24
+
25
+ temp_observation_space = self.key_converter.deduce_observation_space(self.env)
26
+ self.observation_space = spaces.Dict()
27
+ for k, v in temp_observation_space.items():
28
+ assert k.startswith("state.")
29
+ self.observation_space[k[6:] + "_state"] = v
30
+ mapped_names, camera_names, _, _ = self.key_converter.get_camera_config()
31
+ for camera_name in camera_names:
32
+ self.observation_space[camera_name + "_image"] = spaces.Box(
33
+ low=0, high=1, shape=(3, *FINAL_IMAGE_RESOLUTION), dtype=np.float32
34
+ )
35
+ # self.observation_space[
36
+ # "annotation.human.action.task_description"
37
+ # ] = spaces.Text(max_length=256, charset=ALLOWED_LANGUAGE_CHARSET)
38
+
39
+ temp_action_space = self.key_converter.deduce_action_space(self.env)
40
+ self.action_space = spaces.Dict()
41
+ for k, v in temp_action_space.items():
42
+ assert k.startswith("action.")
43
+ if isinstance(v, spaces.Box):
44
+ self.action_space[k[7:] + "_action"] = v
45
+ else:
46
+ self.action_space[k[7:] + "_action"] = spaces.Box(
47
+ low=-1, high=1, shape=(1,), dtype=np.float32
48
+ )
49
+
50
+ self.verbose = True
51
+ for k, v in self.observation_space.items():
52
+ self.verbose and print("{OBS}", k, v)
53
+ for k, v in self.action_space.items():
54
+ self.verbose and print("{ACTION}", k, v)
55
+
56
+ @staticmethod
57
+ def process_img(img):
58
+ h, w, _ = img.shape
59
+ if h != w:
60
+ dim = max(h, w)
61
+ y_offset = (dim - h) // 2
62
+ x_offset = (dim - w) // 2
63
+ img = np.pad(img, ((y_offset, y_offset), (x_offset, x_offset), (0, 0)))
64
+ h, w = dim, dim
65
+ if (h, w) != FINAL_IMAGE_RESOLUTION:
66
+ img = cv2.resize(img, FINAL_IMAGE_RESOLUTION, cv2.INTER_AREA)
67
+ # Convert from (H, W, C) to (C, H, W)
68
+ img = np.copy(
69
+ (np.transpose(img, (2, 0, 1)).astype(np.float32) / 255.0).clip(0.0, 1.0)
70
+ )
71
+ return np.copy(img)
72
+
73
+ def get_gearbc_observation(self, raw_obs):
74
+ obs = {}
75
+ temp_obs = self.key_converter.map_obs(raw_obs)
76
+ for k, v in temp_obs.items():
77
+ if k.startswith("hand.") or k.startswith("body."):
78
+ obs[k[5:] + "_state"] = v
79
+ else:
80
+ raise ValueError(f"Unknown key: {k}")
81
+ mapped_names, camera_names, _, _ = self.key_converter.get_camera_config()
82
+ for mapped_name, camera_name in zip(mapped_names, camera_names):
83
+ obs[camera_name + "_image"] = GearBCRoboCasaEnv.process_img(
84
+ raw_obs[camera_name + "_image"]
85
+ )
86
+ self.render_cache = np.copy(
87
+ (np.transpose(obs[self.render_obs_key], (1, 2, 0)) * 255.0).astype(np.uint8)
88
+ )
89
+ font = cv2.FONT_HERSHEY_SIMPLEX
90
+ font_scale = max(FINAL_IMAGE_RESOLUTION) / 1000
91
+ color = (255, 255, 0) # Yellow text
92
+ thickness = 1
93
+
94
+ # Split text into lines of max 50 characters
95
+ text = self.env.get_ep_meta().get("lang", "")
96
+ words = text.split()
97
+ lines = []
98
+ current_line = []
99
+ current_length = 0
100
+
101
+ for word in words:
102
+ if current_length + len(word) + 1 <= 50: # +1 for space
103
+ current_line.append(word)
104
+ current_length += len(word) + 1
105
+ else:
106
+ lines.append(" ".join(current_line))
107
+ current_line = [word]
108
+ current_length = len(word)
109
+ if current_line:
110
+ lines.append(" ".join(current_line))
111
+
112
+ # Draw each line
113
+ y_position = int(FINAL_IMAGE_RESOLUTION[0] * 0.9)
114
+ x_position = int(FINAL_IMAGE_RESOLUTION[1] * 0.1)
115
+ line_spacing = int(30 * font_scale) # Adjust spacing between lines
116
+
117
+ for line in lines:
118
+ cv2.putText(
119
+ self.render_cache,
120
+ line,
121
+ (x_position, y_position),
122
+ font,
123
+ font_scale,
124
+ color,
125
+ thickness,
126
+ cv2.LINE_AA,
127
+ )
128
+ y_position += line_spacing # Move down for next line
129
+
130
+ # obs["annotation.human.action.task_description"] = raw_obs["language"]
131
+ return obs
132
+
133
+ def reset(self, seed=None, options=None):
134
+ raw_obs, info = super().reset(seed=seed, options=options)
135
+ obs = self.get_gearbc_observation(raw_obs)
136
+ return obs, info
137
+
138
+ def step(self, action):
139
+ temp_action = action.copy()
140
+ action = {}
141
+ for k, v in temp_action.items():
142
+ assert k.endswith("_action")
143
+ action["action." + k[:-7]] = v
144
+ for k, v in action.items():
145
+ self.verbose and print("<ACTION>", k, v)
146
+
147
+ action = self.key_converter.unmap_action(action)
148
+ raw_obs, reward, terminated, truncated, info = super().step(action)
149
+ obs = self.get_gearbc_observation(raw_obs)
150
+
151
+ for k, v in obs.items():
152
+ self.verbose and print("<OBS>", k, v.shape if k.endswith("image") else v)
153
+ self.verbose = False
154
+
155
+ return obs, reward, terminated, truncated, info
156
+
157
+
158
+ def create_gearbcrobocasa_env_class(env, robot, robot_alias):
159
+ class_name = f"{env}_{robot}_Env"
160
+ id_name = f"gearbc/{class_name}"
161
+
162
+ env_class_type = type(
163
+ class_name,
164
+ (GearBCRoboCasaEnv,),
165
+ {
166
+ "__init__": lambda self, **kwargs: super(self.__class__, self).__init__(
167
+ env_name=env,
168
+ robots_name=robot,
169
+ **kwargs,
170
+ )
171
+ },
172
+ )
173
+
174
+ current_module = sys.modules["robocasa.utils.gym_utils.gymnasium_gearbc"]
175
+ setattr(current_module, class_name, env_class_type)
176
+ register(
177
+ id=id_name, # Unique ID for the environment
178
+ entry_point=f"robocasa.utils.gym_utils.gymnasium_gearbc:{class_name}", # Path to your environment class
179
+ )
180
+
181
+
182
+ for ENV in REGISTERED_ENVS:
183
+ for ROBOT, ROBOT_ALIAS in GROOT_ROBOCASA_ENVS_ROBOTS.items():
184
+ create_gearbcrobocasa_env_class(ENV, ROBOT, ROBOT_ALIAS)
third_party/robocasa/robocasa/utils/gym_utils/gymnasium_groot.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from typing import Any, Dict
3
+
4
+ import cv2
5
+ import numpy as np
6
+ from gymnasium import spaces
7
+ from gymnasium.envs.registration import register
8
+
9
+ from robocasa.models.robots import GROOT_ROBOCASA_ENVS_ROBOTS
10
+ from robocasa.models.robots.manipulators.gr1_robot import GR1ArmsOnly, GR1ArmsAndWaist
11
+ from .gymnasium_basic import (
12
+ REGISTERED_ENVS,
13
+ RoboCasaEnv,
14
+ )
15
+
16
+ ALLOWED_LANGUAGE_CHARSET = (
17
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ,.\n\t[]{}()!?'_:"
18
+ )
19
+ FINAL_IMAGE_RESOLUTION = (256, 256)
20
+
21
+
22
+ class GrootRoboCasaEnv(RoboCasaEnv):
23
+ def __init__(self, *args, **kwargs):
24
+ super().__init__(*args, **kwargs)
25
+ self.observation_space = self.key_converter.deduce_observation_space(self.env)
26
+ mapped_names, _, _, _ = self.key_converter.get_camera_config()
27
+ for mapped_name in mapped_names:
28
+ self.observation_space[mapped_name] = spaces.Box(
29
+ low=0, high=255, shape=(*FINAL_IMAGE_RESOLUTION, 3), dtype=np.uint8
30
+ )
31
+ if mapped_name == "video.ego_view_pad_res256_freq20":
32
+ self.observation_space[
33
+ "video.ego_view_bg_crop_pad_res256_freq20"
34
+ ] = spaces.Box(
35
+ low=0, high=255, shape=(*FINAL_IMAGE_RESOLUTION, 3), dtype=np.uint8
36
+ )
37
+ if isinstance(self.env.robots[0].robot_model, GR1ArmsOnly):
38
+ self.observation_space["annotation.human.coarse_action"] = spaces.Text(
39
+ max_length=256, charset=ALLOWED_LANGUAGE_CHARSET
40
+ )
41
+ elif isinstance(self.env.robots[0].robot_model, GR1ArmsAndWaist):
42
+ self.observation_space["annotation.human.coarse_action"] = spaces.Text(
43
+ max_length=256, charset=ALLOWED_LANGUAGE_CHARSET
44
+ )
45
+ else:
46
+ self.observation_space[
47
+ "annotation.human.action.task_description"
48
+ ] = spaces.Text(max_length=256, charset=ALLOWED_LANGUAGE_CHARSET)
49
+ self.action_space = self.key_converter.deduce_action_space(self.env)
50
+
51
+ self.verbose = False
52
+ for k, v in self.observation_space.items():
53
+ self.verbose and print("{OBS}", k, v)
54
+ for k, v in self.action_space.items():
55
+ self.verbose and print("{ACTION}", k, v)
56
+
57
+ @staticmethod
58
+ def process_img(img):
59
+ h, w, _ = img.shape
60
+ if h != w:
61
+ dim = max(h, w)
62
+ y_offset = (dim - h) // 2
63
+ x_offset = (dim - w) // 2
64
+ img = np.pad(img, ((y_offset, y_offset), (x_offset, x_offset), (0, 0)))
65
+ h, w = dim, dim
66
+ if (h, w) != FINAL_IMAGE_RESOLUTION:
67
+ img = cv2.resize(img, FINAL_IMAGE_RESOLUTION, cv2.INTER_AREA)
68
+ return np.copy(img)
69
+
70
+ @staticmethod
71
+ def process_img_cotrain(img):
72
+ assert img.shape[0] == 800 and img.shape[1] == 1280
73
+
74
+ oh, ow = 256, 256
75
+ crop = (310, 770, 110, 1130)
76
+ img = img[crop[0] : crop[1], crop[2] : crop[3]]
77
+
78
+ img_resized = cv2.resize(img, (720, 480), cv2.INTER_AREA)
79
+ width_pad = (img_resized.shape[1] - img_resized.shape[0]) // 2
80
+ img_pad = np.pad(
81
+ img_resized,
82
+ ((width_pad, width_pad), (0, 0), (0, 0)),
83
+ mode="constant",
84
+ constant_values=0,
85
+ )
86
+ img_resized = cv2.resize(img_pad, (oh, ow), cv2.INTER_AREA)
87
+ return img_resized
88
+
89
+ def get_groot_observation(self, raw_obs):
90
+ obs = {}
91
+ temp_obs = self.key_converter.map_obs(raw_obs)
92
+ for k, v in temp_obs.items():
93
+ if k.startswith("hand.") or k.startswith("body."):
94
+ obs["state." + k[5:]] = v
95
+ else:
96
+ raise ValueError(f"Unknown key: {k}")
97
+ mapped_names, camera_names, _, _ = self.key_converter.get_camera_config()
98
+ for mapped_name, camera_name in zip(mapped_names, camera_names):
99
+ obs[mapped_name] = GrootRoboCasaEnv.process_img(
100
+ raw_obs[camera_name + "_image"]
101
+ )
102
+ if mapped_name == "video.ego_view_pad_res256_freq20":
103
+ obs[
104
+ "video.ego_view_bg_crop_pad_res256_freq20"
105
+ ] = GrootRoboCasaEnv.process_img_cotrain(
106
+ raw_obs[camera_name + "_image"]
107
+ )
108
+ if isinstance(self.env.robots[0].robot_model, GR1ArmsOnly):
109
+ obs[
110
+ "annotation.human.coarse_action"
111
+ ] = f"locked_waist: {raw_obs['language']}"
112
+ elif isinstance(self.env.robots[0].robot_model, GR1ArmsAndWaist):
113
+ obs[
114
+ "annotation.human.coarse_action"
115
+ ] = f"unlocked_waist: {raw_obs['language']}"
116
+ else:
117
+ obs["annotation.human.action.task_description"] = raw_obs["language"]
118
+ return obs
119
+
120
+ def reset(self, seed=None, options=None):
121
+ raw_obs, info = super().reset(seed=seed, options=options)
122
+ obs = self.get_groot_observation(raw_obs)
123
+ return obs, info
124
+
125
+ def step(self, action):
126
+ for k, v in action.items():
127
+ self.verbose and print("<ACTION>", k, v)
128
+
129
+ action = self.key_converter.unmap_action(action)
130
+ raw_obs, reward, terminated, truncated, info = super().step(action)
131
+ obs = self.get_groot_observation(raw_obs)
132
+
133
+ for k, v in obs.items():
134
+ self.verbose and print("<OBS>", k, v.shape if k.startswith("video.") else v)
135
+ self.verbose = False
136
+
137
+ return obs, reward, terminated, truncated, info
138
+
139
+
140
+ def create_grootrobocasa_env_class(env, robot, robot_alias):
141
+ class_name = f"{env}_{robot}_Env"
142
+ id_name = f"robocasa_{robot_alias}/{class_name}"
143
+
144
+ env_class_type = type(
145
+ class_name,
146
+ (GrootRoboCasaEnv,),
147
+ {
148
+ "__init__": lambda self, **kwargs: super(self.__class__, self).__init__(
149
+ env_name=env,
150
+ robots_name=robot,
151
+ **kwargs,
152
+ )
153
+ },
154
+ )
155
+
156
+ current_module = sys.modules["robocasa.utils.gym_utils.gymnasium_groot"]
157
+ setattr(current_module, class_name, env_class_type)
158
+ register(
159
+ id=id_name, # Unique ID for the environment
160
+ entry_point=f"robocasa.utils.gym_utils.gymnasium_groot:{class_name}", # Path to your environment class
161
+ )
162
+
163
+ if robot_alias == "gr1_arms_waist_fourier_hands":
164
+ id_name = f"gr1_unified/{class_name}"
165
+ register(
166
+ id=id_name, # Unique ID for the environment
167
+ entry_point=f"robocasa.utils.gym_utils.gymnasium_groot:{class_name}", # Path to your environment class
168
+ )
169
+
170
+
171
+ for ENV in REGISTERED_ENVS:
172
+ for ROBOT, ROBOT_ALIAS in GROOT_ROBOCASA_ENVS_ROBOTS.items():
173
+ create_grootrobocasa_env_class(ENV, ROBOT, ROBOT_ALIAS)