introvoyz041 commited on
Commit
fcbd215
·
verified ·
1 Parent(s): e0e74da

Migrated from GitHub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +170 -0
  2. data/AUTHORS +7 -0
  3. data/CONTRIBUTING.md +23 -0
  4. data/LICENSE +202 -0
  5. data/README.md +138 -0
  6. data/dm_control/__init__.py +14 -0
  7. data/dm_control/_render/__init__.py +109 -0
  8. data/dm_control/_render/base.py +166 -0
  9. data/dm_control/_render/base_test.py +162 -0
  10. data/dm_control/_render/constants.py +33 -0
  11. data/dm_control/_render/executor/__init__.py +51 -0
  12. data/dm_control/_render/executor/render_executor.py +218 -0
  13. data/dm_control/_render/executor/render_executor_test.py +205 -0
  14. data/dm_control/_render/glfw_renderer.py +68 -0
  15. data/dm_control/_render/glfw_renderer_test.py +68 -0
  16. data/dm_control/_render/pyopengl/__init__.py +14 -0
  17. data/dm_control/_render/pyopengl/egl_ext.py +74 -0
  18. data/dm_control/_render/pyopengl/egl_renderer.py +140 -0
  19. data/dm_control/_render/pyopengl/osmesa_renderer.py +86 -0
  20. data/dm_control/_render/pyopengl/osmesa_renderer_test.py +70 -0
  21. data/dm_control/autowrap/__init__.py +15 -0
  22. data/dm_control/autowrap/autowrap.py +126 -0
  23. data/dm_control/autowrap/binding_generator.py +296 -0
  24. data/dm_control/autowrap/codegen_util.py +119 -0
  25. data/dm_control/autowrap/header_parsing.py +335 -0
  26. data/dm_control/blender/fake_core/bpy.py +229 -0
  27. data/dm_control/blender/fake_core/mathutils.py +123 -0
  28. data/dm_control/blender/mujoco_exporter/README.md +213 -0
  29. data/dm_control/blender/mujoco_exporter/__init__.py +170 -0
  30. data/dm_control/blender/mujoco_exporter/blender_scene.py +428 -0
  31. data/dm_control/blender/mujoco_exporter/blender_scene_test.py +244 -0
  32. data/dm_control/blender/mujoco_exporter/doc/add_ik_constraint.png +3 -0
  33. data/dm_control/blender/mujoco_exporter/doc/convhull_blend.png +3 -0
  34. data/dm_control/blender/mujoco_exporter/doc/convhull_mj_hull.png +3 -0
  35. data/dm_control/blender/mujoco_exporter/doc/convhull_mj_rend.png +3 -0
  36. data/dm_control/blender/mujoco_exporter/doc/enable_plugin.png +3 -0
  37. data/dm_control/blender/mujoco_exporter/doc/end_effector_selection.png +3 -0
  38. data/dm_control/blender/mujoco_exporter/doc/gizmo.png +3 -0
  39. data/dm_control/blender/mujoco_exporter/doc/ik_chain_length.png +3 -0
  40. data/dm_control/blender/mujoco_exporter/doc/ik_target.png +3 -0
  41. data/dm_control/blender/mujoco_exporter/doc/install_plugin.png +3 -0
  42. data/dm_control/blender/mujoco_exporter/doc/limits.png +3 -0
  43. data/dm_control/blender/mujoco_exporter/install.sh +13 -0
  44. data/dm_control/blender/mujoco_exporter/mujoco_assets.py +175 -0
  45. data/dm_control/blender/mujoco_exporter/mujoco_assets_test.py +225 -0
  46. data/dm_control/blender/mujoco_exporter/mujoco_scene.py +188 -0
  47. data/dm_control/blender/mujoco_exporter/mujoco_scene_test.py +195 -0
  48. data/dm_control/blender/mujoco_exporter/testing.py +198 -0
  49. data/dm_control/composer/__init__.py +33 -0
  50. data/dm_control/composer/arena.py +70 -0
.gitattributes CHANGED
@@ -58,3 +58,173 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/dm_control/locomotion/soccer/assets/humanoid/jersey.skn filter=lfs diff=lfs merge=lfs -text
62
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/abdomen_1_body.msh filter=lfs diff=lfs merge=lfs -text
63
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/abdomen_8_body.msh filter=lfs diff=lfs merge=lfs -text
64
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_left_black.msh filter=lfs diff=lfs merge=lfs -text
65
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_left_body.msh filter=lfs diff=lfs merge=lfs -text
66
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_right_black.msh filter=lfs diff=lfs merge=lfs -text
67
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/antenna_right_body.msh filter=lfs diff=lfs merge=lfs -text
68
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
69
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
70
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
71
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
72
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
73
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/coxa_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
74
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
75
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
76
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
77
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
78
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
79
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/femur_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
80
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haltere_left_body.msh filter=lfs diff=lfs merge=lfs -text
81
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haltere_right_body.msh filter=lfs diff=lfs merge=lfs -text
82
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haustellum_black.msh filter=lfs diff=lfs merge=lfs -text
83
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/haustellum_body.msh filter=lfs diff=lfs merge=lfs -text
84
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_black.msh filter=lfs diff=lfs merge=lfs -text
85
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_body.msh filter=lfs diff=lfs merge=lfs -text
86
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_ocelli.msh filter=lfs diff=lfs merge=lfs -text
87
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/head_red.msh filter=lfs diff=lfs merge=lfs -text
88
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/labrum_left_lower.msh filter=lfs diff=lfs merge=lfs -text
89
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/labrum_right_lower.msh filter=lfs diff=lfs merge=lfs -text
90
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/rostrum_body.msh filter=lfs diff=lfs merge=lfs -text
91
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/rostrum_bristle-brown.msh filter=lfs diff=lfs merge=lfs -text
92
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T1_left_brown.msh filter=lfs diff=lfs merge=lfs -text
93
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T1_right_brown.msh filter=lfs diff=lfs merge=lfs -text
94
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T2_left_brown.msh filter=lfs diff=lfs merge=lfs -text
95
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T2_right_brown.msh filter=lfs diff=lfs merge=lfs -text
96
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T3_left_brown.msh filter=lfs diff=lfs merge=lfs -text
97
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsal_claw_T3_right_brown.msh filter=lfs diff=lfs merge=lfs -text
98
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T2_1_left_body.msh filter=lfs diff=lfs merge=lfs -text
99
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T2_1_right_body.msh filter=lfs diff=lfs merge=lfs -text
100
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T3_1_left_body.msh filter=lfs diff=lfs merge=lfs -text
101
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tarsus_T3_1_right_body.msh filter=lfs diff=lfs merge=lfs -text
102
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/thorax_black.msh filter=lfs diff=lfs merge=lfs -text
103
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/thorax_body.msh filter=lfs diff=lfs merge=lfs -text
104
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
105
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
106
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
107
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
108
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
109
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/tibia_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
110
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/wing_left_brown.msh filter=lfs diff=lfs merge=lfs -text
111
+ data/dm_control/locomotion/walkers/assets/build_fruitfly/assets/wing_right_brown.msh filter=lfs diff=lfs merge=lfs -text
112
+ data/dm_control/locomotion/walkers/assets/dog_v2/dog_skin.skn filter=lfs diff=lfs merge=lfs -text
113
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/abdomen_1_body.msh filter=lfs diff=lfs merge=lfs -text
114
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/abdomen_8_body.msh filter=lfs diff=lfs merge=lfs -text
115
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_left_black.msh filter=lfs diff=lfs merge=lfs -text
116
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_left_body.msh filter=lfs diff=lfs merge=lfs -text
117
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_right_black.msh filter=lfs diff=lfs merge=lfs -text
118
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/antenna_right_body.msh filter=lfs diff=lfs merge=lfs -text
119
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/blender_model/drosophila_v2.blend filter=lfs diff=lfs merge=lfs -text
120
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
121
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
122
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
123
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
124
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
125
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/coxa_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
126
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
127
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
128
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
129
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
130
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
131
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/femur_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
132
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/haltere_left_body.msh filter=lfs diff=lfs merge=lfs -text
133
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/haltere_right_body.msh filter=lfs diff=lfs merge=lfs -text
134
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/haustellum_black.msh filter=lfs diff=lfs merge=lfs -text
135
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/haustellum_body.msh filter=lfs diff=lfs merge=lfs -text
136
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/head_black.msh filter=lfs diff=lfs merge=lfs -text
137
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/head_body.msh filter=lfs diff=lfs merge=lfs -text
138
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/head_ocelli.msh filter=lfs diff=lfs merge=lfs -text
139
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/head_red.msh filter=lfs diff=lfs merge=lfs -text
140
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/labrum_left_lower.msh filter=lfs diff=lfs merge=lfs -text
141
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/labrum_right_lower.msh filter=lfs diff=lfs merge=lfs -text
142
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/rostrum_body.msh filter=lfs diff=lfs merge=lfs -text
143
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/rostrum_bristle-brown.msh filter=lfs diff=lfs merge=lfs -text
144
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T1_left_brown.msh filter=lfs diff=lfs merge=lfs -text
145
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T1_right_brown.msh filter=lfs diff=lfs merge=lfs -text
146
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T2_left_brown.msh filter=lfs diff=lfs merge=lfs -text
147
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T2_right_brown.msh filter=lfs diff=lfs merge=lfs -text
148
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T3_left_brown.msh filter=lfs diff=lfs merge=lfs -text
149
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsal_claw_T3_right_brown.msh filter=lfs diff=lfs merge=lfs -text
150
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T2_1_left_body.msh filter=lfs diff=lfs merge=lfs -text
151
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T2_1_right_body.msh filter=lfs diff=lfs merge=lfs -text
152
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T3_1_left_body.msh filter=lfs diff=lfs merge=lfs -text
153
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tarsus_T3_1_right_body.msh filter=lfs diff=lfs merge=lfs -text
154
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/thorax_black.msh filter=lfs diff=lfs merge=lfs -text
155
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/thorax_body.msh filter=lfs diff=lfs merge=lfs -text
156
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T1_left_body.msh filter=lfs diff=lfs merge=lfs -text
157
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T1_right_body.msh filter=lfs diff=lfs merge=lfs -text
158
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T2_left_body.msh filter=lfs diff=lfs merge=lfs -text
159
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T2_right_body.msh filter=lfs diff=lfs merge=lfs -text
160
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T3_left_body.msh filter=lfs diff=lfs merge=lfs -text
161
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/tibia_T3_right_body.msh filter=lfs diff=lfs merge=lfs -text
162
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/wing_left_brown.msh filter=lfs diff=lfs merge=lfs -text
163
+ data/dm_control/locomotion/walkers/assets/fruitfly_v2/wing_right_brown.msh filter=lfs diff=lfs merge=lfs -text
164
+ data/dm_control/locomotion/walkers/assets/rodent_walker_skin.skn filter=lfs diff=lfs merge=lfs -text
165
+ data/dm_control/mjcf/test_assets/skins/test_skin.skn filter=lfs diff=lfs merge=lfs -text
166
+ data/dm_control/suite/dog_assets/BONEC_1.stl filter=lfs diff=lfs merge=lfs -text
167
+ data/dm_control/suite/dog_assets/BONEC_2.stl filter=lfs diff=lfs merge=lfs -text
168
+ data/dm_control/suite/dog_assets/BONEC_3.stl filter=lfs diff=lfs merge=lfs -text
169
+ data/dm_control/suite/dog_assets/BONEC_4.stl filter=lfs diff=lfs merge=lfs -text
170
+ data/dm_control/suite/dog_assets/BONEC_5.stl filter=lfs diff=lfs merge=lfs -text
171
+ data/dm_control/suite/dog_assets/BONEC_6.stl filter=lfs diff=lfs merge=lfs -text
172
+ data/dm_control/suite/dog_assets/BONEC_7.stl filter=lfs diff=lfs merge=lfs -text
173
+ data/dm_control/suite/dog_assets/BONEJaw.stl filter=lfs diff=lfs merge=lfs -text
174
+ data/dm_control/suite/dog_assets/BONEL_1.stl filter=lfs diff=lfs merge=lfs -text
175
+ data/dm_control/suite/dog_assets/BONEL_2.stl filter=lfs diff=lfs merge=lfs -text
176
+ data/dm_control/suite/dog_assets/BONEL_3.stl filter=lfs diff=lfs merge=lfs -text
177
+ data/dm_control/suite/dog_assets/BONEL_4.stl filter=lfs diff=lfs merge=lfs -text
178
+ data/dm_control/suite/dog_assets/BONEL_5.stl filter=lfs diff=lfs merge=lfs -text
179
+ data/dm_control/suite/dog_assets/BONEL_6.stl filter=lfs diff=lfs merge=lfs -text
180
+ data/dm_control/suite/dog_assets/BONEL_7.stl filter=lfs diff=lfs merge=lfs -text
181
+ data/dm_control/suite/dog_assets/BONEMergedSkull.stl filter=lfs diff=lfs merge=lfs -text
182
+ data/dm_control/suite/dog_assets/BONEPelvis.stl filter=lfs diff=lfs merge=lfs -text
183
+ data/dm_control/suite/dog_assets/BONERibcage.stl filter=lfs diff=lfs merge=lfs -text
184
+ data/dm_control/suite/dog_assets/BONESacrum.stl filter=lfs diff=lfs merge=lfs -text
185
+ data/dm_control/suite/dog_assets/SKINbody.stl filter=lfs diff=lfs merge=lfs -text
186
+ data/dm_control/suite/dog_assets/dog_skin.msh filter=lfs diff=lfs merge=lfs -text
187
+ data/dm_control/suite/dog_assets/dog_skin.skn filter=lfs diff=lfs merge=lfs -text
188
+ data/dm_control/suite/dog_assets/extras/BONEEthmoid.stl filter=lfs diff=lfs merge=lfs -text
189
+ data/dm_control/suite/dog_assets/extras/BONEMandible.stl filter=lfs diff=lfs merge=lfs -text
190
+ data/dm_control/suite/dog_assets/extras/BONESkull.stl filter=lfs diff=lfs merge=lfs -text
191
+ data/dm_control/suite/dog_assets/extras/BONET_1.stl filter=lfs diff=lfs merge=lfs -text
192
+ data/dm_control/suite/dog_assets/extras/BONET_10.stl filter=lfs diff=lfs merge=lfs -text
193
+ data/dm_control/suite/dog_assets/extras/BONET_11.stl filter=lfs diff=lfs merge=lfs -text
194
+ data/dm_control/suite/dog_assets/extras/BONET_12.stl filter=lfs diff=lfs merge=lfs -text
195
+ data/dm_control/suite/dog_assets/extras/BONET_13.stl filter=lfs diff=lfs merge=lfs -text
196
+ data/dm_control/suite/dog_assets/extras/BONET_2.stl filter=lfs diff=lfs merge=lfs -text
197
+ data/dm_control/suite/dog_assets/extras/BONET_3.stl filter=lfs diff=lfs merge=lfs -text
198
+ data/dm_control/suite/dog_assets/extras/BONET_4.stl filter=lfs diff=lfs merge=lfs -text
199
+ data/dm_control/suite/dog_assets/extras/BONET_5.stl filter=lfs diff=lfs merge=lfs -text
200
+ data/dm_control/suite/dog_assets/extras/BONET_6.stl filter=lfs diff=lfs merge=lfs -text
201
+ data/dm_control/suite/dog_assets/extras/BONET_7.stl filter=lfs diff=lfs merge=lfs -text
202
+ data/dm_control/suite/dog_assets/extras/BONET_8.stl filter=lfs diff=lfs merge=lfs -text
203
+ data/dm_control/suite/dog_assets/extras/BONET_9.stl filter=lfs diff=lfs merge=lfs -text
204
+ data/dm_control/suite/dog_assets/extras/MUSCMm.dorsi_Fascia_thoracolumbar_.stl filter=lfs diff=lfs merge=lfs -text
205
+ data/dm_control/suite/dog_assets/extras/MUSCMm.thoracis_serratus_ventr_L.stl filter=lfs diff=lfs merge=lfs -text
206
+ data/dm_control/suite/dog_assets/extras/MUSCMm.thoracis_serratus_ventr_R.stl filter=lfs diff=lfs merge=lfs -text
207
+ data/dm_control/suite/dog_assets/extras/MUSCNose.stl filter=lfs diff=lfs merge=lfs -text
208
+ data/dm_control/suite/dog_assets/extras/MUSCabdominis_Aponeurosis.stl filter=lfs diff=lfs merge=lfs -text
209
+ data/dm_control/suite/dog_assets/extras/MUSCdiaphragma.stl filter=lfs diff=lfs merge=lfs -text
210
+ data/dm_control/suite/dog_assets/extras/MUSCm.brachiocephalicus.stl filter=lfs diff=lfs merge=lfs -text
211
+ data/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_L(2).stl filter=lfs diff=lfs merge=lfs -text
212
+ data/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_L.stl filter=lfs diff=lfs merge=lfs -text
213
+ data/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_R(2).stl filter=lfs diff=lfs merge=lfs -text
214
+ data/dm_control/suite/dog_assets/extras/MUSCm.flexor_digitorum_profundus_R.stl filter=lfs diff=lfs merge=lfs -text
215
+ data/dm_control/suite/dog_assets/extras/MUSCm.orbicularis_oculi.stl filter=lfs diff=lfs merge=lfs -text
216
+ data/dm_control/suite/dog_assets/extras/MUSCm.trapezius.stl filter=lfs diff=lfs merge=lfs -text
217
+ data/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_ext.L.stl filter=lfs diff=lfs merge=lfs -text
218
+ data/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_ext_R.stl filter=lfs diff=lfs merge=lfs -text
219
+ data/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_int.L.stl filter=lfs diff=lfs merge=lfs -text
220
+ data/dm_control/suite/dog_assets/extras/MUSCmm.intercostals_int_R.stl filter=lfs diff=lfs merge=lfs -text
221
+ data/dm_control/suite/dog_assets/extras/MUSCmm.thoracis_m.pectoralis_profundus.stl filter=lfs diff=lfs merge=lfs -text
222
+ data/dm_control/third_party/kinova/meshes/arm.stl filter=lfs diff=lfs merge=lfs -text
223
+ data/dm_control/third_party/kinova/meshes/base.stl filter=lfs diff=lfs merge=lfs -text
224
+ data/dm_control/third_party/kinova/meshes/finger_proximal.stl filter=lfs diff=lfs merge=lfs -text
225
+ data/dm_control/third_party/kinova/meshes/forearm.stl filter=lfs diff=lfs merge=lfs -text
226
+ data/dm_control/third_party/kinova/meshes/hand_3finger.stl filter=lfs diff=lfs merge=lfs -text
227
+ data/dm_control/third_party/kinova/meshes/hand_3finger_insert.stl filter=lfs diff=lfs merge=lfs -text
228
+ data/dm_control/third_party/kinova/meshes/hand_3finger_main.stl filter=lfs diff=lfs merge=lfs -text
229
+ data/dm_control/third_party/kinova/meshes/shoulder.stl filter=lfs diff=lfs merge=lfs -text
230
+ data/dm_control/third_party/kinova/meshes/wrist.stl filter=lfs diff=lfs merge=lfs -text
data/AUTHORS ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # This is the list of dm_control authors for copyright purposes.
2
+ #
3
+ # This does not necessarily list everyone who has contributed code, since in
4
+ # some cases, their employer may be the copyright holder. To see the full list
5
+ # of contributors, see the revision history in source control.
6
+
7
+ DeepMind Technologies
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How to Contribute
2
+
3
+ We'd love to accept your patches and contributions to this project. There are
4
+ just a few small guidelines you need to follow.
5
+
6
+ ## Contributor License Agreement
7
+
8
+ Contributions to this project must be accompanied by a Contributor License
9
+ Agreement. You (or your employer) retain the copyright to your contribution,
10
+ this simply gives us permission to use and redistribute your contributions as
11
+ part of the project. Head over to <https://cla.developers.google.com/> to see
12
+ your current agreements on file or to sign a new one.
13
+
14
+ You generally only need to submit a CLA once, so if you've already submitted one
15
+ (even if it was for a different project), you probably don't need to do it
16
+ again.
17
+
18
+ ## Code reviews
19
+
20
+ All submissions, including submissions by project members, require review. We
21
+ use GitHub pull requests for this purpose. Consult
22
+ [GitHub Help](https://help.github.com/articles/about-pull-requests/) for more
23
+ information on using pull requests.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # `dm_control`: Google DeepMind Infrastructure for Physics-Based Simulation.
2
+
3
+ Google DeepMind's software stack for physics-based simulation and Reinforcement
4
+ Learning environments, using MuJoCo physics.
5
+
6
+ An **introductory tutorial** for this package is available as a Colaboratory
7
+ notebook:
8
+ [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google-deepmind/dm_control/blob/main/tutorial.ipynb)
9
+
10
+ ## Overview
11
+
12
+ This package consists of the following "core" components:
13
+
14
+ - [`dm_control.mujoco`]: Libraries that provide Python bindings to the MuJoCo
15
+ physics engine.
16
+
17
+ - [`dm_control.suite`]: A set of Python Reinforcement Learning environments
18
+ powered by the MuJoCo physics engine.
19
+
20
+ - [`dm_control.viewer`]: An interactive environment viewer.
21
+
22
+ Additionally, the following components are available for the creation of more
23
+ complex control tasks:
24
+
25
+ - [`dm_control.mjcf`]: A library for composing and modifying MuJoCo MJCF
26
+ models in Python.
27
+
28
+ - `dm_control.composer`: A library for defining rich RL environments from
29
+ reusable, self-contained components.
30
+
31
+ - [`dm_control.locomotion`]: Additional libraries for custom tasks.
32
+
33
+ - [`dm_control.locomotion.soccer`]: Multi-agent soccer tasks.
34
+
35
+ If you use this package, please cite our accompanying [publication]:
36
+
37
+ ```
38
+ @article{tunyasuvunakool2020,
39
+ title = {dm_control: Software and tasks for continuous control},
40
+ journal = {Software Impacts},
41
+ volume = {6},
42
+ pages = {100022},
43
+ year = {2020},
44
+ issn = {2665-9638},
45
+ doi = {https://doi.org/10.1016/j.simpa.2020.100022},
46
+ url = {https://www.sciencedirect.com/science/article/pii/S2665963820300099},
47
+ author = {Saran Tunyasuvunakool and Alistair Muldal and Yotam Doron and
48
+ Siqi Liu and Steven Bohez and Josh Merel and Tom Erez and
49
+ Timothy Lillicrap and Nicolas Heess and Yuval Tassa},
50
+ }
51
+ ```
52
+
53
+ ## Installation
54
+
55
+ Install `dm_control` from PyPI by running
56
+
57
+ ```sh
58
+ pip install dm_control
59
+ ```
60
+
61
+ > **Note**: **`dm_control` cannot be installed in "editable" mode** (i.e. `pip
62
+ > install -e`).
63
+ >
64
+ > While `dm_control` has been largely updated to use the pybind11-based bindings
65
+ > provided via the `mujoco` package, at this time it still relies on some legacy
66
+ > components that are automatically generated from MuJoCo header files in a way
67
+ > that is incompatible with editable mode. Attempting to install `dm_control` in
68
+ > editable mode will result in import errors like:
69
+ >
70
+ > ```
71
+ > ImportError: cannot import name 'constants' from partially initialized module 'dm_control.mujoco.wrapper.mjbindings' ...
72
+ > ```
73
+ >
74
+ > The solution is to `pip uninstall dm_control` and then reinstall it without
75
+ > the `-e` flag.
76
+
77
+ ## Versioning
78
+
79
+ Starting from version 1.0.0, we adopt semantic versioning.
80
+
81
+ Prior to version 1.0.0, the `dm_control` Python package was versioned `0.0.N`,
82
+ where `N` was an internal revision number that increased by an arbitrary amount
83
+ at every single Git commit.
84
+
85
+ If you want to install an unreleased version of `dm_control` directly from our
86
+ repository, you can do so by running `pip install
87
+ git+https://github.com/google-deepmind/dm_control.git`.
88
+
89
+ ## Rendering
90
+
91
+ The MuJoCo Python bindings support three different OpenGL rendering backends:
92
+ EGL (headless, hardware-accelerated), GLFW (windowed, hardware-accelerated), and
93
+ OSMesa (purely software-based). At least one of these three backends must be
94
+ available in order render through `dm_control`.
95
+
96
+ * Hardware rendering with a windowing system is supported via GLFW and GLEW.
97
+ On Linux these can be installed using your distribution's package manager.
98
+ For example, on Debian and Ubuntu, this can be done by running `sudo apt-get
99
+ install libglfw3 libglew2.0`. Please note that:
100
+
101
+ - [`dm_control.viewer`] can only be used with GLFW.
102
+ - GLFW will not work on headless machines.
103
+
104
+ * "Headless" hardware rendering (i.e. without a windowing system such as X11)
105
+ requires [EXT_platform_device] support in the EGL driver. Recent Nvidia
106
+ drivers support this. You will also need GLEW. On Debian and Ubuntu, this
107
+ can be installed via `sudo apt-get install libglew2.0`.
108
+
109
+ * Software rendering requires GLX and OSMesa. On Debian and Ubuntu these can
110
+ be installed using `sudo apt-get install libgl1-mesa-glx libosmesa6`.
111
+
112
+ By default, `dm_control` will attempt to use GLFW first, then EGL, then OSMesa.
113
+ You can also specify a particular backend to use by setting the `MUJOCO_GL=`
114
+ environment variable to `"glfw"`, `"egl"`, or `"osmesa"`, respectively. When
115
+ rendering with EGL, you can also specify which GPU to use for rendering by
116
+ setting the environment variable `MUJOCO_EGL_DEVICE_ID=` to the target GPU ID.
117
+
118
+ ## Additional instructions for Homebrew users on macOS
119
+
120
+ 1. The above instructions using `pip` should work, provided that you use a
121
+ Python interpreter that is installed by Homebrew (rather than the
122
+ system-default one).
123
+
124
+ 2. Before running, the `DYLD_LIBRARY_PATH` environment variable needs to be
125
+ updated with the path to the GLFW library. This can be done by running
126
+ `export DYLD_LIBRARY_PATH=$(brew --prefix)/lib:$DYLD_LIBRARY_PATH`.
127
+
128
+ [EXT_platform_device]: https://www.khronos.org/registry/EGL/extensions/EXT/EGL_EXT_platform_device.txt
129
+ [Releases page on the MuJoCo GitHub repository]: https://github.com/google-deepmind/mujoco/releases
130
+ [MuJoCo website]: https://mujoco.org/
131
+ [publication]: https://doi.org/10.1016/j.simpa.2020.100022
132
+ [`ctypes`]: https://docs.python.org/3/library/ctypes.html
133
+ [`dm_control.mjcf`]: dm_control/mjcf/README.md
134
+ [`dm_control.mujoco`]: dm_control/mujoco/README.md
135
+ [`dm_control.suite`]: dm_control/suite/README.md
136
+ [`dm_control.viewer`]: dm_control/viewer/README.md
137
+ [`dm_control.locomotion`]: dm_control/locomotion/README.md
138
+ [`dm_control.locomotion.soccer`]: dm_control/locomotion/soccer/README.md
data/dm_control/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
data/dm_control/_render/__init__.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017-2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """OpenGL context management for rendering MuJoCo scenes.
17
+
18
+ By default, the `Renderer` class will try to load one of the following rendering
19
+ APIs, in descending order of priority: GLFW > EGL > OSMesa.
20
+
21
+ It is also possible to select a specific backend by setting the `MUJOCO_GL=`
22
+ environment variable to 'glfw', 'egl', or 'osmesa'.
23
+ """
24
+
25
+ import collections
26
+ import os
27
+
28
+ from absl import logging
29
+ from dm_control._render import constants
30
+
31
+ BACKEND = os.environ.get(constants.MUJOCO_GL)
32
+
33
+
34
+ # pylint: disable=g-import-not-at-top
35
+ def _import_egl():
36
+ from dm_control._render.pyopengl.egl_renderer import EGLContext
37
+ return EGLContext
38
+
39
+
40
+ def _import_glfw():
41
+ from dm_control._render.glfw_renderer import GLFWContext
42
+ return GLFWContext
43
+
44
+
45
+ def _import_osmesa():
46
+ from dm_control._render.pyopengl.osmesa_renderer import OSMesaContext
47
+ return OSMesaContext
48
+
49
+
50
+ # Import removed.
51
+ # pylint: enable=g-import-not-at-top
52
+
53
+
54
+ def _no_renderer():
55
+ def no_renderer(*args, **kwargs):
56
+ del args, kwargs
57
+ raise RuntimeError('No OpenGL rendering backend is available.')
58
+ return no_renderer
59
+
60
+
61
+ _ALL_RENDERERS = (
62
+ (constants.GLFW, _import_glfw),
63
+ (constants.EGL, _import_egl),
64
+ (constants.OSMESA, _import_osmesa),
65
+ # Option removed.
66
+ )
67
+
68
+ _NO_RENDERER = (
69
+ (constants.NO_RENDERER, _no_renderer),
70
+ )
71
+
72
+
73
+ if BACKEND is not None:
74
+ # If a backend was specified, try importing it and error if unsuccessful.
75
+ import_func = None
76
+ for names, importer in _ALL_RENDERERS + _NO_RENDERER:
77
+ if BACKEND in names:
78
+ import_func = importer
79
+ BACKEND = names[0] # canonicalize the renderer name
80
+ break
81
+ if import_func is None:
82
+ all_names = set()
83
+ for names, _ in _ALL_RENDERERS + _NO_RENDERER:
84
+ all_names.update(names)
85
+ raise RuntimeError(
86
+ 'Environment variable {} must be one of {!r}: got {!r}.'
87
+ .format(constants.MUJOCO_GL, sorted(all_names), BACKEND))
88
+ logging.info('MUJOCO_GL=%s, attempting to import specified OpenGL backend.',
89
+ BACKEND)
90
+ Renderer = import_func()
91
+ else:
92
+ logging.info('MUJOCO_GL is not set, so an OpenGL backend will be chosen '
93
+ 'automatically.')
94
+ # Otherwise try importing them in descending order of priority until
95
+ # successful.
96
+ for names, import_func in _ALL_RENDERERS:
97
+ try:
98
+ Renderer = import_func()
99
+ BACKEND = names[0]
100
+ logging.info('Successfully imported OpenGL backend: %s', names[0])
101
+ break
102
+ except ImportError:
103
+ logging.info('Failed to import OpenGL backend: %s', names[0])
104
+ if BACKEND is None:
105
+ logging.info('No OpenGL backend could be imported. Attempting to create a '
106
+ 'rendering context will result in a RuntimeError.')
107
+ Renderer = _no_renderer()
108
+
109
+ USING_GPU = BACKEND in constants.EGL + constants.GLFW
data/dm_control/_render/base.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Base class for OpenGL context handlers.
17
+
18
+ `ContextBase` defines a common API that OpenGL rendering contexts should conform
19
+ to. In addition, it provides a `make_current` context manager that:
20
+
21
+ 1. Makes this OpenGL context current within the appropriate rendering thread.
22
+ 2. Yields an object exposing a `call` method that can be used to execute OpenGL
23
+ calls within the rendering thread.
24
+
25
+ See the docstring for `dm_control.utils.render_executor` for further details
26
+ regarding rendering threads.
27
+ """
28
+
29
+ import abc
30
+ import atexit
31
+ import collections
32
+ import contextlib
33
+ import sys
34
+ import weakref
35
+
36
+ from absl import logging
37
+ from dm_control._render import executor
38
+ import numpy as np
39
+
40
+
41
+ _CURRENT_CONTEXT_FOR_THREAD = collections.defaultdict(lambda: None)
42
+ _CURRENT_THREAD_FOR_CONTEXT = collections.defaultdict(lambda: None)
43
+
44
+
45
+ class ContextBase(metaclass=abc.ABCMeta):
46
+ """Base class for managing OpenGL contexts."""
47
+
48
+ def __init__(self,
49
+ max_width,
50
+ max_height,
51
+ render_executor_class=executor.RenderExecutor):
52
+ """Initializes this context."""
53
+ logging.debug('Using render executor class: %s',
54
+ render_executor_class.__name__)
55
+ self._render_executor = render_executor_class()
56
+ self._refcount = 0
57
+
58
+ self_weakref = weakref.ref(self)
59
+ def _free_at_exit():
60
+ if self_weakref():
61
+ self_weakref()._free_unconditionally() # pylint: disable=protected-access
62
+ atexit.register(_free_at_exit)
63
+
64
+ with self._render_executor.execution_context() as ctx:
65
+ ctx.call(self._platform_init, max_width, max_height)
66
+
67
+ self._patients = []
68
+
69
+ def keep_alive(self, obj):
70
+ self._patients.append(obj)
71
+
72
+ def dont_keep_alive(self, obj):
73
+ try:
74
+ self._patients.remove(obj)
75
+ except ValueError:
76
+ pass
77
+
78
+ def increment_refcount(self):
79
+ self._refcount += 1
80
+
81
+ def decrement_refcount(self):
82
+ self._refcount -= 1
83
+
84
+ @property
85
+ def terminated(self):
86
+ return self._render_executor.terminated
87
+
88
+ @property
89
+ def thread(self):
90
+ return self._render_executor.thread
91
+
92
+ def _free_on_executor_thread(self): # pylint: disable=missing-function-docstring
93
+ current_ctx = _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread]
94
+ if current_ctx is not None:
95
+ del _CURRENT_THREAD_FOR_CONTEXT[current_ctx]
96
+ del _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread]
97
+
98
+ self._platform_make_current()
99
+
100
+ try:
101
+ dummy = []
102
+ while self._patients:
103
+ patient = self._patients.pop()
104
+ assert sys.getrefcount(patient) == sys.getrefcount(dummy)
105
+ if hasattr(patient, 'free'):
106
+ patient.free()
107
+ del patient
108
+ finally:
109
+ self._platform_free()
110
+
111
+ def free(self):
112
+ """Frees resources associated with this context if its refcount is zero."""
113
+ if self._refcount == 0:
114
+ self._free_unconditionally()
115
+
116
+ def _free_unconditionally(self):
117
+ self._render_executor.terminate(self._free_on_executor_thread)
118
+
119
+ def __del__(self):
120
+ self._free_unconditionally()
121
+
122
+ @contextlib.contextmanager
123
+ def make_current(self):
124
+ """Context manager that makes this Renderer's OpenGL context current.
125
+
126
+ Yields:
127
+ An object that exposes a `call` method that can be used to call a
128
+ function on the dedicated rendering thread.
129
+
130
+ Raises:
131
+ RuntimeError: If this context is already current on another thread.
132
+ """
133
+
134
+ with self._render_executor.execution_context() as ctx:
135
+ if _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] != id(self):
136
+ if _CURRENT_THREAD_FOR_CONTEXT[id(self)]:
137
+ raise RuntimeError(
138
+ 'Cannot make context {!r} current on thread {!r}: '
139
+ 'this context is already current on another thread {!r}.'
140
+ .format(self, self._render_executor.thread,
141
+ _CURRENT_THREAD_FOR_CONTEXT[id(self)]))
142
+ else:
143
+ current_context = (
144
+ _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread])
145
+ if current_context:
146
+ del _CURRENT_THREAD_FOR_CONTEXT[current_context]
147
+ _CURRENT_THREAD_FOR_CONTEXT[id(self)] = self._render_executor.thread
148
+ _CURRENT_CONTEXT_FOR_THREAD[self._render_executor.thread] = id(self)
149
+ ctx.call(self._platform_make_current)
150
+ yield ctx
151
+
152
+ def to_pixels(self, buffer):
153
+ """Converts the buffer to pixels."""
154
+ return np.flipud(buffer)
155
+
156
+ @abc.abstractmethod
157
+ def _platform_init(self, max_width, max_height):
158
+ """Performs an implementation-specific context initialization."""
159
+
160
+ @abc.abstractmethod
161
+ def _platform_make_current(self):
162
+ """Make the OpenGL context current on the executing thread."""
163
+
164
+ @abc.abstractmethod
165
+ def _platform_free(self):
166
+ """Performs an implementation-specific context cleanup."""
data/dm_control/_render/base_test.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for the base rendering module."""
17
+
18
+ import threading
19
+ from absl.testing import absltest
20
+ from dm_control._render import base
21
+ from dm_control._render import executor
22
+
23
+ WIDTH = 1024
24
+ HEIGHT = 768
25
+
26
+
27
+ class ContextBaseTests(absltest.TestCase):
28
+
29
+ class ContextMock(base.ContextBase):
30
+
31
+ def _platform_init(self, max_width, max_height):
32
+ self.init_thread = threading.current_thread()
33
+ self.make_current_count = 0
34
+ self.max_width = max_width
35
+ self.max_height = max_height
36
+ self.free_thread = None
37
+
38
+ def _platform_make_current(self):
39
+ self.make_current_count += 1
40
+ self.make_current_thread = threading.current_thread()
41
+
42
+ def _platform_free(self):
43
+ self.free_thread = threading.current_thread()
44
+
45
+ def setUp(self):
46
+ super().setUp()
47
+ self.context = ContextBaseTests.ContextMock(WIDTH, HEIGHT)
48
+
49
+ def test_init(self):
50
+ self.assertIs(self.context.init_thread, self.context.thread)
51
+ self.assertEqual(self.context.max_width, WIDTH)
52
+ self.assertEqual(self.context.max_height, HEIGHT)
53
+
54
+ def test_make_current(self):
55
+ self.assertEqual(self.context.make_current_count, 0)
56
+
57
+ with self.context.make_current():
58
+ pass
59
+ self.assertEqual(self.context.make_current_count, 1)
60
+ self.assertIs(self.context.make_current_thread, self.context.thread)
61
+
62
+ # Already current, shouldn't trigger a call to `_platform_make_current`.
63
+ with self.context.make_current():
64
+ pass
65
+ self.assertEqual(self.context.make_current_count, 1)
66
+ self.assertIs(self.context.make_current_thread, self.context.thread)
67
+
68
+ def test_thread_sharing(self):
69
+ first_context = ContextBaseTests.ContextMock(
70
+ WIDTH, HEIGHT, executor.PassthroughRenderExecutor)
71
+ second_context = ContextBaseTests.ContextMock(
72
+ WIDTH, HEIGHT, executor.PassthroughRenderExecutor)
73
+
74
+ with first_context.make_current():
75
+ pass
76
+ self.assertEqual(first_context.make_current_count, 1)
77
+
78
+ with first_context.make_current():
79
+ pass
80
+ self.assertEqual(first_context.make_current_count, 1)
81
+
82
+ with second_context.make_current():
83
+ pass
84
+ self.assertEqual(second_context.make_current_count, 1)
85
+
86
+ with second_context.make_current():
87
+ pass
88
+ self.assertEqual(second_context.make_current_count, 1)
89
+
90
+ with first_context.make_current():
91
+ pass
92
+ self.assertEqual(first_context.make_current_count, 2)
93
+
94
+ with second_context.make_current():
95
+ pass
96
+ self.assertEqual(second_context.make_current_count, 2)
97
+
98
+ def test_free(self):
99
+ with self.context.make_current():
100
+ pass
101
+
102
+ thread = self.context.thread
103
+ self.assertIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT)
104
+ self.assertIn(thread, base._CURRENT_CONTEXT_FOR_THREAD)
105
+
106
+ self.context.free()
107
+ self.assertIs(self.context.free_thread, thread)
108
+ self.assertIsNone(self.context.thread)
109
+
110
+ self.assertNotIn(id(self.context), base._CURRENT_THREAD_FOR_CONTEXT)
111
+ self.assertNotIn(thread, base._CURRENT_CONTEXT_FOR_THREAD)
112
+
113
+ def test_free_with_multiple_contexts(self):
114
+ context1 = ContextBaseTests.ContextMock(WIDTH, HEIGHT,
115
+ executor.PassthroughRenderExecutor)
116
+ with context1.make_current():
117
+ pass
118
+
119
+ context2 = ContextBaseTests.ContextMock(WIDTH, HEIGHT,
120
+ executor.PassthroughRenderExecutor)
121
+ with context2.make_current():
122
+ pass
123
+
124
+ self.assertEqual(base._CURRENT_CONTEXT_FOR_THREAD[threading.main_thread()],
125
+ id(context2))
126
+ self.assertIs(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)],
127
+ threading.main_thread())
128
+
129
+ context1.free()
130
+ self.assertIsNone(
131
+ base._CURRENT_CONTEXT_FOR_THREAD[self.context.free_thread])
132
+ self.assertIsNone(base._CURRENT_THREAD_FOR_CONTEXT[id(context2)])
133
+
134
+ def test_refcounting(self):
135
+ thread = self.context.thread
136
+
137
+ self.assertEqual(self.context._refcount, 0)
138
+ self.context.increment_refcount()
139
+ self.assertEqual(self.context._refcount, 1)
140
+
141
+ # Context should not be freed yet, since its refcount is still positive.
142
+ self.context.free()
143
+ self.assertIsNone(self.context.free_thread)
144
+ self.assertIs(self.context.thread, thread)
145
+
146
+ # Decrement the refcount to zero.
147
+ self.context.decrement_refcount()
148
+ self.assertEqual(self.context._refcount, 0)
149
+
150
+ # Now the context can be freed.
151
+ self.context.free()
152
+ self.assertIs(self.context.free_thread, thread)
153
+ self.assertIsNone(self.context.thread)
154
+
155
+ def test_del(self):
156
+ self.assertIsNone(self.context.free_thread)
157
+ self.context.__del__()
158
+ self.assertIsNotNone(self.context.free_thread)
159
+
160
+
161
+ if __name__ == '__main__':
162
+ absltest.main()
data/dm_control/_render/constants.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """String constants for the rendering module."""
17
+
18
+ # Name of the environment variable that selects a renderer platform.
19
+ MUJOCO_GL = 'MUJOCO_GL'
20
+
21
+ # Name of the environment variable that selects a platform for PyOpenGL.
22
+ PYOPENGL_PLATFORM = 'PYOPENGL_PLATFORM'
23
+
24
+ # Renderer platform specifiers.
25
+ # All values in each tuple are synonyms for the MUJOCO_GL environment variable.
26
+ # The first entry in each tuple is considered "canonical", and is the one
27
+ # assigned to the _render.BACKEND variable.
28
+ OSMESA = ('osmesa',)
29
+ GLFW = ('glfw', 'on', 'enable', 'enabled', 'true', '1', '')
30
+ EGL = ('egl',)
31
+ # Constant removed.
32
+ NO_RENDERER = ('off', 'disable', 'disabled', 'false', '0')
33
+
data/dm_control/_render/executor/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """RenderExecutor executes OpenGL rendering calls on an appropriate thread.
17
+
18
+ OpenGL calls must be made on the same thread as where an OpenGL context is
19
+ made current on. With GPU rendering, migrating OpenGL contexts between threads
20
+ can become expensive. We provide a thread-safe executor that maintains a
21
+ thread on which an OpenGL context can be kept permanently current, and any other
22
+ threads that wish to render with that context will have their rendering calls
23
+ offloaded to the dedicated thread.
24
+
25
+ For single-threaded applications, set the `DISABLE_RENDER_THREAD_OFFLOADING`
26
+ environment variable before launching the Python interpreter. This will
27
+ eliminate the overhead of unnecessary thread-switching.
28
+ """
29
+
30
+ # pylint: disable=g-import-not-at-top
31
+ import os
32
+ _OFFLOAD = not bool(os.environ.get('DISABLE_RENDER_THREAD_OFFLOADING', ''))
33
+ del os
34
+
35
+ from dm_control._render.executor.render_executor import BaseRenderExecutor
36
+ from dm_control._render.executor.render_executor import OffloadingRenderExecutor
37
+ from dm_control._render.executor.render_executor import PassthroughRenderExecutor
38
+
39
+ _EXECUTORS = (PassthroughRenderExecutor, OffloadingRenderExecutor)
40
+
41
+ try:
42
+ from dm_control._render.executor.native_mutex.render_executor import NativeMutexOffloadingRenderExecutor
43
+ _EXECUTORS += (NativeMutexOffloadingRenderExecutor,)
44
+ except ImportError:
45
+ NativeMutexOffloadingRenderExecutor = None
46
+
47
+ if _OFFLOAD:
48
+ RenderExecutor = ( # pylint: disable=invalid-name
49
+ NativeMutexOffloadingRenderExecutor or OffloadingRenderExecutor)
50
+ else:
51
+ RenderExecutor = PassthroughRenderExecutor # pylint: disable=invalid-name
data/dm_control/_render/executor/render_executor.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017-2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """RenderExecutors executes OpenGL rendering calls on an appropriate thread.
17
+
18
+ The purpose of these classes is to ensure that OpenGL calls are made on the
19
+ same thread as where an OpenGL context was made current.
20
+
21
+ In a single-threaded setting, `PassthroughRenderExecutor` is essentially a no-op
22
+ that executes rendering calls on the same thread. This is provided to minimize
23
+ thread-switching overhead.
24
+
25
+ In a multithreaded setting, `OffloadingRenderExecutor` maintains a separate
26
+ dedicated thread on which the OpenGL context is created and made current. All
27
+ subsequent rendering calls are then offloaded onto this dedicated thread.
28
+ """
29
+
30
+ import abc
31
+ import collections
32
+ from concurrent import futures
33
+ import contextlib
34
+ import threading
35
+
36
+
37
+ _NOT_IN_CONTEXT = 'Cannot be called outside of an `execution_context`.'
38
+ _ALREADY_TERMINATED = 'This executor has already been terminated.'
39
+
40
+
41
+ class _FakeLock:
42
+ """An object with the same API as `threading.Lock` but that does nothing."""
43
+
44
+ def acquire(self, blocking=True):
45
+ pass
46
+
47
+ def release(self):
48
+ pass
49
+
50
+ def __enter__(self):
51
+ pass
52
+
53
+ def __exit__(self, exc_type, exc_value, traceback):
54
+ del exc_type, exc_value, traceback
55
+
56
+
57
+ _FAKE_LOCK = _FakeLock()
58
+
59
+
60
+ class BaseRenderExecutor(metaclass=abc.ABCMeta):
61
+ """An object that manages rendering calls for an OpenGL context.
62
+
63
+ This class helps ensure that OpenGL calls are made on the correct thread. The
64
+ usage pattern is as follows:
65
+
66
+ ```python
67
+ executor = SomeRenderExecutorClass()
68
+ with executor.execution_context() as ctx:
69
+ ctx.call(an_opengl_call, arg, kwarg=foo)
70
+ result = ctx.call(another_opengl_call)
71
+ ```
72
+ """
73
+
74
+ def __init__(self):
75
+ self._locked = 0
76
+ self._terminated = False
77
+
78
+ def _check_locked(self):
79
+ if not self._locked:
80
+ raise RuntimeError(_NOT_IN_CONTEXT)
81
+
82
+ def _check_not_terminated(self):
83
+ if self._terminated:
84
+ raise RuntimeError(_ALREADY_TERMINATED)
85
+
86
+ @contextlib.contextmanager
87
+ def execution_context(self):
88
+ """A context manager that allows calls to be offloaded to this executor."""
89
+ self._check_not_terminated()
90
+ with self._lock_if_necessary:
91
+ self._locked += 1
92
+ yield self
93
+ self._locked -= 1
94
+
95
+ @property
96
+ def terminated(self):
97
+ return self._terminated
98
+
99
+ @property
100
+ @abc.abstractmethod
101
+ def thread(self):
102
+ pass
103
+
104
+ @property
105
+ @abc.abstractmethod
106
+ def _lock_if_necessary(self):
107
+ pass
108
+
109
+ @abc.abstractmethod
110
+ def call(self, *args, **kwargs):
111
+ pass
112
+
113
+ @abc.abstractmethod
114
+ def terminate(self, cleanup_callable=None):
115
+ pass
116
+
117
+
118
+ class PassthroughRenderExecutor(BaseRenderExecutor):
119
+ """A no-op render executor that executes on the calling thread."""
120
+
121
+ def __init__(self):
122
+ super().__init__()
123
+ self._mutex = threading.RLock()
124
+
125
+ @property
126
+ def thread(self):
127
+ if not self._terminated:
128
+ return threading.current_thread()
129
+ else:
130
+ return None
131
+
132
+ @property
133
+ def _lock_if_necessary(self):
134
+ return self._mutex
135
+
136
+ def call(self, func, *args, **kwargs):
137
+ self._check_locked()
138
+ return func(*args, **kwargs)
139
+
140
+ def terminate(self, cleanup_callable=None):
141
+ with self._lock_if_necessary:
142
+ if not self._terminated:
143
+ if cleanup_callable:
144
+ cleanup_callable()
145
+ self._terminated = True
146
+
147
+
148
+ class _ThreadPoolExecutorPool:
149
+ """A pool of reusable ThreadPoolExecutors."""
150
+
151
+ def __init__(self):
152
+ self._deque = collections.deque()
153
+ self._lock = threading.Lock()
154
+
155
+ def acquire(self):
156
+ with self._lock:
157
+ if self._deque:
158
+ return self._deque.popleft()
159
+ else:
160
+ return futures.ThreadPoolExecutor(max_workers=1)
161
+
162
+ def release(self, thread_pool_executor):
163
+ with self._lock:
164
+ self._deque.append(thread_pool_executor)
165
+
166
+
167
+ _THREAD_POOL_EXECUTOR_POOL = _ThreadPoolExecutorPool()
168
+
169
+
170
+ class OffloadingRenderExecutor(BaseRenderExecutor):
171
+ """A render executor that executes calls on a dedicated offload thread."""
172
+
173
+ def __init__(self):
174
+ super().__init__()
175
+ self._mutex = threading.RLock()
176
+ self._executor = _THREAD_POOL_EXECUTOR_POOL.acquire()
177
+ self._thread = self._executor.submit(threading.current_thread).result()
178
+
179
+ @property
180
+ def thread(self):
181
+ return self._thread
182
+
183
+ @property
184
+ def _lock_if_necessary(self):
185
+ if threading.current_thread() is self.thread:
186
+ # If the offload thread needs to make a call to its own executor, for
187
+ # example when a weakref callback is triggered during an offloaded call,
188
+ # then we must not try to reacquire our own lock.
189
+ # Otherwise, a deadlock ensues.
190
+ return _FAKE_LOCK
191
+ else:
192
+ return self._mutex
193
+
194
+ def call(self, func, *args, **kwargs):
195
+ self._check_locked()
196
+ return self._call_locked(func, *args, **kwargs)
197
+
198
+ def _call_locked(self, func, *args, **kwargs):
199
+ if threading.current_thread() is self.thread:
200
+ # If the offload thread needs to make a call to its own executor, for
201
+ # example when a weakref callback is triggered during an offloaded call,
202
+ # we should just directly call the function.
203
+ # Otherwise, a deadlock ensues.
204
+ return func(*args, **kwargs)
205
+ else:
206
+ return self._executor.submit(func, *args, **kwargs).result()
207
+
208
+ def terminate(self, cleanup_callable=None):
209
+ if self._terminated:
210
+ return
211
+ with self._lock_if_necessary:
212
+ if not self._terminated:
213
+ if cleanup_callable:
214
+ self._call_locked(cleanup_callable)
215
+ _THREAD_POOL_EXECUTOR_POOL.release(self._executor)
216
+ self._executor = None
217
+ self._thread = None
218
+ self._terminated = True
data/dm_control/_render/executor/render_executor_test.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017-2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for dm_control.utils.render_executor."""
17
+
18
+ import threading
19
+ import time
20
+ import unittest
21
+
22
+ from absl.testing import absltest
23
+ from absl.testing import parameterized
24
+ from dm_control._render import executor
25
+ import mock
26
+
27
+
28
+ def enforce_timeout(timeout):
29
+ def wrap(test_func):
30
+ def wrapped_test(self, *args, **kwargs):
31
+ thread = threading.Thread(
32
+ target=test_func, args=((self,) + args), kwargs=kwargs)
33
+ thread.daemon = True
34
+ thread.start()
35
+ thread.join(timeout=timeout)
36
+ self.assertFalse(
37
+ thread.is_alive(),
38
+ msg='Test timed out after {} seconds.'.format(timeout))
39
+ return wrapped_test
40
+ return wrap
41
+
42
+
43
+ class RenderExecutorTest(parameterized.TestCase):
44
+
45
+ def _make_executor(self, executor_type):
46
+ if (executor_type == executor.NativeMutexOffloadingRenderExecutor and
47
+ executor_type is None):
48
+ raise unittest.SkipTest(
49
+ 'NativeMutexOffloadingRenderExecutor is not available.')
50
+ else:
51
+ return executor_type()
52
+
53
+ def test_passthrough_executor_thread(self):
54
+ render_executor = self._make_executor(executor.PassthroughRenderExecutor)
55
+ self.assertIs(render_executor.thread, threading.current_thread())
56
+ render_executor.terminate()
57
+
58
+ @parameterized.parameters(executor.OffloadingRenderExecutor,
59
+ executor.NativeMutexOffloadingRenderExecutor)
60
+ def test_offloading_executor_thread(self, executor_type):
61
+ render_executor = self._make_executor(executor_type)
62
+ self.assertIsNot(render_executor.thread, threading.current_thread())
63
+ render_executor.terminate()
64
+
65
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
66
+ executor.OffloadingRenderExecutor,
67
+ executor.NativeMutexOffloadingRenderExecutor)
68
+ def test_call_on_correct_thread(self, executor_type):
69
+ render_executor = self._make_executor(executor_type)
70
+ with render_executor.execution_context() as ctx:
71
+ actual_executed_thread = ctx.call(threading.current_thread)
72
+ self.assertIs(actual_executed_thread, render_executor.thread)
73
+ render_executor.terminate()
74
+
75
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
76
+ executor.OffloadingRenderExecutor,
77
+ executor.NativeMutexOffloadingRenderExecutor)
78
+ def test_multithreaded(self, executor_type):
79
+ render_executor = self._make_executor(executor_type)
80
+ list_length = 5
81
+ shared_list = [None] * list_length
82
+
83
+ def fill_list(thread_idx):
84
+ def assign_value(i):
85
+ shared_list[i] = thread_idx
86
+ for _ in range(1000):
87
+ with render_executor.execution_context() as ctx:
88
+ for i in range(list_length):
89
+ ctx.call(assign_value, i)
90
+ # Other threads should be prevented from calling `assign_value` while
91
+ # this thread is inside the `execution_context`.
92
+ self.assertEqual(shared_list, [thread_idx] * list_length)
93
+
94
+ threads = [threading.Thread(target=fill_list, args=(i,)) for i in range(9)]
95
+ for thread in threads:
96
+ thread.start()
97
+ for thread in threads:
98
+ thread.join()
99
+
100
+ render_executor.terminate()
101
+
102
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
103
+ executor.OffloadingRenderExecutor,
104
+ executor.NativeMutexOffloadingRenderExecutor)
105
+ def test_exception(self, executor_type):
106
+ render_executor = self._make_executor(executor_type)
107
+ message = 'fake error'
108
+ def raise_value_error():
109
+ raise ValueError(message)
110
+ with render_executor.execution_context() as ctx:
111
+ with self.assertRaisesWithLiteralMatch(ValueError, message):
112
+ ctx.call(raise_value_error)
113
+ render_executor.terminate()
114
+
115
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
116
+ executor.OffloadingRenderExecutor,
117
+ executor.NativeMutexOffloadingRenderExecutor)
118
+ def test_terminate(self, executor_type):
119
+ render_executor = self._make_executor(executor_type)
120
+ cleanup = mock.MagicMock()
121
+ render_executor.terminate(cleanup)
122
+ cleanup.assert_called_once_with()
123
+
124
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
125
+ executor.OffloadingRenderExecutor,
126
+ executor.NativeMutexOffloadingRenderExecutor)
127
+ def test_call_outside_of_context(self, executor_type):
128
+ render_executor = self._make_executor(executor_type)
129
+ func = mock.MagicMock()
130
+ with self.assertRaisesWithLiteralMatch(
131
+ RuntimeError, executor.render_executor._NOT_IN_CONTEXT):
132
+ render_executor.call(func)
133
+ # Also test that the locked flag is properly cleared when leaving a context.
134
+ with render_executor.execution_context():
135
+ render_executor.call(lambda: None)
136
+ with self.assertRaisesWithLiteralMatch(
137
+ RuntimeError, executor.render_executor._NOT_IN_CONTEXT):
138
+ render_executor.call(func)
139
+ func.assert_not_called()
140
+ render_executor.terminate()
141
+
142
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
143
+ executor.OffloadingRenderExecutor,
144
+ executor.NativeMutexOffloadingRenderExecutor)
145
+ def test_call_after_terminate(self, executor_type):
146
+ render_executor = self._make_executor(executor_type)
147
+ render_executor.terminate()
148
+ func = mock.MagicMock()
149
+ with self.assertRaisesWithLiteralMatch(
150
+ RuntimeError, executor.render_executor._ALREADY_TERMINATED):
151
+ with render_executor.execution_context() as ctx:
152
+ ctx.call(func)
153
+ func.assert_not_called()
154
+
155
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
156
+ executor.OffloadingRenderExecutor,
157
+ executor.NativeMutexOffloadingRenderExecutor)
158
+ def test_locking(self, executor_type):
159
+ render_executor = self._make_executor(executor_type)
160
+ other_thread_context_entered = threading.Condition()
161
+ other_thread_context_done = [False]
162
+ def other_thread_func():
163
+ with render_executor.execution_context():
164
+ with other_thread_context_entered:
165
+ other_thread_context_entered.notify()
166
+ time.sleep(1)
167
+ other_thread_context_done[0] = True
168
+ other_thread = threading.Thread(target=other_thread_func)
169
+ with other_thread_context_entered:
170
+ other_thread.start()
171
+ other_thread_context_entered.wait()
172
+ with render_executor.execution_context():
173
+ self.assertTrue(
174
+ other_thread_context_done[0],
175
+ msg=('Main thread should not be able to enter the execution context '
176
+ 'until the other thread is done.'))
177
+
178
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
179
+ executor.OffloadingRenderExecutor,
180
+ executor.NativeMutexOffloadingRenderExecutor)
181
+ @enforce_timeout(timeout=5.)
182
+ def test_reentrant_locking(self, executor_type):
183
+ render_executor = self._make_executor(executor_type)
184
+ def triple_lock(render_executor):
185
+ with render_executor.execution_context():
186
+ with render_executor.execution_context():
187
+ with render_executor.execution_context():
188
+ pass
189
+ triple_lock(render_executor)
190
+
191
+ @parameterized.parameters(executor.PassthroughRenderExecutor,
192
+ executor.OffloadingRenderExecutor,
193
+ executor.NativeMutexOffloadingRenderExecutor)
194
+ @enforce_timeout(timeout=5.)
195
+ def test_no_deadlock_in_callbacks(self, executor_type):
196
+ render_executor = self._make_executor(executor_type)
197
+ # This test times out in the event of a deadlock.
198
+ def callback():
199
+ with render_executor.execution_context() as ctx:
200
+ ctx.call(lambda: None)
201
+ with render_executor.execution_context() as ctx:
202
+ ctx.call(callback)
203
+
204
+ if __name__ == '__main__':
205
+ absltest.main()
data/dm_control/_render/glfw_renderer.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """An OpenGL renderer backed by GLFW."""
17
+
18
+ from dm_control._render import base
19
+ from dm_control._render import executor
20
+
21
+ # Re-raise any exceptions that occur during module import as `ImportError`s.
22
+ # This simplifies the conditional imports in `render/__init__.py`.
23
+ try:
24
+ import glfw # pylint: disable=g-import-not-at-top
25
+ except (ImportError, IOError, OSError) as exc:
26
+ raise ImportError from exc
27
+ try:
28
+ glfw.init()
29
+ except glfw.GLFWError as exc:
30
+ raise ImportError from exc
31
+
32
+
33
+ class GLFWContext(base.ContextBase):
34
+ """An OpenGL context backed by GLFW."""
35
+
36
+ def __init__(self, max_width, max_height):
37
+ # GLFWContext always uses `PassthroughRenderExecutor` rather than offloading
38
+ # rendering calls to a separate thread because GLFW can only be safely used
39
+ # from the main thread.
40
+ super().__init__(max_width, max_height, executor.PassthroughRenderExecutor)
41
+
42
+ def _platform_init(self, max_width, max_height):
43
+ """Initializes this context.
44
+
45
+ Args:
46
+ max_width: Integer specifying the maximum framebuffer width in pixels.
47
+ max_height: Integer specifying the maximum framebuffer height in pixels.
48
+ """
49
+ glfw.window_hint(glfw.VISIBLE, 0)
50
+ glfw.window_hint(glfw.DOUBLEBUFFER, 0)
51
+ self._context = glfw.create_window(width=max_width, height=max_height,
52
+ title='Invisible window', monitor=None,
53
+ share=None)
54
+ # This reference prevents `glfw.destroy_window` from being garbage-collected
55
+ # before the last window is destroyed, otherwise we may get
56
+ # `AttributeError`s when the `__del__` method is later called.
57
+ self._destroy_window = glfw.destroy_window
58
+
59
+ def _platform_make_current(self):
60
+ glfw.make_context_current(self._context)
61
+
62
+ def _platform_free(self):
63
+ """Frees resources associated with this context."""
64
+ if self._context:
65
+ if glfw.get_current_context() == self._context:
66
+ glfw.make_context_current(None)
67
+ self._destroy_window(self._context)
68
+ self._context = None
data/dm_control/_render/glfw_renderer_test.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for GLFWContext."""
17
+
18
+ import unittest
19
+ from absl.testing import absltest
20
+ from dm_control import _render
21
+ from dm_control.mujoco import wrapper
22
+ from dm_control.mujoco.testing import decorators
23
+
24
+ import mock # pylint: disable=g-import-not-at-top
25
+
26
+ MAX_WIDTH = 1024
27
+ MAX_HEIGHT = 1024
28
+
29
+ CONTEXT_PATH = _render.__name__ + '.glfw_renderer.glfw'
30
+
31
+
32
+ @unittest.skipUnless(
33
+ _render.BACKEND == _render.constants.GLFW[0],
34
+ reason='GLFW beckend not selected.')
35
+ class GLFWContextTest(absltest.TestCase):
36
+
37
+ def test_init(self):
38
+ mock_context = mock.MagicMock()
39
+ with mock.patch(CONTEXT_PATH) as mock_glfw:
40
+ mock_glfw.create_window.return_value = mock_context
41
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
42
+ self.assertIs(renderer._context, mock_context)
43
+
44
+ def test_make_current(self):
45
+ mock_context = mock.MagicMock()
46
+ with mock.patch(CONTEXT_PATH) as mock_glfw:
47
+ mock_glfw.create_window.return_value = mock_context
48
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
49
+ with renderer.make_current():
50
+ pass
51
+ mock_glfw.make_context_current.assert_called_once_with(mock_context)
52
+
53
+ def test_freeing(self):
54
+ mock_context = mock.MagicMock()
55
+ with mock.patch(CONTEXT_PATH) as mock_glfw:
56
+ mock_glfw.create_window.return_value = mock_context
57
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
58
+ renderer.free()
59
+ mock_glfw.destroy_window.assert_called_once_with(mock_context)
60
+ self.assertIsNone(renderer._context)
61
+
62
+ @decorators.run_threaded(num_threads=1, calls_per_thread=20)
63
+ def test_repeatedly_create_and_destroy_context(self):
64
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
65
+ wrapper.MjrContext(wrapper.MjModel.from_xml_string('<mujoco/>'), renderer)
66
+
67
+ if __name__ == '__main__':
68
+ absltest.main()
data/dm_control/_render/pyopengl/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
data/dm_control/_render/pyopengl/egl_ext.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Extends OpenGL.EGL with definitions necessary for headless rendering."""
17
+
18
+ import ctypes
19
+ from OpenGL.platform import ctypesloader # pylint: disable=g-bad-import-order
20
+ try:
21
+ # Nvidia driver seems to need libOpenGL.so (as opposed to libGL.so)
22
+ # for multithreading to work properly. We load this in before everything else.
23
+ ctypesloader.loadLibrary(ctypes.cdll, 'OpenGL', mode=ctypes.RTLD_GLOBAL)
24
+ except OSError:
25
+ pass
26
+
27
+ # pylint: disable=g-import-not-at-top
28
+
29
+ from OpenGL import EGL
30
+ from OpenGL import error
31
+
32
+
33
+ # From the EGL_EXT_device_enumeration extension.
34
+ PFNEGLQUERYDEVICESEXTPROC = ctypes.CFUNCTYPE(
35
+ EGL.EGLBoolean,
36
+ EGL.EGLint,
37
+ ctypes.POINTER(EGL.EGLDeviceEXT),
38
+ ctypes.POINTER(EGL.EGLint),
39
+ )
40
+ try:
41
+ _eglQueryDevicesEXT = PFNEGLQUERYDEVICESEXTPROC( # pylint: disable=invalid-name
42
+ EGL.eglGetProcAddress('eglQueryDevicesEXT'))
43
+ except TypeError:
44
+ raise ImportError('eglQueryDevicesEXT is not available.')
45
+
46
+
47
+ # From the EGL_EXT_platform_device extension.
48
+ EGL_PLATFORM_DEVICE_EXT = 0x313F
49
+ PFNEGLGETPLATFORMDISPLAYEXTPROC = ctypes.CFUNCTYPE(
50
+ EGL.EGLDisplay, EGL.EGLenum, ctypes.c_void_p, ctypes.POINTER(EGL.EGLint))
51
+ try:
52
+ eglGetPlatformDisplayEXT = PFNEGLGETPLATFORMDISPLAYEXTPROC( # pylint: disable=invalid-name
53
+ EGL.eglGetProcAddress('eglGetPlatformDisplayEXT'))
54
+ except TypeError:
55
+ raise ImportError('eglGetPlatformDisplayEXT is not available.')
56
+
57
+
58
+ # Wrap raw _eglQueryDevicesEXT function into something more Pythonic.
59
+ def eglQueryDevicesEXT(max_devices=10): # pylint: disable=invalid-name
60
+ devices = (EGL.EGLDeviceEXT * max_devices)()
61
+ num_devices = EGL.EGLint()
62
+ success = _eglQueryDevicesEXT(max_devices, devices, num_devices)
63
+ if success == EGL.EGL_TRUE:
64
+ return [devices[i] for i in range(num_devices.value)]
65
+ else:
66
+ raise error.GLError(err=EGL.eglGetError(),
67
+ baseOperation=eglQueryDevicesEXT,
68
+ result=success)
69
+
70
+
71
+ # Expose everything from upstream so that
72
+ # we can use this as a drop-in replacement for OpenGL.EGL.
73
+ # pylint: disable=wildcard-import,g-bad-import-order
74
+ from OpenGL.EGL import *
data/dm_control/_render/pyopengl/egl_renderer.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """An OpenGL renderer backed by EGL, provided through PyOpenGL."""
17
+
18
+ import atexit
19
+ import ctypes
20
+ import os
21
+
22
+ from dm_control._render import base
23
+ from dm_control._render import constants
24
+ from dm_control._render import executor
25
+
26
+ PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM)
27
+
28
+ if not PYOPENGL_PLATFORM:
29
+ os.environ[constants.PYOPENGL_PLATFORM] = constants.EGL[0]
30
+ elif PYOPENGL_PLATFORM != constants.EGL[0]:
31
+ raise ImportError(
32
+ 'Cannot use EGL rendering platform. '
33
+ 'The PYOPENGL_PLATFORM environment variable is set to {!r} '
34
+ '(should be either unset or {!r}).'
35
+ .format(PYOPENGL_PLATFORM, constants.EGL[0]))
36
+
37
+
38
+ # pylint: disable=g-import-not-at-top
39
+ from dm_control._render.pyopengl import egl_ext as EGL
40
+ from OpenGL import error
41
+
42
+
43
+ def create_initialized_headless_egl_display():
44
+ """Creates an initialized EGL display directly on a device."""
45
+ all_devices = EGL.eglQueryDevicesEXT()
46
+ selected_device = os.environ.get('MUJOCO_EGL_DEVICE_ID', None)
47
+ if selected_device is None:
48
+ candidates = all_devices
49
+ else:
50
+ device_idx = int(selected_device)
51
+ if not 0 <= device_idx < len(all_devices):
52
+ raise RuntimeError(
53
+ f'MUJOCO_EGL_DEVICE_ID must be an integer between 0 and '
54
+ f'{len(all_devices) - 1} (inclusive), got {device_idx}.')
55
+ candidates = all_devices[device_idx:device_idx + 1]
56
+ for device in candidates:
57
+ display = EGL.eglGetPlatformDisplayEXT(
58
+ EGL.EGL_PLATFORM_DEVICE_EXT, device, None)
59
+ if display != EGL.EGL_NO_DISPLAY and EGL.eglGetError() == EGL.EGL_SUCCESS:
60
+ # `eglInitialize` may or may not raise an exception on failure depending
61
+ # on how PyOpenGL is configured. We therefore catch a `GLError` and also
62
+ # manually check the output of `eglGetError()` here.
63
+ try:
64
+ initialized = EGL.eglInitialize(display, None, None)
65
+ except error.GLError:
66
+ pass
67
+ else:
68
+ if initialized == EGL.EGL_TRUE and EGL.eglGetError() == EGL.EGL_SUCCESS:
69
+ return display
70
+ return EGL.EGL_NO_DISPLAY
71
+
72
+
73
+ EGL_DISPLAY = create_initialized_headless_egl_display()
74
+ if EGL_DISPLAY == EGL.EGL_NO_DISPLAY:
75
+ raise ImportError('Cannot initialize a headless EGL display.')
76
+ atexit.register(EGL.eglTerminate, EGL_DISPLAY)
77
+
78
+
79
+ EGL_ATTRIBUTES = (
80
+ EGL.EGL_RED_SIZE, 8,
81
+ EGL.EGL_GREEN_SIZE, 8,
82
+ EGL.EGL_BLUE_SIZE, 8,
83
+ EGL.EGL_ALPHA_SIZE, 8,
84
+ EGL.EGL_DEPTH_SIZE, 24,
85
+ EGL.EGL_STENCIL_SIZE, 8,
86
+ EGL.EGL_COLOR_BUFFER_TYPE, EGL.EGL_RGB_BUFFER,
87
+ EGL.EGL_SURFACE_TYPE, EGL.EGL_PBUFFER_BIT,
88
+ EGL.EGL_RENDERABLE_TYPE, EGL.EGL_OPENGL_BIT,
89
+ EGL.EGL_NONE
90
+ )
91
+
92
+
93
+ class EGLContext(base.ContextBase):
94
+ """An OpenGL context backed by EGL."""
95
+
96
+ def __init__(self, max_width, max_height):
97
+ # EGLContext currently only works with `PassthroughRenderExecutor`.
98
+ # TODO(b/110927854) Make this work with the offloading executor.
99
+ self._context = None
100
+ super().__init__(max_width, max_height, executor.PassthroughRenderExecutor)
101
+
102
+ def _platform_init(self, unused_max_width, unused_max_height):
103
+ """Initialization this EGL context."""
104
+ num_configs = ctypes.c_long(0)
105
+ config_size = 1
106
+ # ctypes syntax for making an array of length config_size.
107
+ configs = (EGL.EGLConfig * config_size)()
108
+ EGL.eglReleaseThread()
109
+ EGL.eglChooseConfig(
110
+ EGL_DISPLAY,
111
+ EGL_ATTRIBUTES,
112
+ configs,
113
+ config_size,
114
+ num_configs)
115
+ if num_configs.value < 1:
116
+ raise RuntimeError(
117
+ 'EGL failed to find a framebuffer configuration that matches the '
118
+ 'desired attributes: {}'.format(EGL_ATTRIBUTES))
119
+ EGL.eglBindAPI(EGL.EGL_OPENGL_API)
120
+ self._context = EGL.eglCreateContext(
121
+ EGL_DISPLAY, configs[0], EGL.EGL_NO_CONTEXT, None)
122
+ if not self._context:
123
+ raise RuntimeError('Cannot create an EGL context.')
124
+
125
+ def _platform_make_current(self):
126
+ if self._context:
127
+ success = EGL.eglMakeCurrent(
128
+ EGL_DISPLAY, EGL.EGL_NO_SURFACE, EGL.EGL_NO_SURFACE, self._context)
129
+ if not success:
130
+ raise RuntimeError('Failed to make the EGL context current.')
131
+
132
+ def _platform_free(self):
133
+ """Frees resources associated with this context."""
134
+ if self._context:
135
+ current_context = EGL.eglGetCurrentContext()
136
+ if current_context and self._context.address == current_context.address:
137
+ EGL.eglMakeCurrent(EGL_DISPLAY, EGL.EGL_NO_SURFACE,
138
+ EGL.EGL_NO_SURFACE, EGL.EGL_NO_CONTEXT)
139
+ EGL.eglDestroyContext(EGL_DISPLAY, self._context)
140
+ self._context = None
data/dm_control/_render/pyopengl/osmesa_renderer.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """An OpenGL renderer backed by OSMesa."""
17
+
18
+ import os
19
+
20
+ from dm_control._render import base
21
+ from dm_control._render import constants
22
+
23
+ PYOPENGL_PLATFORM = os.environ.get(constants.PYOPENGL_PLATFORM)
24
+
25
+ if not PYOPENGL_PLATFORM:
26
+ os.environ[constants.PYOPENGL_PLATFORM] = constants.OSMESA[0]
27
+ elif PYOPENGL_PLATFORM != constants.OSMESA[0]:
28
+ raise ImportError(
29
+ 'Cannot use OSMesa rendering platform. '
30
+ 'The PYOPENGL_PLATFORM environment variable is set to {!r} '
31
+ '(should be either unset or {!r}).'
32
+ .format(PYOPENGL_PLATFORM, constants.OSMESA[0]))
33
+
34
+ # pylint: disable=g-import-not-at-top
35
+ from OpenGL import GL
36
+ from OpenGL import osmesa
37
+ from OpenGL.GL import arrays
38
+
39
+ _DEPTH_BITS = 24
40
+ _STENCIL_BITS = 8
41
+ _ACCUM_BITS = 0
42
+
43
+
44
+ class OSMesaContext(base.ContextBase):
45
+ """An OpenGL context backed by OSMesa."""
46
+
47
+ def __init__(self, *args, **kwargs):
48
+ self._context = None
49
+ super().__init__(*args, **kwargs)
50
+
51
+ def _platform_init(self, max_width, max_height):
52
+ """Initializes this OSMesa context."""
53
+ self._context = osmesa.OSMesaCreateContextExt(
54
+ osmesa.OSMESA_RGBA,
55
+ _DEPTH_BITS,
56
+ _STENCIL_BITS,
57
+ _ACCUM_BITS,
58
+ None, # sharelist
59
+ )
60
+ if not self._context:
61
+ raise RuntimeError('Failed to create OSMesa GL context.')
62
+
63
+ self._height = max_height
64
+ self._width = max_width
65
+
66
+ # Allocate a buffer to render into.
67
+ self._buffer = arrays.GLfloatArray.zeros((max_height, max_width, 4))
68
+
69
+ def _platform_make_current(self):
70
+ if self._context:
71
+ success = osmesa.OSMesaMakeCurrent(
72
+ self._context,
73
+ self._buffer,
74
+ GL.GL_FLOAT,
75
+ self._width,
76
+ self._height)
77
+ if not success:
78
+ raise RuntimeError('Failed to make OSMesa context current.')
79
+
80
+ def _platform_free(self):
81
+ """Frees resources associated with this context."""
82
+ if self._context and self._context == osmesa.OSMesaGetCurrentContext():
83
+ osmesa.OSMesaMakeCurrent(None, None, GL.GL_FLOAT, 0, 0)
84
+ osmesa.OSMesaDestroyContext(self._context)
85
+ self._buffer = None
86
+ self._context = None
data/dm_control/_render/pyopengl/osmesa_renderer_test.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for OSMesaContext."""
17
+
18
+ import unittest
19
+
20
+ from absl.testing import absltest
21
+ from dm_control import _render
22
+ import mock
23
+ from OpenGL import GL
24
+
25
+ MAX_WIDTH = 640
26
+ MAX_HEIGHT = 480
27
+
28
+ CONTEXT_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.osmesa'
29
+ GL_ARRAYS_PATH = _render.__name__ + '.pyopengl.osmesa_renderer.arrays'
30
+
31
+
32
+ @unittest.skipUnless(
33
+ _render.BACKEND == _render.constants.OSMESA,
34
+ reason='OSMesa backend not selected.')
35
+ class OSMesaContextTest(absltest.TestCase):
36
+
37
+ def test_init(self):
38
+ mock_context = mock.MagicMock()
39
+ with mock.patch(CONTEXT_PATH) as mock_osmesa:
40
+ mock_osmesa.OSMesaCreateContextExt.return_value = mock_context
41
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
42
+ self.assertIs(renderer._context, mock_context)
43
+ renderer.free()
44
+
45
+ def test_make_current(self):
46
+ mock_context = mock.MagicMock()
47
+ mock_buffer = mock.MagicMock()
48
+ with mock.patch(CONTEXT_PATH) as mock_osmesa:
49
+ with mock.patch(GL_ARRAYS_PATH) as mock_glarrays:
50
+ mock_osmesa.OSMesaCreateContextExt.return_value = mock_context
51
+ mock_glarrays.GLfloatArray.zeros.return_value = mock_buffer
52
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
53
+ with renderer.make_current():
54
+ pass
55
+ mock_osmesa.OSMesaMakeCurrent.assert_called_once_with(
56
+ mock_context, mock_buffer, GL.GL_FLOAT, MAX_WIDTH, MAX_HEIGHT)
57
+ renderer.free()
58
+
59
+ def test_freeing(self):
60
+ mock_context = mock.MagicMock()
61
+ with mock.patch(CONTEXT_PATH) as mock_osmesa:
62
+ mock_osmesa.OSMesaCreateContextExt.return_value = mock_context
63
+ renderer = _render.Renderer(MAX_WIDTH, MAX_HEIGHT)
64
+ renderer.free()
65
+ mock_osmesa.OSMesaDestroyContext.assert_called_once_with(mock_context)
66
+ self.assertIsNone(renderer._context)
67
+
68
+
69
+ if __name__ == '__main__':
70
+ absltest.main()
data/dm_control/autowrap/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
data/dm_control/autowrap/autowrap.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ r"""Automatically generates ctypes Python bindings for MuJoCo.
17
+
18
+ Parses the following MuJoCo header files:
19
+
20
+ mjdata.h
21
+ mjmodel.h
22
+ mjrender.h
23
+ mjui.h
24
+ mjvisualize.h
25
+ mjxmacro.h
26
+ mujoco.h;
27
+
28
+ generates the following Python source files:
29
+
30
+ constants.py: constants
31
+ enums.py: enums
32
+ sizes.py: size information for dynamically-shaped arrays
33
+
34
+ Example usage:
35
+
36
+ autowrap --header_paths='/path/to/mjmodel.h /path/to/mjdata.h ...' \
37
+ --output_dir=/path/to/mjbindings
38
+ """
39
+
40
+ import collections
41
+ import io
42
+ import os
43
+
44
+ from absl import app
45
+ from absl import flags
46
+ from absl import logging
47
+ from dm_control.autowrap import binding_generator
48
+ from dm_control.autowrap import codegen_util
49
+
50
+ _MJMODEL_H = "mjmodel.h"
51
+ _MJXMACRO_H = "mjxmacro.h"
52
+
53
+ FLAGS = flags.FLAGS
54
+
55
+ flags.DEFINE_spaceseplist(
56
+ "header_paths", None,
57
+ "Space-separated list of paths to MuJoCo header files.")
58
+
59
+ flags.DEFINE_string("output_dir", None,
60
+ "Path to output directory for wrapper source files.")
61
+
62
+
63
+ def main(unused_argv):
64
+ special_header_paths = {}
65
+
66
+ # Get the path to the mjmodel and mjxmacro header files.
67
+ # These header files need special handling.
68
+ for header in (_MJMODEL_H, _MJXMACRO_H):
69
+ for path in FLAGS.header_paths:
70
+ if path.endswith(header):
71
+ special_header_paths[header] = path
72
+ break
73
+ if header not in special_header_paths:
74
+ logging.fatal("List of inputs must contain a path to %s", header)
75
+
76
+ # Make sure mjmodel.h is parsed first, since it is included by other headers.
77
+ srcs = codegen_util.UniqueOrderedDict()
78
+ sorted_header_paths = sorted(FLAGS.header_paths)
79
+ sorted_header_paths.remove(special_header_paths[_MJMODEL_H])
80
+ sorted_header_paths.insert(0, special_header_paths[_MJMODEL_H])
81
+ for p in sorted_header_paths:
82
+ with io.open(p, "r", errors="ignore") as f:
83
+ srcs[p] = f.read()
84
+
85
+ # consts_dict should be a codegen_util.UniqueOrderedDict.
86
+ # This is a temporary workaround due to the fact that the parser does not yet
87
+ # handle nested `#if define(predicate)` blocks, which results in some
88
+ # constants being parsed twice. We therefore can't enforce the uniqueness of
89
+ # the keys in `consts_dict`. As of MuJoCo v1.30 there is only a single problem
90
+ # block beginning on line 10 in mujoco.h, and a single constant is affected
91
+ # (MJAPI).
92
+ consts_dict = collections.OrderedDict()
93
+
94
+ # These are commented in `mjdata.h` but have no macros in `mjxmacro.h`.
95
+ hints_dict = codegen_util.UniqueOrderedDict({"buffer": ("nbuffer",),
96
+ "stack": ("narena",)})
97
+
98
+ parser = binding_generator.BindingGenerator(
99
+ consts_dict=consts_dict, hints_dict=hints_dict)
100
+
101
+ # Parse enums.
102
+ for pth, src in srcs.items():
103
+ if pth is not special_header_paths[_MJXMACRO_H]:
104
+ parser.parse_enums(src)
105
+
106
+ # Parse constants and type declarations.
107
+ for pth, src in srcs.items():
108
+ if pth is not special_header_paths[_MJXMACRO_H]:
109
+ parser.parse_consts_typedefs(src)
110
+
111
+ # Get shape hints from mjxmacro.h.
112
+ parser.parse_hints(srcs[special_header_paths[_MJXMACRO_H]])
113
+
114
+ # Create the output directory if it doesn't already exist.
115
+ if not os.path.exists(FLAGS.output_dir):
116
+ os.makedirs(FLAGS.output_dir)
117
+
118
+ # Generate Python source files and write them to the output directory.
119
+ parser.write_consts(os.path.join(FLAGS.output_dir, "constants.py"))
120
+ parser.write_enums(os.path.join(FLAGS.output_dir, "enums.py"))
121
+ parser.write_index_dict(os.path.join(FLAGS.output_dir, "sizes.py"))
122
+
123
+ if __name__ == "__main__":
124
+ flags.mark_flag_as_required("header_paths")
125
+ flags.mark_flag_as_required("output_dir")
126
+ app.run(main)
data/dm_control/autowrap/binding_generator.py ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Parses MuJoCo header files and generates Python bindings."""
17
+
18
+ import os
19
+ import pprint
20
+ import textwrap
21
+
22
+ from absl import logging
23
+ from dm_control.autowrap import codegen_util
24
+ from dm_control.autowrap import header_parsing
25
+ import pyparsing
26
+
27
+
28
+ class BindingGenerator:
29
+ """Parses declarations from MuJoCo headers and generates Python bindings."""
30
+
31
+ def __init__(self,
32
+ enums_dict=None,
33
+ consts_dict=None,
34
+ typedefs_dict=None,
35
+ hints_dict=None,
36
+ index_dict=None):
37
+ """Constructs a new HeaderParser instance.
38
+
39
+ The optional arguments listed below can be used to passing in dict-like
40
+ objects specifying pre-defined declarations. By default empty
41
+ UniqueOrderedDicts will be instantiated and then populated according to the
42
+ contents of the headers.
43
+
44
+ Args:
45
+ enums_dict: Nested mappings from {enum_name: {member_name: value}}.
46
+ consts_dict: Mapping from {const_name: value}.
47
+ typedefs_dict: Mapping from {type_name: ctypes_typename}.
48
+ hints_dict: Mapping from {var_name: shape_tuple}.
49
+ index_dict: Mapping from {lowercase_struct_name: {var_name: shape_tuple}}.
50
+ """
51
+ self.enums_dict = (enums_dict if enums_dict is not None
52
+ else codegen_util.UniqueOrderedDict())
53
+ self.consts_dict = (consts_dict if consts_dict is not None
54
+ else codegen_util.UniqueOrderedDict())
55
+ self.typedefs_dict = (typedefs_dict if typedefs_dict is not None
56
+ else codegen_util.UniqueOrderedDict())
57
+ self.hints_dict = (hints_dict if hints_dict is not None
58
+ else codegen_util.UniqueOrderedDict())
59
+ self.index_dict = (index_dict if index_dict is not None
60
+ else codegen_util.UniqueOrderedDict())
61
+
62
+ def get_consts_and_enums(self):
63
+ consts_and_enums = self.consts_dict.copy()
64
+ for enum in self.enums_dict.values():
65
+ consts_and_enums.update(enum)
66
+ return consts_and_enums
67
+
68
+ def resolve_size(self, old_size):
69
+ """Resolves an array size identifier.
70
+
71
+ The following conversions will be attempted:
72
+
73
+ * If `old_size` is an integer it will be returned as-is.
74
+ * If `old_size` is a string of the form `"3"` it will be cast to an int.
75
+ * If `old_size` is a string in `self.consts_dict` then the value of the
76
+ constant will be returned.
77
+ * If `old_size` is a string of the form `"3*constant_name"` then the
78
+ result of `3*constant_value` will be returned.
79
+ * If `old_size` is a string that does not specify an int constant and
80
+ cannot be cast to an int (e.g. an identifier for a dynamic dimension,
81
+ such as `"ncontact"`) then it will be returned as-is.
82
+
83
+ Args:
84
+ old_size: An int or string.
85
+
86
+ Returns:
87
+ An int or string.
88
+ """
89
+ if isinstance(old_size, int):
90
+ return old_size # If it's already an int then there's nothing left to do
91
+ elif "*" in old_size:
92
+ # If it's a string specifying a product (such as "2*mjMAXLINEPNT"),
93
+ # recursively resolve the components to ints and calculate the result.
94
+ size = 1
95
+ sizes = []
96
+ is_int = True
97
+ for part in old_size.split("*"):
98
+ dim = self.resolve_size(part)
99
+ sizes.append(dim)
100
+ if not isinstance(dim, int):
101
+ is_int = False
102
+ else:
103
+ size *= dim
104
+ if is_int:
105
+ return size
106
+ else:
107
+ return tuple(sizes)
108
+ else:
109
+ # Recursively dereference any sizes declared in header macros
110
+ size = codegen_util.recursive_dict_lookup(old_size,
111
+ self.get_consts_and_enums())
112
+ # Try to coerce the result to an int, return a string if this fails
113
+ return codegen_util.try_coerce_to_num(size, try_types=(int,))
114
+
115
+ def get_shape_tuple(self, old_size, squeeze=False):
116
+ """Generates a shape tuple from parser results.
117
+
118
+ Args:
119
+ old_size: Either a `pyparsing.ParseResults`, or a valid int or string
120
+ input to `self.resolve_size` (see method docstring for further details).
121
+ squeeze: If True, any dimensions that are statically defined as 1 will be
122
+ removed from the shape tuple.
123
+
124
+ Returns:
125
+ A shape tuple containing ints for dimensions that are statically defined,
126
+ and string size identifiers for dimensions that can only be determined at
127
+ runtime.
128
+ """
129
+ if isinstance(old_size, pyparsing.ParseResults):
130
+ # For multi-dimensional arrays, convert each dimension separately
131
+ shape = tuple(self.resolve_size(dim) for dim in old_size)
132
+ else:
133
+ shape = (self.resolve_size(old_size),)
134
+ if squeeze:
135
+ shape = tuple(d for d in shape if d != 1) # Remove singleton dimensions
136
+ return shape
137
+
138
+ def resolve_typename(self, old_ctypes_typename):
139
+ """Gets a qualified ctypes typename from typedefs_dict and C_TO_CTYPES."""
140
+
141
+ # Recursively dereference any typenames declared in self.typedefs_dict
142
+ new_ctypes_typename = codegen_util.recursive_dict_lookup(
143
+ old_ctypes_typename, self.typedefs_dict)
144
+
145
+ # Try to convert to a ctypes native typename
146
+ new_ctypes_typename = header_parsing.C_TO_CTYPES.get(
147
+ new_ctypes_typename, new_ctypes_typename)
148
+
149
+ if new_ctypes_typename == old_ctypes_typename:
150
+ logging.warning("Could not resolve typename '%s'", old_ctypes_typename)
151
+
152
+ return new_ctypes_typename
153
+
154
+ # Parsing functions.
155
+ # ----------------------------------------------------------------------------
156
+
157
+ def parse_hints(self, xmacro_src):
158
+ """Parses mjxmacro.h, update self.hints_dict."""
159
+ parser = header_parsing.XMACRO
160
+ for tokens, _, _ in parser.scanString(xmacro_src):
161
+ for xmacro in tokens:
162
+ if not (
163
+ xmacro.name.startswith("MJMODEL")
164
+ or xmacro.name.startswith("MJDATA")
165
+ ):
166
+ continue
167
+ for member in xmacro.members:
168
+ if not hasattr(member, "name") or not member.name:
169
+ continue
170
+ # "Squeeze out" singleton dimensions.
171
+ shape = self.get_shape_tuple(member.dims, squeeze=True)
172
+ self.hints_dict.update({member.name: shape})
173
+
174
+ if codegen_util.is_macro_pointer(xmacro.name):
175
+ struct_name = codegen_util.macro_struct_name(xmacro.name)
176
+ if struct_name not in self.index_dict:
177
+ self.index_dict[struct_name] = {}
178
+
179
+ self.index_dict[struct_name].update({member.name: shape})
180
+
181
+ def parse_enums(self, src):
182
+ """Parses mj*.h, update self.enums_dict."""
183
+ parser = header_parsing.ENUM_DECL
184
+ for tokens, _, _ in parser.scanString(src):
185
+ for enum in tokens:
186
+ members = codegen_util.UniqueOrderedDict()
187
+ value = 0
188
+ for member in enum.members:
189
+ # Leftward bitshift
190
+ if member.bit_lshift_a:
191
+ value = int(member.bit_lshift_a) << int(member.bit_lshift_b)
192
+ # Assignment
193
+ elif member.value:
194
+ value = int(member.value)
195
+ # Implicit count
196
+ else:
197
+ value += 1
198
+ members.update({member.name: value})
199
+ self.enums_dict.update({enum.name: members})
200
+
201
+ def parse_consts_typedefs(self, src):
202
+ """Updates self.consts_dict, self.typedefs_dict."""
203
+ parser = (header_parsing.COND_DECL |
204
+ header_parsing.UNCOND_DECL)
205
+ for tokens, _, _ in parser.scanString(src):
206
+ self.recurse_into_conditionals(tokens)
207
+
208
+ def recurse_into_conditionals(self, tokens):
209
+ """Called recursively within nested #if(n)def... #else... #endif blocks."""
210
+ for token in tokens:
211
+ # Another nested conditional block
212
+ if token.predicate:
213
+ if (token.predicate in self.get_consts_and_enums()
214
+ and self.get_consts_and_enums()[token.predicate]):
215
+ self.recurse_into_conditionals(token.if_true)
216
+ else:
217
+ self.recurse_into_conditionals(token.if_false)
218
+ # One or more declarations
219
+ else:
220
+ if token.typename:
221
+ self.typedefs_dict.update({token.name: token.typename})
222
+ elif token.value:
223
+ value = codegen_util.try_coerce_to_num(token.value)
224
+ # Avoid adding function aliases.
225
+ if isinstance(value, str):
226
+ continue
227
+ else:
228
+ self.consts_dict.update({token.name: value})
229
+ else:
230
+ self.consts_dict.update({token.name: True})
231
+
232
+ # Code generation methods
233
+ # ----------------------------------------------------------------------------
234
+
235
+ def make_header(self, imports=()):
236
+ """Returns a header string for an auto-generated Python source file."""
237
+ docstring = textwrap.dedent("""
238
+ \"\"\"Automatically generated by {scriptname:}.
239
+
240
+ MuJoCo header version: {mujoco_version:}
241
+ \"\"\"
242
+ """.format(scriptname=os.path.split(__file__)[-1],
243
+ mujoco_version=self.consts_dict["mjVERSION_HEADER"]))
244
+ docstring = docstring[1:] # Strip the leading line break.
245
+ return "\n".join([docstring] + list(imports) + ["\n"])
246
+
247
+ def write_consts(self, fname):
248
+ """Write constants."""
249
+ imports = [
250
+ "# pylint: disable=invalid-name",
251
+ ]
252
+ with open(fname, "w") as f:
253
+ f.write(self.make_header(imports))
254
+ f.write(codegen_util.comment_line("Constants") + "\n")
255
+ for name, value in self.consts_dict.items():
256
+ f.write("{0} = {1}\n".format(name, value))
257
+ f.write("\n" + codegen_util.comment_line("End of generated code"))
258
+
259
+ def write_enums(self, fname):
260
+ """Write enum definitions."""
261
+ with open(fname, "w") as f:
262
+ imports = [
263
+ "import collections",
264
+ "# pylint: disable=invalid-name",
265
+ "# pylint: disable=line-too-long",
266
+ ]
267
+ f.write(self.make_header(imports))
268
+ f.write(codegen_util.comment_line("Enums"))
269
+ for enum_name, members in self.enums_dict.items():
270
+ fields = ["\"{}\"".format(name) for name in members.keys()]
271
+ values = [str(value) for value in members.values()]
272
+ s = textwrap.dedent("""
273
+ {0} = collections.namedtuple(
274
+ "{0}",
275
+ [{1}]
276
+ )({2})
277
+ """).format(enum_name, ",\n ".join(fields), ", ".join(values))
278
+ f.write(s)
279
+ f.write("\n" + codegen_util.comment_line("End of generated code"))
280
+
281
+ def write_index_dict(self, fname):
282
+ """Write file containing array shape information for indexing."""
283
+ pp = pprint.PrettyPrinter()
284
+ output_string = pp.pformat(dict(self.index_dict))
285
+ indent = codegen_util.Indenter()
286
+ imports = [
287
+ "# pylint: disable=bad-continuation",
288
+ "# pylint: disable=line-too-long",
289
+ ]
290
+ with open(fname, "w") as f:
291
+ f.write(self.make_header(imports))
292
+ f.write("array_sizes = (\n")
293
+ with indent:
294
+ f.write(output_string)
295
+ f.write("\n)")
296
+ f.write("\n" + codegen_util.comment_line("End of generated code"))
data/dm_control/autowrap/codegen_util.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Misc helper functions needed by autowrap.py."""
17
+
18
+ import collections
19
+
20
+ _MJXMACRO_SUFFIX = "_POINTERS"
21
+
22
+
23
+ class Indenter:
24
+ r"""Callable context manager for tracking string indentation levels.
25
+
26
+ Example usage:
27
+
28
+ ```python
29
+ idt = Indenter()
30
+ s = idt("level 0\n")
31
+ with idt:
32
+ s += idt("level 1\n")
33
+ with idt:
34
+ s += idt("level 2\n")
35
+ s += idt("level 1 again\n")
36
+ s += idt("back to level 0\n")
37
+ print(s)
38
+ ```
39
+ """
40
+
41
+ def __init__(self, level=0, indent_str=" "):
42
+ """Initializes an Indenter.
43
+
44
+ Args:
45
+ level: The initial indentation level.
46
+ indent_str: The string used to indent each line.
47
+ """
48
+ self.indent_str = indent_str
49
+ self.level = level
50
+
51
+ def __enter__(self):
52
+ self.level += 1
53
+ return self
54
+
55
+ def __exit__(self, type_, value, traceback):
56
+ self.level -= 1
57
+
58
+ def __call__(self, string):
59
+ return indent(string, self.level, self.indent_str)
60
+
61
+
62
+ def indent(s, n=1, indent_str=" "):
63
+ """Inserts `n * indent_str` at the start of each non-empty line in `s`."""
64
+ p = n * indent_str
65
+ return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True))
66
+
67
+
68
+ class UniqueOrderedDict(collections.OrderedDict):
69
+ """Subclass of `OrderedDict` that enforces the uniqueness of keys."""
70
+
71
+ def __setitem__(self, k, v):
72
+ existing_v = self.get(k)
73
+ if existing_v is None:
74
+ super().__setitem__(k, v)
75
+ elif v != existing_v:
76
+ raise ValueError("Key '{}' already exists.".format(k))
77
+
78
+
79
+ def macro_struct_name(name, suffix=None):
80
+ """Converts mjxmacro struct names, e.g. "MJDATA_POINTERS" to "mjdata"."""
81
+ if name.startswith("MJMODEL_POINTERS"):
82
+ return "mjmodel"
83
+ if suffix is None:
84
+ suffix = _MJXMACRO_SUFFIX
85
+ if name.endswith(suffix):
86
+ return name[:-len(suffix)].lower()
87
+ return name.lower()
88
+
89
+
90
+ def is_macro_pointer(name):
91
+ """Returns True if the mjxmacro struct name contains pointer sizes."""
92
+ return name.endswith(_MJXMACRO_SUFFIX) or name.startswith("MJMODEL_POINTERS")
93
+
94
+
95
+ def try_coerce_to_num(s, try_types=(int, float)):
96
+ """Try to coerce string to Python numeric type, return None if empty."""
97
+ if not s:
98
+ return None
99
+ for try_type in try_types:
100
+ try:
101
+ return try_type(s.rstrip("UuFf"))
102
+ except (ValueError, AttributeError):
103
+ continue
104
+ return s
105
+
106
+
107
+ def recursive_dict_lookup(key, try_dict, max_depth=10):
108
+ """Recursively map dictionary keys to values."""
109
+ if max_depth < 0:
110
+ raise KeyError("Maximum recursion depth exceeded")
111
+ while key in try_dict:
112
+ key = try_dict[key]
113
+ return recursive_dict_lookup(key, try_dict, max_depth - 1)
114
+ return key
115
+
116
+
117
+ def comment_line(string, width=79, fill_char="-"):
118
+ """Wraps `string` in a padded comment line."""
119
+ return "# {0:{2}^{1}}\n".format(string, width - 2, fill_char)
data/dm_control/autowrap/header_parsing.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2017 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """pyparsing definitions and helper functions for parsing MuJoCo headers."""
17
+
18
+ import pyparsing as pp
19
+
20
+
21
+ # NB: Don't enable parser memoization (`pp.ParserElement.enablePackrat()`),
22
+ # since this results in a ~6x slowdown.
23
+
24
+
25
+ NONE = "None"
26
+ CTYPES_CHAR = "ctypes.c_char"
27
+
28
+ C_TO_CTYPES = {
29
+ # integers
30
+ "int": "ctypes.c_int",
31
+ "unsigned int": "ctypes.c_uint",
32
+ "char": CTYPES_CHAR,
33
+ "unsigned char": "ctypes.c_ubyte",
34
+ "size_t": "ctypes.c_size_t",
35
+ # floats
36
+ "float": "ctypes.c_float",
37
+ "double": "ctypes.c_double",
38
+ # pointers
39
+ "void": NONE,
40
+ }
41
+
42
+ CTYPES_PTRS = {NONE: "ctypes.c_void_p"}
43
+
44
+ CTYPES_TO_NUMPY = {
45
+ # integers
46
+ "ctypes.c_int": "np.intc",
47
+ "ctypes.c_uint": "np.uintc",
48
+ "ctypes.c_ubyte": "np.ubyte",
49
+ # floats
50
+ "ctypes.c_float": "np.float32",
51
+ "ctypes.c_double": "np.float64",
52
+ }
53
+
54
+ # Helper functions for constructing recursive parsers.
55
+ # ------------------------------------------------------------------------------
56
+
57
+
58
+ def _nested_scopes(opening, closing, body):
59
+ """Constructs a parser for (possibly nested) scopes."""
60
+ scope = pp.Forward()
61
+ scope << pp.Group( # pylint: disable=expression-not-assigned
62
+ opening +
63
+ pp.ZeroOrMore(body | scope)("members") +
64
+ closing)
65
+ return scope
66
+
67
+
68
+ def _nested_if_else(if_, pred, else_, endif, match_if_true, match_if_false):
69
+ """Constructs a parser for (possibly nested) if...(else)...endif blocks."""
70
+ ifelse = pp.Forward()
71
+ ifelse << pp.Group( # pylint: disable=expression-not-assigned
72
+ if_ +
73
+ pred("predicate") +
74
+ pp.ZeroOrMore(match_if_true | ifelse)("if_true") +
75
+ pp.Optional(else_ +
76
+ pp.ZeroOrMore(match_if_false | ifelse)("if_false")) +
77
+ endif)
78
+ return ifelse
79
+
80
+
81
+ def _nested_ifn_else(ifn_, pred, else_, endif, match_if_true, match_if_false):
82
+ """Constructs a parser for (possibly nested) if...(else)...endif blocks."""
83
+ ifnelse = pp.Forward()
84
+ ifnelse << pp.Group( # pylint: disable=expression-not-assigned
85
+ ifn_ +
86
+ pred("predicate") +
87
+ pp.ZeroOrMore(match_if_true | ifnelse)("if_false") +
88
+ pp.Optional(else_ +
89
+ pp.ZeroOrMore(match_if_false | ifnelse)("if_true")) +
90
+ endif)
91
+ return ifnelse
92
+
93
+
94
+ # Some common string patterns to suppress.
95
+ # ------------------------------------------------------------------------------
96
+ (LPAREN, RPAREN, LBRACK, RBRACK, LBRACE, RBRACE, SEMI, COMMA, EQUAL, FSLASH,
97
+ BSLASH) = list(map(pp.Suppress, "()[]{};,=/\\"))
98
+ X = (pp.Keyword("X") | pp.Keyword("XMJV") | pp.Keyword("XNV")).suppress()
99
+ EOL = pp.LineEnd().suppress()
100
+
101
+ # Comments, continuation.
102
+ # ------------------------------------------------------------------------------
103
+ COMMENT = pp.Combine(
104
+ pp.Suppress("//") +
105
+ pp.Optional(pp.White()).suppress() +
106
+ pp.SkipTo(pp.LineEnd()))
107
+
108
+ MULTILINE_COMMENT = pp.delimitedList(
109
+ COMMENT.copy().setWhitespaceChars(" \t"), delim=EOL)
110
+
111
+ CONTINUATION = (BSLASH + pp.LineEnd()).suppress()
112
+
113
+ # Preprocessor directives.
114
+ # ------------------------------------------------------------------------------
115
+ DEFINE = pp.Keyword("#define").suppress()
116
+ IFDEF = pp.Keyword("#ifdef").suppress()
117
+ IFNDEF = pp.Keyword("#ifndef").suppress()
118
+ ELSE = pp.Keyword("#else").suppress()
119
+ ENDIF = pp.Keyword("#endif").suppress()
120
+
121
+ # Variable names, types, literals etc.
122
+ # ------------------------------------------------------------------------------
123
+ NAME = pp.Word(pp.alphanums + "_")
124
+ INT = pp.Word(pp.nums + "UuLl")
125
+ FLOAT = pp.Word(pp.nums + ".+-EeFf")
126
+ NUMBER = FLOAT | INT
127
+
128
+ # Dimensions can be of the form `[3]`, `[constant_name]` or `[2*constant_name]`
129
+ ARRAY_DIM = pp.Combine(
130
+ LBRACK +
131
+ (INT | NAME) +
132
+ pp.Optional(pp.Literal("*")) +
133
+ pp.Optional(INT | NAME) +
134
+ RBRACK)
135
+
136
+ PTR = pp.Literal("*")
137
+ EXTERN = pp.Keyword("extern")
138
+ NATIVE_TYPENAME = pp.MatchFirst([pp.Keyword(n) for n in C_TO_CTYPES.keys()])
139
+
140
+ # Macros.
141
+ # ------------------------------------------------------------------------------
142
+
143
+ HDR_GUARD = DEFINE + "THIRD_PARTY_MUJOCO_HDRS_"
144
+
145
+ # e.g. "#define mjUSEDOUBLE"
146
+ DEF_FLAG = pp.Group(
147
+ DEFINE +
148
+ NAME("name") +
149
+ (COMMENT("comment") | EOL)).ignore(HDR_GUARD)
150
+
151
+ # e.g. "#define mjMINVAL 1E-14 // minimum value in any denominator"
152
+ DEF_CONST = pp.Group(
153
+ DEFINE +
154
+ NAME("name") +
155
+ (NUMBER | NAME)("value") +
156
+ (COMMENT("comment") | EOL))
157
+
158
+ # e.g. "X( mjtNum*, name_textadr, ntext, 1 )"
159
+ XDIM = pp.delimitedList(
160
+ (
161
+ pp.Suppress(pp.Keyword("MJ_M") + LPAREN) +
162
+ NAME +
163
+ pp.Suppress(RPAREN)
164
+ ) | NAME | INT, delim="*", combine=True)
165
+ XMEMBER = pp.Group(
166
+ X +
167
+ LPAREN +
168
+ (NATIVE_TYPENAME | NAME)("typename") +
169
+ pp.Optional(PTR("ptr")) +
170
+ COMMA +
171
+ NAME("name") +
172
+ COMMA +
173
+ pp.delimitedList(XDIM, delim=COMMA)("dims") +
174
+ RPAREN)
175
+
176
+ XMACRO_LINE = XMEMBER | NAME
177
+ XMACRO = pp.Group(
178
+ pp.Optional(COMMENT("comment")) +
179
+ DEFINE +
180
+ NAME("name") +
181
+ CONTINUATION +
182
+ pp.delimitedList(XMACRO_LINE, delim=CONTINUATION)("members"))
183
+
184
+
185
+ # Type/variable declarations.
186
+ # ------------------------------------------------------------------------------
187
+ TYPEDEF = pp.Keyword("typedef").suppress()
188
+ STRUCT = pp.Keyword("struct")
189
+ UNION = pp.Keyword("union")
190
+ ENUM = pp.Keyword("enum").suppress()
191
+
192
+ # e.g. "typedef unsigned char mjtByte; // used for true/false"
193
+ TYPE_DECL = pp.Group(
194
+ TYPEDEF +
195
+ pp.Optional(STRUCT) +
196
+ (NATIVE_TYPENAME | NAME)("typename") +
197
+ pp.Optional(PTR("ptr")) +
198
+ NAME("name") +
199
+ SEMI +
200
+ pp.Optional(COMMENT("comment")))
201
+
202
+ # Declarations of flags/constants/types.
203
+ UNCOND_DECL = DEF_FLAG | DEF_CONST | TYPE_DECL
204
+
205
+ # Declarations inside (possibly nested) #if(n)def... #else... #endif... blocks.
206
+ COND_DECL = _nested_if_else(
207
+ IFDEF, NAME, ELSE, ENDIF, UNCOND_DECL, UNCOND_DECL
208
+ ) | _nested_ifn_else(IFNDEF, NAME, ELSE, ENDIF, UNCOND_DECL, UNCOND_DECL)
209
+ # Note: this doesn't work for '#if defined(FLAG)' blocks
210
+
211
+ # e.g. "mjtNum gravity[3]; // gravitational acceleration"
212
+ STRUCT_MEMBER = pp.Group(
213
+ pp.Optional(STRUCT("struct")) +
214
+ (NATIVE_TYPENAME | NAME)("typename") +
215
+ pp.Optional(PTR("ptr")) +
216
+ NAME("name") +
217
+ pp.ZeroOrMore(ARRAY_DIM)("size") +
218
+ SEMI +
219
+ pp.Optional(COMMENT("comment")))
220
+
221
+ # Struct declaration within a union (non-nested).
222
+ UNION_STRUCT_DECL = pp.Group(
223
+ STRUCT("struct") +
224
+ pp.Optional(NAME("typename")) +
225
+ pp.Optional(COMMENT("comment")) +
226
+ LBRACE +
227
+ pp.OneOrMore(STRUCT_MEMBER)("members") +
228
+ RBRACE +
229
+ pp.Optional(NAME("name")) +
230
+ SEMI)
231
+
232
+ ANONYMOUS_UNION_DECL = pp.Group(
233
+ pp.Optional(MULTILINE_COMMENT("comment")) +
234
+ UNION("anonymous_union") +
235
+ LBRACE +
236
+ pp.OneOrMore(
237
+ UNION_STRUCT_DECL |
238
+ STRUCT_MEMBER |
239
+ COMMENT.suppress())("members") +
240
+ RBRACE +
241
+ SEMI)
242
+
243
+ # Multiple (possibly nested) struct declarations.
244
+ NESTED_STRUCTS = _nested_scopes(
245
+ opening=(STRUCT +
246
+ pp.Optional(NAME("typename")) +
247
+ pp.Optional(COMMENT("comment")) +
248
+ LBRACE),
249
+ closing=(RBRACE + pp.Optional(NAME("name")) + SEMI),
250
+ body=pp.OneOrMore(
251
+ STRUCT_MEMBER |
252
+ ANONYMOUS_UNION_DECL |
253
+ COMMENT.suppress())("members"))
254
+
255
+ BIT_LSHIFT = INT("bit_lshift_a") + pp.Suppress("<<") + INT("bit_lshift_b")
256
+
257
+ ENUM_LINE = pp.Group(
258
+ NAME("name") +
259
+ pp.Optional(EQUAL + (INT("value") ^ BIT_LSHIFT)) +
260
+ pp.Optional(COMMA) +
261
+ pp.Optional(COMMENT("comment")))
262
+
263
+ ENUM_DECL = pp.Group(
264
+ TYPEDEF +
265
+ ENUM +
266
+ NAME("typename") +
267
+ pp.Optional(COMMENT("comment")) +
268
+ LBRACE +
269
+ pp.OneOrMore(ENUM_LINE | COMMENT.suppress())("members") +
270
+ RBRACE +
271
+ pp.Optional(NAME("name")) +
272
+ SEMI)
273
+
274
+ # Function declarations.
275
+ # ------------------------------------------------------------------------------
276
+ MJAPI = pp.Keyword("MJAPI").suppress()
277
+ CONST = pp.Keyword("const")
278
+ VOID = pp.Group(pp.Keyword("void") + ~PTR).suppress()
279
+
280
+ ARG = pp.Group(
281
+ pp.Optional(CONST("is_const")) +
282
+ (NATIVE_TYPENAME | NAME)("typename") +
283
+ pp.Optional(PTR("ptr")) +
284
+ NAME("name") +
285
+ pp.Optional(ARRAY_DIM("size")))
286
+
287
+ RET = pp.Group(
288
+ pp.Optional(CONST("is_const")) +
289
+ (NATIVE_TYPENAME | NAME)("typename") +
290
+ pp.Optional(PTR("ptr")))
291
+
292
+ FUNCTION_DECL = (
293
+ (VOID | RET("return_value")) +
294
+ NAME("name") +
295
+ LPAREN +
296
+ (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) +
297
+ RPAREN +
298
+ SEMI)
299
+
300
+ MJAPI_FUNCTION_DECL = pp.Group(
301
+ pp.Optional(MULTILINE_COMMENT("comment")) +
302
+ pp.LineStart() +
303
+ MJAPI +
304
+ FUNCTION_DECL)
305
+
306
+ # e.g.
307
+ # // predicate function: set enable/disable based on item category
308
+ # typedef int (*mjfItemEnable)(int category, void* data);
309
+ FUNCTION_PTR_TYPE_DECL = pp.Group(
310
+ pp.Optional(MULTILINE_COMMENT("comment")) +
311
+ TYPEDEF +
312
+ RET("return_type") +
313
+ LPAREN +
314
+ PTR +
315
+ NAME("typename") +
316
+ RPAREN +
317
+ LPAREN +
318
+ (VOID | pp.delimitedList(ARG, delim=COMMA)("arguments")) +
319
+ RPAREN +
320
+ SEMI)
321
+
322
+ # Global variables.
323
+ # ------------------------------------------------------------------------------
324
+
325
+ MJAPI_STRING_ARRAY = (
326
+ MJAPI +
327
+ EXTERN +
328
+ CONST +
329
+ pp.Keyword("char") +
330
+ PTR +
331
+ NAME("name") +
332
+ pp.OneOrMore(ARRAY_DIM)("dims") +
333
+ SEMI)
334
+
335
+ MJAPI_FUNCTION_PTR = MJAPI + EXTERN + NAME("typename") + NAME("name") + SEMI
data/dm_control/blender/fake_core/bpy.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Fake Blender bpy module."""
17
+
18
+ from __future__ import annotations # postponed evaluation of annotations
19
+
20
+ from typing import Any, Collection, Sequence
21
+
22
+ from dm_control.blender.fake_core import mathutils
23
+
24
+ # pylint: disable=invalid-name
25
+ # pylint: disable=missing-class-docstring
26
+
27
+
28
+ class WindowManager:
29
+
30
+ def progress_begin(self, start: int, end: int):
31
+ pass
32
+
33
+ def progress_update(self, steps_done: int):
34
+ pass
35
+
36
+ def progress_end(self):
37
+ pass
38
+
39
+
40
+ class context:
41
+
42
+ @property
43
+ def window_manager(self) -> WindowManager:
44
+ return WindowManager()
45
+
46
+ @staticmethod
47
+ def evaluated_depsgraph_get():
48
+ pass
49
+
50
+
51
+ class types:
52
+
53
+ class Constraint:
54
+
55
+ @property
56
+ def name(self):
57
+ pass
58
+
59
+ @property
60
+ def owner_space(self):
61
+ pass
62
+
63
+ class Scene:
64
+ pass
65
+
66
+ class Object:
67
+
68
+ @property
69
+ def name(self) -> str:
70
+ raise NotImplementedError()
71
+
72
+ @property
73
+ def parent(self) -> types.Object | None:
74
+ pass
75
+
76
+ @property
77
+ def parent_bone(self) -> types.Bone | None:
78
+ pass
79
+
80
+ @property
81
+ def data(self):
82
+ pass
83
+
84
+ @property
85
+ def pose(self):
86
+ pass
87
+
88
+ @property
89
+ def matrix_world(self) -> mathutils.Matrix:
90
+ raise NotImplementedError()
91
+
92
+ @matrix_world.setter
93
+ def matrix_world(self, _) -> mathutils.Matrix:
94
+ raise NotImplementedError()
95
+
96
+ def select_set(self, _):
97
+ pass
98
+
99
+ def to_mesh(self):
100
+ pass
101
+
102
+ def evaluated_get(self, _) -> types.Object:
103
+ pass
104
+
105
+ @property
106
+ def mode(self) -> str:
107
+ return 'OBJECT'
108
+
109
+ @property
110
+ def type(self):
111
+ pass
112
+
113
+ def update_from_editmode(self):
114
+ pass
115
+
116
+ class Bone:
117
+
118
+ @property
119
+ def name(self) -> str:
120
+ raise NotImplementedError()
121
+
122
+ @property
123
+ def parent(self) -> types.Bone | None:
124
+ pass
125
+
126
+ @property
127
+ def matrix_local(self) -> mathutils.Matrix:
128
+ raise NotImplementedError()
129
+
130
+ @property
131
+ def matrix(self) -> mathutils.Matrix:
132
+ raise NotImplementedError()
133
+
134
+ class bpy_struct:
135
+ pass
136
+
137
+ class Context:
138
+
139
+ @property
140
+ def scene(self) -> types.Scene:
141
+ pass
142
+
143
+ class Light:
144
+
145
+ @property
146
+ def type(self):
147
+ pass
148
+
149
+ @property
150
+ def use_shadow(self):
151
+ pass
152
+
153
+ @property
154
+ def color(self) -> mathutils.Color:
155
+ raise NotImplementedError()
156
+
157
+ @property
158
+ def linear_attenuation(self):
159
+ pass
160
+
161
+ @property
162
+ def quadratic_attenuation(self):
163
+ pass
164
+
165
+ class LimitRotationConstraint(Constraint):
166
+ pass
167
+
168
+ class LimitLocationConstraint(Constraint):
169
+ pass
170
+
171
+ class Material:
172
+
173
+ @property
174
+ def name(self) -> str:
175
+ raise NotImplementedError()
176
+
177
+ @property
178
+ def specular_intensity(self):
179
+ pass
180
+
181
+ @property
182
+ def metallic(self):
183
+ pass
184
+
185
+ @property
186
+ def roughness(self) -> float:
187
+ raise NotImplementedError()
188
+
189
+ @property
190
+ def diffuse_color(self) -> Sequence[float]:
191
+ raise NotImplementedError()
192
+
193
+ class Mesh:
194
+
195
+ @property
196
+ def name(self) -> str:
197
+ raise NotImplementedError()
198
+
199
+ def calc_loop_triangles(self):
200
+ pass
201
+
202
+ @property
203
+ def uv_layers(self) -> Any:
204
+ raise NotImplementedError()
205
+
206
+ @property
207
+ def loop_triangles(self) -> Collection[Any]:
208
+ raise NotImplementedError()
209
+
210
+ @property
211
+ def vertices(self) -> Any:
212
+ raise NotImplementedError()
213
+
214
+
215
+ class ops:
216
+
217
+ class object:
218
+
219
+ @staticmethod
220
+ def select_all(action):
221
+ pass
222
+
223
+ class export_mesh:
224
+
225
+ @classmethod
226
+ def stl(
227
+ cls, filepath, use_selection, use_mesh_modifiers, axis_forward, axis_up
228
+ ):
229
+ pass
data/dm_control/blender/fake_core/mathutils.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Fake Blender mathutils module."""
17
+ # pylint: disable=invalid-name
18
+
19
+ import numpy as np
20
+
21
+
22
+ class Color:
23
+ """Fake color class."""
24
+
25
+ def __init__(self, coords):
26
+ self._coords = coords
27
+
28
+ @property
29
+ def r(self) -> float:
30
+ return self._coords[0]
31
+
32
+ @property
33
+ def g(self) -> float:
34
+ return self._coords[1]
35
+
36
+ @property
37
+ def b(self) -> float:
38
+ return self._coords[2]
39
+
40
+ @property
41
+ def a(self) -> float:
42
+ return self._coords[3]
43
+
44
+
45
+ class Vector:
46
+ """Fake vector class."""
47
+
48
+ def __init__(self, coords):
49
+ self._coords = np.asarray(coords)
50
+
51
+ @property
52
+ def x(self) -> float:
53
+ return self._coords[0]
54
+
55
+ @property
56
+ def y(self) -> float:
57
+ return self._coords[1]
58
+
59
+ @property
60
+ def z(self) -> float:
61
+ return self._coords[2]
62
+
63
+ @property
64
+ def w(self) -> float:
65
+ return self._coords[3]
66
+
67
+ def __eq__(self, rhs) -> bool:
68
+ if not isinstance(rhs, Vector):
69
+ return False
70
+ return np.linalg.norm(self._coords - rhs._coords) < 1e-6
71
+
72
+ def __str__(self) -> str:
73
+ return 'Vector({:.2f}, {:.2f}, {:.2f})'.format(self.x, self.y, self.z)
74
+
75
+ def __repr__(self) -> str:
76
+ return 'Vector({:.2f}, {:.2f}, {:.2f})'.format(self.x, self.y, self.z)
77
+
78
+
79
+ class Quaternion:
80
+ """Fake quaternion class."""
81
+
82
+ def __init__(self, coords):
83
+ self._coords = coords
84
+
85
+ @property
86
+ def x(self) -> float:
87
+ return self._coords[1]
88
+
89
+ @property
90
+ def y(self) -> float:
91
+ return self._coords[2]
92
+
93
+ @property
94
+ def z(self) -> float:
95
+ return self._coords[3]
96
+
97
+ @property
98
+ def w(self) -> float:
99
+ return self._coords[0]
100
+
101
+ def __matmul__(self, rhs: Vector) -> Vector:
102
+ return Vector((1, 0, 0))
103
+
104
+
105
+ class Matrix:
106
+ """Fake matrix class."""
107
+
108
+ def __init__(self, coords):
109
+ self._coords = coords
110
+
111
+ @classmethod
112
+ def Diagonal(cls, _):
113
+ return cls((1,))
114
+
115
+ @property
116
+ def translation(self) -> Vector:
117
+ return Vector((0.0, 0.0, 0.0))
118
+
119
+ def to_quaternion(self) -> Quaternion:
120
+ return Quaternion((1.0, 0.0, 0.0, 0.0))
121
+
122
+ def to_scale(self) -> Vector:
123
+ return Vector((0.0, 0.0, 0.0))
data/dm_control/blender/mujoco_exporter/README.md ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Export Mujoco models from Blender
2
+
3
+ ## Prerequisites
4
+
5
+ The MuJoCo exporter works as Blender addon, tested with ver 3.4.1. You can
6
+ download Blender from [https://www.blender.org](https://www.blender.org/).
7
+
8
+ ## Installation
9
+
10
+ ### Preparing a plugin installer
11
+
12
+ The `install.sh` command will deploy the installable version of the plugin to
13
+ `./addons/mujoco_model_exporter`. This folder should be zipped:
14
+
15
+ ```shell
16
+ $ cd ./addons && zip -r mujoco_model_exporter.zip mujoco_model_exporter/*
17
+ ```
18
+
19
+ ### Installing the plugin in Blender
20
+
21
+ Open Blender and select `Edit/Preferences` menu option.
22
+
23
+ ![Addon preferences](doc/install_plugin.png "Click the Install button"){style="display:block;margin:auto"}
24
+
25
+ Clicking the Install button will open a file selection dialog that will allow
26
+ you to select the .zip archive with the plugin.
27
+
28
+ The next window will follow, listing the installed plugin and allowing you to
29
+ enable it.
30
+
31
+ ![Enabling a plugin](doc/enable_plugin.png "Check the checkbox next to plugin's name"){style="display:block;margin:auto"}
32
+
33
+ Check the checkbox next to its name to enable it.
34
+
35
+ ## Modelling for Mujoco.
36
+
37
+ The plugin was designed to allow the artists to keep using core Blender features
38
+ when building models for Mujoco.
39
+
40
+ feature | Mujoco | Blender
41
+ -------------- | ------------------------- | -----------------------------------
42
+ kinematic tree | hierarchy of Bodies | Armatures or hierarchies of Objects
43
+ geometry | Geoms | Meshes
44
+ materials | Material + Texture assets | Material + Texture definitions
45
+ lighting | Lights | Lights
46
+
47
+ ### Node naming
48
+
49
+ The exporter will copy the names of the bones, meshes and lights. Mujoco joints
50
+ will be named after the bone that owns the respective constraint, with a postfix
51
+ denoting the degree of freedom they enable.
52
+
53
+ ### Modelling kinematic trees using Armatures and IK
54
+
55
+ Blender Armatures allow to model kinematic capabilities of a Blender model. They
56
+ comprise a tree of bones, each of which can be further extended with IK
57
+ Constraints.
58
+
59
+ Only the bones affected by an IK chain will receive appropriate degrees of
60
+ freedom. This means that if you export a model without any IK chains, it will be
61
+ exported as a static model.
62
+
63
+ #### IK Constraints and bone limits
64
+
65
+ IK constraints offer the easiest way to verify how a kinematic chain would
66
+ behave in a physical environment. For that reason we chose to use them, along
67
+ with IK bone limits, to model Mujoco joints.
68
+
69
+ ![Select the end effector](doc/end_effector_selection.png "Select the end effector")
70
+
71
+ * Select the bone at the end of a kinematic chain,
72
+
73
+ ![Add IK constraint](doc/add_ik_constraint.png "Add IK constraint")
74
+
75
+ * Add an IK Bone Constraint to it.
76
+ [This webpage](https://docs.blender.org/manual/en/latest/animation/constraints/tracking/ik_solver.html)
77
+ contains detailed instructions.
78
+
79
+ ![Adding an IK target](doc/ik_target.png "Add an IK target")
80
+
81
+ * Add a target bone to the scene and use it as the IK constraint's target.
82
+
83
+ ![Set the chain length](doc/ik_chain_length.png "Adjust the chain length")
84
+
85
+ * Adjust the `Chain Length` value to reflect the number of parent bones that
86
+ should become a part of this IK chain.
87
+
88
+ ![Define bone limits](doc/limits.png "Define bone limits")
89
+
90
+ * For each of the bones in the chain, visit the `Bone/Inverse Kinematics` tab
91
+ and adjust the locks and bone limits.
92
+
93
+ ![Bone limits gizmo](doc/gizmo.png "Bone limits gizmo")
94
+
95
+ *NOTE*: you can take advantage of a helpful limit visualization gizmo.
96
+
97
+ ### Armature free joints.
98
+
99
+ Armatures form the kinematic trees, so it makes sense to give their roots all 6
100
+ degrees of freedom.
101
+
102
+ This behavior can be changed by disabling the `Armature freejoint` export
103
+ option.
104
+
105
+ ### Modelling the geometry
106
+
107
+ Mujoco uses parametric geometry comprised of primitive shapes such
108
+ as cubes, spheres and capsules. It does support triangle based mesh geometry
109
+ however.
110
+
111
+ Blender on the other hand deals exclusively in meshes, and even though it
112
+ contains a palette of such primitive shapes, these are not parametric.
113
+
114
+ #### MSH files
115
+
116
+ The exporter therefore exports the geometry as meshes. All meshes referenced by
117
+ the scene are exported into Mujoco's native .msh format.
118
+
119
+ When this plugin was created, the native .msh format was the only format to
120
+ support texture mapping. Since MuJoCo 2.1.2, `.obj` files are supported. The
121
+ `.msh` format is expected to be deprecated and removed soon. Until this plugin
122
+ is updated to output `.obj` files we recommend all user to convert their `.msh`
123
+ files to `.obj` files using [this](https://github.com/google-deepmind/mujoco/blob/main/python/mujoco/msh2obj.py) utility.
124
+
125
+ #### Phong lighting model and lack of support for Cycles nodes
126
+
127
+ Mujoco implements a forward rendering model with Phong lightning and support for
128
+ reflective surfaces.
129
+
130
+ [Mujoco material definition](http://www.mujoco.org/book/XMLreference.html#material)
131
+ is fixed and limited to:
132
+
133
+ * base color (diffuse color)
134
+ * specularity coefficient
135
+ * smoothness coefficient
136
+ * reflectiveness coefficient
137
+
138
+ These parameters translate well to Blender's default material definition, which
139
+ should be used to model the materials exported to Mujoco.
140
+
141
+ Due to the diversity and open-ended nature of Cycle's material nodes, the choice
142
+ was made not to support materials defined using them.
143
+
144
+ #### Division of meshes that employ multiple materials
145
+
146
+ Mujoco renderer supports a single material per mesh, in contrast to Blender's
147
+ multi material model. In order to support meshes with multiple materials, the
148
+ exporter divides them into submeshes, each of which uses a single material.
149
+
150
+ Since Blender materials are applied to faces, and a single face may only have a
151
+ single material assigned, there is no risk that the subdivided mesh will exhibit
152
+ any overlapping artifacts.
153
+
154
+ #### Effect of mesh division on inertia and mass.
155
+
156
+ The exported submeshes will have different geometry and volume than the
157
+ original. This will affect the mass and inertia of the geom that uses the
158
+ exported mesh.
159
+
160
+ Please note that Mujoco derives these quantities not from the mesh itself, but
161
+ rather from the convex hull calculated for it. The sum of hulls of subdivided
162
+ meshes are not guaranteed to be equal to the hull of the original mesh.
163
+
164
+ This phenomenon is illustrated on the image below.
165
+
166
+ Blender | Mujoco renderer | Mujoco convex hulls
167
+ ----------------------------- | ------------------------------- | -------------------
168
+ ![](doc/convhull_blend.png) | ![](doc/convhull_mj_rend.png) | ![](doc/convhull_mj_hull.png)
169
+
170
+ A different material was assigned to 2 out of 6 rectangular faces of the right
171
+ cube, causing that mesh to be split into two submeshes.
172
+
173
+ While they render well in Mujoco, the Moiré effect visible on the convex hull
174
+ comes from two overlapping hulls, each with a different volume.
175
+
176
+ #### Double-sided materials
177
+
178
+ Double sided materials cause the meshes (or faces) that use them to be exported
179
+ with the faces duplicated with the reverse face winding order. This is because
180
+ Mujoco renderer does not support any other face culling modes than back face
181
+ culling.
182
+
183
+ *CAUTION*: Because this operation affects the exported geometry, it may
184
+ indirectly affect the physical properties of a geom that references that mesh,
185
+ such as its mass and inertia. Please use this feature with caution.
186
+
187
+ #### Scaling
188
+
189
+ *CAUTION*: If you are using the scaling transform, the exporter will modify your
190
+ scene!
191
+
192
+ The exporter will by default reset the scaling transform on all bones and meshes
193
+ to ensure affine reference frame transformations.
194
+
195
+ This operation can be undo'ed after the exporter is completed, but the exporter
196
+ doesn't undo it automatically!
197
+
198
+ ### Textures
199
+
200
+ *NOTE*: This feature will be added in the next version of the exporter.
201
+
202
+ #### One texture channel
203
+
204
+ Mujoco renderer supports a single texture channel. It's therefore advised to use
205
+ a single UV map for meshes that are to be exported to Mujoco.
206
+
207
+ #### Choice between atlases and individual textures
208
+
209
+ Mujoco's fixed rendering pipeline is quite fast, and handles both variants well.
210
+ Therefore we leave it up to the artist to decide which it prefers using.
211
+
212
+ Please keep in mind that the exporter doesn't export the texture assets. Those
213
+ should be copied into the folder with the exported model manually.
data/dm_control/blender/mujoco_exporter/__init__.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Blender 3.4 plugin for exporting models to MuJoCo native format."""
17
+
18
+ import contextlib
19
+ import os
20
+ from xml.dom import minidom
21
+
22
+ import bpy
23
+ from bpy_extras.io_utils import ExportHelper
24
+
25
+ from . import blender_scene
26
+ from . import mujoco_assets
27
+ from . import mujoco_scene
28
+
29
+
30
+ bl_info = {
31
+ 'name': 'Export MuJoCo',
32
+ 'author': 'The dm_control authors',
33
+ 'version': (2, 0),
34
+ 'blender': (3, 3, 1),
35
+ 'location': 'File > Export > MuJoCo',
36
+ 'warning': '',
37
+ 'description': 'Export articulated MuJoCo model',
38
+ 'doc_url': '',
39
+ 'category': 'Import-Export',
40
+ }
41
+
42
+
43
+ @contextlib.contextmanager
44
+ def context_settings_cacher(context: bpy.types.Context):
45
+ """Preserves the pose of exported objects and the scene mode."""
46
+ # Cache the mode
47
+ prev_mode = context.mode
48
+
49
+ # Set the Object mode required by the exporter
50
+ bpy.ops.object.mode_set(mode='OBJECT')
51
+
52
+ # Set the armatures in their neutral pose
53
+ pose_positions = []
54
+ for o in context.scene.objects:
55
+ if o.type == 'ARMATURE':
56
+ pose_positions.append((o, o.data.pose_position))
57
+ o.data.pose_position = 'REST'
58
+ context.view_layer.update()
59
+
60
+ try:
61
+ yield
62
+ finally:
63
+ # Restore the poses.
64
+ for armature, pose_position in pose_positions:
65
+ armature.data.pose_position = pose_position
66
+ context.view_layer.update()
67
+
68
+ # Restore the mode
69
+ bpy.ops.object.mode_set(mode=prev_mode)
70
+
71
+
72
+ def apply_scale():
73
+ bpy.ops.object.select_all(action='SELECT')
74
+ bpy.ops.object.transform_apply(location=False, scale=True, rotation=False)
75
+ bpy.ops.object.select_all(action='DESELECT')
76
+
77
+
78
+ class ExportMjcf(bpy.types.Operator, ExportHelper):
79
+ """Export to MJCF file format."""
80
+
81
+ bl_idname = 'export_scene.mjcf'
82
+ bl_label = 'Export MJCF'
83
+
84
+ filename_ext = '.xml'
85
+ filter_glob = bpy.props.StringProperty(default='*.xml', options={'HIDDEN'})
86
+
87
+ # Export settings
88
+ armature_freejoint: bpy.props.BoolProperty(
89
+ name='Armature freejoint',
90
+ description='Add a freejoint to armature body',
91
+ default=False,
92
+ )
93
+ apply_mesh_modifiers: bpy.props.BoolProperty(
94
+ name='Apply modifiers',
95
+ description='Apply mesh modifiers',
96
+ default=False,
97
+ )
98
+
99
+ def _export_mjcf(self, context: bpy.types.Context) -> None:
100
+ """Converts a Blender scene to Mujoco XML format."""
101
+ # Create a new XML document
102
+ xml_doc = minidom.Document()
103
+ mujoco = xml_doc.createElement('mujoco')
104
+ xml_doc.appendChild(mujoco)
105
+
106
+ # Create a list of blender objects, arranged according to their hierarchy,
107
+ # where parents precede the children.
108
+ blender_objects = blender_scene.map_blender_tree(
109
+ context, lambda o: o if o.is_visible else None
110
+ )
111
+ # Remove None entries that correspond to invisible objects.
112
+ blender_objects = [o for o in blender_objects if o]
113
+
114
+ export_settings = self.as_keywords()
115
+
116
+ # Build the scene tree
117
+ worldbody_el = mujoco_scene.export_to_xml(
118
+ doc=xml_doc,
119
+ objects=blender_objects,
120
+ armature_freejoint=export_settings['armature_freejoint'],
121
+ )
122
+ mujoco.appendChild(worldbody_el)
123
+
124
+ # Build the asset tree
125
+ asset_el = mujoco_assets.export_to_xml(
126
+ doc=xml_doc,
127
+ objects=blender_objects,
128
+ folder=os.path.dirname(export_settings['filepath']),
129
+ apply_mesh_modifiers=export_settings['apply_mesh_modifiers'],
130
+ )
131
+ mujoco.appendChild(asset_el)
132
+
133
+ # Add compiler options that would allow to export small feature meshes.
134
+ compiler_el = xml_doc.createElement('compiler')
135
+ mujoco.appendChild(compiler_el)
136
+ compiler_el.setAttribute('boundmass', '1e-3')
137
+ compiler_el.setAttribute('boundinertia', '1e-9')
138
+ # TODO(b/266818670): support assets export into subdirectory
139
+ # compiler_el.setAttribute('meshdir', 'assets')
140
+
141
+ # Write the XML to a file.
142
+ with open(export_settings['filepath'], 'w') as file:
143
+ file.write(xml_doc.toprettyxml(indent=' '))
144
+
145
+ def execute(self, context: bpy.types.Context):
146
+ """Export the scene."""
147
+ with context_settings_cacher(context):
148
+ apply_scale()
149
+ self._export_mjcf(context)
150
+
151
+ return {'FINISHED'}
152
+
153
+
154
+ def menu_func_export(self, context: bpy.types.Context):
155
+ del context
156
+ self.layout.operator(ExportMjcf.bl_idname, text='MuJoCo (.xml)')
157
+
158
+
159
+ def register():
160
+ bpy.utils.register_class(ExportMjcf)
161
+ bpy.types.TOPBAR_MT_file_export.append(menu_func_export)
162
+
163
+
164
+ def unregister():
165
+ bpy.utils.unregister_class(ExportMjcf)
166
+ bpy.types.TOPBAR_MT_file_export.remove(menu_func_export)
167
+
168
+
169
+ if __name__ == '__main__':
170
+ register()
data/dm_control/blender/mujoco_exporter/blender_scene.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Blender scene parsers."""
17
+
18
+ # disable: pytype=strict-none
19
+ import dataclasses
20
+ import math
21
+ from typing import Any, Callable, Sequence, Tuple, cast
22
+
23
+ from dm_control.blender.fake_core import bpy
24
+ from dm_control.blender.fake_core import mathutils
25
+
26
+ _ARMATURE = 'ARMATURE'
27
+ _CAMERA = 'CAMERA'
28
+ _EMPTY = 'EMPTY'
29
+ _LIGHT = 'LIGHT'
30
+ _MESH = 'MESH'
31
+ _VEC_ZERO = mathutils.Vector((0, 0, 0))
32
+ _OX = mathutils.Vector((1, 0, 0))
33
+ _OY = mathutils.Vector((0, 1, 0))
34
+ _OZ = mathutils.Vector((0, 0, 1))
35
+
36
+
37
+ def _check_that_parent_bone_exists(obj: bpy.types.Object) -> None:
38
+ """Checks if the bone the object was supposed to be parented exists."""
39
+ assert obj is not None
40
+ if obj.parent is None:
41
+ raise ValueError(
42
+ 'Armature object "{}" was parented to does not exist'.format(obj.name)
43
+ )
44
+
45
+ armature = obj.parent
46
+ if armature.type != _ARMATURE:
47
+ raise ValueError(
48
+ 'Parent of object "{}" - "{}", is not an armature, but a "{}"'.format(
49
+ obj.name, armature.name, armature.type
50
+ )
51
+ )
52
+
53
+ if obj.parent_bone not in armature.data.bones:
54
+ raise ValueError(
55
+ 'Object "{}" is parented to a non-existing bone "{}" from '
56
+ 'armature "{}"'.format(obj.name, obj.parent_bone, armature.name)
57
+ )
58
+
59
+
60
+ def _check_constraint_in_local_space(
61
+ constraint: bpy.types.Constraint, owner: 'ObjectRef'
62
+ ) -> None:
63
+ if constraint and constraint.owner_space != 'LOCAL':
64
+ raise ValueError(
65
+ 'Constraint "{}" (bone "{}", armature "{}") uses an unsupported '
66
+ 'owner_mode "{}". Only "LOCAL" mode is supported at the '
67
+ 'moment'.format(
68
+ type(constraint),
69
+ owner.bone_name(),
70
+ owner.obj_name(),
71
+ constraint.owner_space,
72
+ )
73
+ )
74
+
75
+
76
+ def _angle_distance(lhs_deg: float, rhs_deg: float) -> float:
77
+ """Calculates distance between two angles, in degrees."""
78
+ x_2 = math.cos(math.radians(lhs_deg)) * math.cos(math.radians(rhs_deg))
79
+ y_2 = math.sin(math.radians(lhs_deg)) * math.sin(math.radians(rhs_deg))
80
+ return math.degrees(math.acos(x_2 + y_2))
81
+
82
+
83
+ @dataclasses.dataclass(frozen=True)
84
+ class AffineTransform:
85
+ pos: mathutils.Vector
86
+ rot: mathutils.Quaternion
87
+
88
+
89
+ @dataclasses.dataclass(frozen=True)
90
+ class Dof:
91
+ """Degree of freedom description."""
92
+
93
+ name: str
94
+ axis: mathutils.Vector
95
+ limited: bool = False
96
+ limits: Tuple[float, float] = (0, 0)
97
+
98
+
99
+ @dataclasses.dataclass(frozen=True)
100
+ class ObjectRef:
101
+ """References a Blender object, be that a scene object or a bone.
102
+
103
+ Object reference is hashable and comparable. Equality is based on the names
104
+ of the underlying objects. Blender's API guarantees that a combination of
105
+ object/bone name will be unique across the scene. We're leveraging that rule.
106
+ """
107
+
108
+ native_obj: bpy.types.Object | None
109
+ native_bone: bpy.types.Bone | None = None
110
+
111
+ def __hash__(self) -> int:
112
+ return hash(self.name)
113
+
114
+ def __eq__(self, rhs) -> bool:
115
+ if not isinstance(rhs, ObjectRef):
116
+ return False
117
+ return self.name == rhs.name
118
+
119
+ @property
120
+ def is_none(self) -> bool:
121
+ return self.native_bone is None
122
+
123
+ @property
124
+ def is_armature(self) -> bool:
125
+ return ( # pytype: disable=bad-return-type
126
+ self.native_obj
127
+ and self.native_obj.type == _ARMATURE
128
+ and not self.native_bone
129
+ )
130
+
131
+ @property
132
+ def is_bone(self) -> bool:
133
+ return bool(
134
+ self.native_obj
135
+ and self.native_obj.type == _ARMATURE
136
+ and self.native_bone
137
+ )
138
+
139
+ @property
140
+ def is_mesh(self) -> bool:
141
+ return self.native_obj and self.native_obj.type == _MESH # pytype: disable=bad-return-type
142
+
143
+ @property
144
+ def is_light(self) -> bool:
145
+ return self.native_obj and self.native_obj.type == _LIGHT # pytype: disable=bad-return-type
146
+
147
+ @property
148
+ def is_camera(self) -> bool:
149
+ return self.native_obj and self.native_obj.type == _CAMERA # pytype: disable=bad-return-type
150
+
151
+ @property
152
+ def is_empty(self) -> bool:
153
+ return self.native_obj and self.native_obj.type == _EMPTY # pytype: disable=bad-return-type
154
+
155
+ @property
156
+ def name(self) -> str:
157
+ if not self.native_obj:
158
+ return ''
159
+ if self.native_bone:
160
+ return '{}_{}'.format(self.native_bone.name, self.native_obj.name)
161
+ else:
162
+ return self.native_obj.name
163
+
164
+ def as_light(self) -> bpy.types.Light:
165
+ return cast(bpy.types.Light, self.obj_data())
166
+
167
+ def get_local_transform(self) -> AffineTransform:
168
+ """Returns a transform wrt. the local reference frame."""
169
+
170
+ def get_bone_local_mtx(bone: bpy.types.Bone) -> mathutils.Matrix:
171
+ """Derives a local matrix of an armature bone."""
172
+ assert isinstance(bone, bpy.types.Bone)
173
+ if bone.parent:
174
+ return bone.parent.matrix_local.inverted() @ bone.matrix_local
175
+ else:
176
+ return bone.matrix_local
177
+
178
+ def get_object_local_mtx(obj: bpy.types.Object) -> mathutils.Matrix:
179
+ """Derives a local matrix of an object, such as a mesh or armature."""
180
+ assert isinstance(obj, bpy.types.Object)
181
+ if obj.parent:
182
+ local_mtx = obj.parent.matrix_world.inverted() @ obj.matrix_world
183
+ if obj.parent_bone:
184
+ assert obj.parent.type == _ARMATURE
185
+ armature = obj.parent
186
+ bone = armature.data.bones[obj.parent_bone]
187
+ return bone.matrix_local.inverted() @ local_mtx
188
+ else:
189
+ return local_mtx
190
+ else:
191
+ return obj.matrix_world
192
+
193
+ if self.is_bone:
194
+ local_mtx = get_bone_local_mtx(self.native_bone)
195
+ else:
196
+ local_mtx = get_object_local_mtx(self.native_obj)
197
+
198
+ rot_quat = local_mtx.to_quaternion()
199
+ pos = local_mtx.translation
200
+ return AffineTransform(pos, rot_quat)
201
+
202
+ @property
203
+ def is_visible(self) -> bool:
204
+ """Checks if an object is visible."""
205
+ if not self.native_obj:
206
+ return False
207
+ if hasattr(self.native_obj, 'visible_get'):
208
+ return self.native_obj.visible_get()
209
+ else:
210
+ return True
211
+
212
+ @property
213
+ def parent(self) -> 'ObjectRef':
214
+ """Returns a reference to the parent of this object."""
215
+ if self.native_obj is None:
216
+ return ObjectRef(None)
217
+
218
+ def bone_parent(
219
+ armature: bpy.types.Object, bone: bpy.types.Bone
220
+ ) -> 'ObjectRef':
221
+ if bone.parent:
222
+ # Parent of a child bone is its parent bone in the same armature
223
+ assert isinstance(bone.parent, bpy.types.Bone)
224
+ return ObjectRef.new_bone(armature, bone.parent)
225
+ else:
226
+ # Parent of the root bone is the armature.
227
+ return ObjectRef.new_object(armature)
228
+
229
+ def object_parent(obj: bpy.types.Object) -> 'ObjectRef':
230
+ if obj.parent_bone:
231
+ # The object is parented to an armature, and the .parent field must
232
+ # contain a reference the armature.
233
+ assert obj.parent and obj.parent.type == _ARMATURE
234
+ _check_that_parent_bone_exists(obj)
235
+ armature = obj.parent
236
+ parent_bone = armature.data.bones[obj.parent_bone]
237
+ return ObjectRef.new_bone(armature, parent_bone)
238
+ elif obj.parent:
239
+ # The object is parented to another object.
240
+ return ObjectRef.new_object(obj.parent)
241
+ else:
242
+ # This is a root object
243
+ return ObjectRef(None)
244
+
245
+ if self.native_bone:
246
+ return bone_parent(self.native_obj, self.native_bone)
247
+ else:
248
+ return object_parent(self.native_obj)
249
+
250
+ def get_rotation_dofs(self) -> Sequence[Dof]:
251
+ """Returns the rotation degrees of freedom in the subtractive mode.
252
+
253
+ The method returns the degrees of freedom present from the point of view
254
+ of Blender. These are modeled such that in absence of constraints, all
255
+ degrees of freedom are present.
256
+
257
+ Returns:
258
+ A sequence of degree of freedom definitions.
259
+ """
260
+ if not self.is_bone:
261
+ raise ValueError(
262
+ 'Rotation degrees of freedom are defined only for bones.'
263
+ )
264
+ assert self.native_obj
265
+ assert self.native_obj.type == _ARMATURE
266
+ armature = self.native_obj
267
+ bone = armature.pose.bones[self.native_bone.name]
268
+ if not bone.is_in_ik_chain:
269
+ # Bones not in an IK chain don't receive any degrees of freedom.
270
+ return []
271
+
272
+ is_locked = [bone.lock_ik_x, bone.lock_ik_y, bone.lock_ik_z]
273
+ use_limits = [bone.use_ik_limit_x, bone.use_ik_limit_y, bone.use_ik_limit_z]
274
+ limits = [
275
+ (math.degrees(bone.ik_min_x), math.degrees(bone.ik_max_x)),
276
+ (math.degrees(bone.ik_min_y), math.degrees(bone.ik_max_y)),
277
+ (math.degrees(bone.ik_min_z), math.degrees(bone.ik_max_z)),
278
+ ]
279
+ axes = [_OX, _OY, _OZ]
280
+ names = [
281
+ 'rx_{}'.format(self.name),
282
+ 'ry_{}'.format(self.name),
283
+ 'rz_{}'.format(self.name),
284
+ ]
285
+ axis_names = ['X', 'Y', 'Z']
286
+
287
+ def build_dof(idx):
288
+ if limits[idx][0] >= limits[idx][1]:
289
+ raise ValueError(
290
+ 'Bone "{}" uses incorrect IK limits for {} axis. '
291
+ '{} < {} is violated'.format(
292
+ self.name, axis_names[idx], limits[idx][0], limits[idx][1]
293
+ )
294
+ )
295
+ return Dof(
296
+ name=names[idx],
297
+ axis=axes[idx],
298
+ limited=use_limits[idx],
299
+ limits=limits[idx],
300
+ )
301
+
302
+ return [build_dof(i) for i in range(3) if not is_locked[i]]
303
+
304
+ def obj_data(self) -> bpy.types.Object | None:
305
+ if self.native_obj is not None:
306
+ return self.native_obj.data
307
+ else:
308
+ return None
309
+
310
+ def obj_name(self) -> str | None:
311
+ if self.native_obj is not None:
312
+ return self.native_obj.name
313
+ else:
314
+ return None
315
+
316
+ def bone_name(self) -> str | None:
317
+ if self.native_bone is not None:
318
+ return self.native_bone.name
319
+ else:
320
+ return None
321
+
322
+ @property
323
+ def mesh(self) -> bpy.types.Mesh:
324
+ """Returns the mesh associated with this object."""
325
+ assert self.is_mesh
326
+ return cast(bpy.types.Mesh, self.obj_data())
327
+
328
+ def get_modified_mesh(self) -> bpy.types.Mesh | None:
329
+ """Returns a mesh with modifiers applied to it."""
330
+ assert self.is_mesh
331
+ assert self.native_obj is not None
332
+ if self.native_obj.mode == 'EDIT':
333
+ self.native_obj.update_from_editmode()
334
+
335
+ # get the modifiers
336
+ depsgraph = bpy.context.evaluated_depsgraph_get()
337
+ mesh_owner = self.native_obj.evaluated_get(depsgraph)
338
+
339
+ return mesh_owner.to_mesh()
340
+
341
+ @property
342
+ def materials(self) -> Sequence[bpy.types.Material]:
343
+ """Returns the materials assigned to this object."""
344
+ data = self.obj_data()
345
+ if hasattr(data, 'materials'):
346
+ return data.materials
347
+ else:
348
+ return []
349
+
350
+ @classmethod
351
+ def new_object(cls, obj: bpy.types.Object) -> 'ObjectRef':
352
+ assert isinstance(obj, bpy.types.Object) or obj is None
353
+ return cls(obj)
354
+
355
+ @classmethod
356
+ def new_bone(
357
+ cls,
358
+ armature: bpy.types.Object,
359
+ bone: bpy.types.Bone | None,
360
+ ) -> 'ObjectRef':
361
+ assert isinstance(armature, bpy.types.Object)
362
+ assert armature.type == _ARMATURE
363
+ assert isinstance(bone, bpy.types.Bone) or bone is None
364
+ return cls(armature, bone)
365
+
366
+
367
+ NoneRef = ObjectRef(None, None)
368
+
369
+
370
+ def map_blender_tree(
371
+ context: bpy.types.Context, callback: Callable[[ObjectRef], Any]
372
+ ) -> Sequence[Any]:
373
+ """Returns a list of scene objects in the breadth-first order."""
374
+ # Collect all nodes to explore - objects and bones alike
375
+ assert context.scene is not None
376
+ to_explore = [ObjectRef.new_object(o) for o in context.scene.objects]
377
+ armatures = [o for o in context.scene.objects if o.type == 'ARMATURE']
378
+ for armature in armatures:
379
+ for bone in armature.data.bones:
380
+ to_explore.append(ObjectRef.new_bone(armature, bone))
381
+
382
+ explored = set()
383
+ explored.add(NoneRef)
384
+ result = []
385
+
386
+ while to_explore:
387
+ obj_ref: ObjectRef = to_explore[0]
388
+ to_explore = to_explore[1:]
389
+
390
+ if obj_ref.parent in explored:
391
+ explored.add(obj_ref)
392
+ result.append(callback(obj_ref))
393
+ else:
394
+ to_explore.append(obj_ref)
395
+
396
+ return result
397
+
398
+
399
+ def get_material_mesh_pair_name(mesh_name: str, mat_name: str) -> str:
400
+ """Build the name for a mesh-material pair."""
401
+ return '{}_{}'.format(mesh_name, mat_name) if mat_name else mesh_name
402
+
403
+
404
+ def is_material_mesh_pair_valid(mesh: bpy.types.Mesh, mat_idx: int) -> bool:
405
+ """Tests the mesh-material pair whether it contains any geometry."""
406
+ mesh.calc_loop_triangles()
407
+ faces = [f for f in mesh.loop_triangles if f.material_index == mat_idx]
408
+ return bool(faces)
409
+
410
+
411
+ def map_materials(
412
+ func: Callable[[bpy.types.Material], Any],
413
+ materials: Sequence[bpy.types.Material],
414
+ ) -> Sequence[Any]:
415
+ """Maps a collection of materials, adjusting for empty collections.
416
+
417
+ In case of an empty collection, a substitute for a default material is passed
418
+ to the mapping callback.
419
+
420
+ Args:
421
+ func: Mapping callback.
422
+ materials: Collection of materials.
423
+
424
+ Returns:
425
+ An arbitrary collection of data mapped out of the materials collection.
426
+ """
427
+ materials = materials or []
428
+ return [func(material) for material in materials]
data/dm_control/blender/mujoco_exporter/blender_scene_test.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for blender_scene.py."""
17
+
18
+ import math
19
+ from unittest import mock
20
+ from absl.testing import absltest
21
+ from absl.testing import parameterized
22
+ from dm_control.blender.fake_core import bpy
23
+ from dm_control.blender.fake_core import mathutils
24
+ from dm_control.blender.mujoco_exporter import blender_scene
25
+ from dm_control.blender.mujoco_exporter import testing
26
+ import numpy as np
27
+
28
+
29
+ class AngleDistanceTest(parameterized.TestCase):
30
+
31
+ @parameterized.parameters([
32
+ [0, 0, 0],
33
+ [90, 90, 0],
34
+ [-90, -90, 0],
35
+ [-90, 0, 90],
36
+ [0, 90, 90],
37
+ [-90, 90, 180],
38
+ [-180, 180, 0],
39
+ [-270, 90, 0],
40
+ [-90, 270, 0],
41
+ [-90, 360, 90],
42
+ ])
43
+ def test_angle_distance(self, lhs, rhs, result):
44
+ self.assertAlmostEqual(blender_scene._angle_distance(lhs, rhs), result, 2)
45
+
46
+
47
+ class ObjectRefTest(absltest.TestCase):
48
+
49
+ def test_hashing_and_comparison(self):
50
+ mesh_a = blender_scene.ObjectRef.new_object(
51
+ testing.build_mesh_object('mesh_a')
52
+ )
53
+ mesh_a_copy = blender_scene.ObjectRef.new_object(
54
+ testing.build_mesh_object('mesh_a')
55
+ )
56
+ mesh_b = blender_scene.ObjectRef.new_object(
57
+ testing.build_mesh_object('mesh_b')
58
+ )
59
+
60
+ self.assertEqual(hash(mesh_a), hash(mesh_a_copy))
61
+ self.assertNotEqual(hash(mesh_a), hash(mesh_b))
62
+
63
+ self.assertEqual(mesh_a, mesh_a_copy)
64
+ self.assertNotEqual(mesh_a, mesh_b)
65
+
66
+ def test_parent_of_root_object_is_noneref(self):
67
+ obj_ref = blender_scene.ObjectRef.new_object(
68
+ testing.build_mesh_object('mesh')
69
+ )
70
+ self.assertEqual(obj_ref.parent, blender_scene.NoneRef)
71
+
72
+ def test_parent_of_object_parented_to_another_object(self):
73
+ parent_obj = testing.build_mesh_object('parent_obj')
74
+ child_obj = testing.build_mesh_object('child_obj', parent=parent_obj)
75
+
76
+ parent_ref = blender_scene.ObjectRef.new_object(parent_obj)
77
+ child_ref = blender_scene.ObjectRef.new_object(child_obj)
78
+ self.assertEqual(child_ref.parent, parent_ref)
79
+
80
+ def test_parent_of_object_parented_to_bone(self):
81
+ bone = testing.build_bone('bone')
82
+ armature = testing.build_armature('armature', bones=[bone])
83
+ child_obj = testing.build_mesh_object(
84
+ 'child_obj', parent=armature, parent_bone=bone.name
85
+ )
86
+
87
+ parent_ref = blender_scene.ObjectRef.new_bone(armature, bone)
88
+ child_ref = blender_scene.ObjectRef.new_object(child_obj)
89
+ self.assertEqual(child_ref.parent, parent_ref)
90
+
91
+ def test_parent_of_root_bone_is_armature(self):
92
+ bone = testing.build_bone('bone')
93
+ armature = testing.build_armature('armature', bones=[bone])
94
+
95
+ armature_ref = blender_scene.ObjectRef.new_object(armature)
96
+ bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
97
+ self.assertEqual(bone_ref.parent, armature_ref)
98
+
99
+
100
+ class BlenderTreeMapperTest(parameterized.TestCase):
101
+
102
+ @parameterized.parameters([
103
+ [['obj1']],
104
+ [['obj1', 'obj2']],
105
+ [['obj2', 'obj1']],
106
+ [['obj2', 'obj1', 'obj3']],
107
+ ])
108
+ def test_object_without_hierarchy(self, object_names):
109
+ context = mock.MagicMock(spec=bpy.types.Context)
110
+ context.scene.objects = [
111
+ testing.build_mesh_object(name) for name in object_names
112
+ ]
113
+
114
+ objects = blender_scene.map_blender_tree(context, lambda x: x)
115
+ self.assertEqual([o.native_obj.name for o in objects], object_names)
116
+
117
+ @parameterized.parameters([
118
+ # A hierarchy with 2 objects
119
+ dict(
120
+ parent_child_tuples=[('obj_1', 'obj_1_1')],
121
+ expected_order=['obj_1', 'obj_1_1'],
122
+ ),
123
+ # Shallow hierarchy with 3 objects
124
+ dict(
125
+ parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_1', 'obj_1_2')],
126
+ expected_order=['obj_1', 'obj_1_1', 'obj_1_2'],
127
+ ),
128
+ # Deep hierarchy with 3 objects
129
+ dict(
130
+ parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_1_1', 'obj_1_2')],
131
+ expected_order=['obj_1', 'obj_1_1', 'obj_1_2'],
132
+ ),
133
+ # 2 hierarchies, 2 objects each
134
+ dict(
135
+ parent_child_tuples=[('obj_1', 'obj_1_1'), ('obj_2', 'obj_2_1')],
136
+ expected_order=['obj_1', 'obj_1_1', 'obj_2', 'obj_2_1'],
137
+ ),
138
+ ])
139
+ def test_object_with_hierarchy(self, parent_child_tuples, expected_order):
140
+ objects = {}
141
+ for parent_name, child_name in parent_child_tuples:
142
+ parent = objects.get(parent_name, None)
143
+ if not parent:
144
+ parent = testing.build_mesh_object(parent_name)
145
+ objects[parent_name] = parent
146
+
147
+ child = testing.build_mesh_object(child_name, parent=parent)
148
+ objects[child_name] = child
149
+
150
+ context = mock.MagicMock(spec=bpy.types.Context)
151
+ context.scene.objects = [o for o in objects.values()]
152
+
153
+ object_names = blender_scene.map_blender_tree(context, lambda x: x.name)
154
+ self.assertEqual(object_names, expected_order)
155
+
156
+ def test_boneless_armature(self):
157
+ armature = testing.build_armature('armature')
158
+
159
+ context = mock.MagicMock(spec=bpy.types.Context)
160
+ context.scene.objects = [armature]
161
+
162
+ objects = blender_scene.map_blender_tree(context, lambda x: x)
163
+ self.assertLen(objects, 1)
164
+
165
+ def test_armature_with_bones(self):
166
+ root = testing.build_bone('root')
167
+ r_arm = testing.build_bone('r_arm', parent=root)
168
+ l_arm = testing.build_bone('l_arm', parent=root)
169
+ r_finger = testing.build_bone('r_finger', parent=r_arm)
170
+ armature = testing.build_armature(
171
+ 'armature', bones=[r_finger, l_arm, root, r_arm]
172
+ )
173
+ expected_order = [
174
+ 'armature',
175
+ 'root_armature',
176
+ 'r_arm_armature',
177
+ 'r_finger_armature',
178
+ 'l_arm_armature',
179
+ ]
180
+
181
+ context = mock.MagicMock(spec=bpy.types.Context)
182
+ # Randomize the order of objects to test the sorting mechanism.
183
+ context.scene.objects = [armature]
184
+
185
+ object_names = blender_scene.map_blender_tree(context, lambda x: x.name)
186
+ self.assertEqual(object_names, expected_order)
187
+
188
+
189
+ class DegreesOfFreedomTest(parameterized.TestCase):
190
+
191
+ def test_ik_with_unlimited_dofs_adds_all_dofs(self):
192
+ constraint = testing.build_rotation_constraint(
193
+ use_limit_x=False, use_limit_y=False, use_limit_z=False
194
+ )
195
+ bone = testing.build_bone('bone', constraint=constraint)
196
+ armature = testing.build_armature('bone', bones=[bone])
197
+ bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
198
+
199
+ dofs = bone_ref.get_rotation_dofs()
200
+ self.assertLen(dofs, 3)
201
+ self.assertEqual(dofs[0].axis, mathutils.Vector((1, 0, 0)))
202
+ self.assertEqual(dofs[1].axis, mathutils.Vector((0, 1, 0)))
203
+ self.assertEqual(dofs[2].axis, mathutils.Vector((0, 0, 1)))
204
+ self.assertFalse(dofs[0].limited)
205
+ self.assertFalse(dofs[1].limited)
206
+ self.assertFalse(dofs[2].limited)
207
+
208
+ def test_ik_with_removed_dofs(self):
209
+ constraint = testing.build_rotation_constraint(
210
+ lock_x=False,
211
+ lock_y=True,
212
+ lock_z=False,
213
+ use_limit_x=True,
214
+ use_limit_z=False,
215
+ )
216
+ bone = testing.build_bone('bone', constraint=constraint)
217
+ armature = testing.build_armature('bone', bones=[bone])
218
+ bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
219
+
220
+ dofs = bone_ref.get_rotation_dofs()
221
+ self.assertLen(dofs, 2)
222
+ self.assertEqual(dofs[0].axis, mathutils.Vector((1, 0, 0)))
223
+ self.assertEqual(dofs[1].axis, mathutils.Vector((0, 0, 1)))
224
+ self.assertTrue(dofs[0].limited)
225
+ self.assertFalse(dofs[1].limited)
226
+
227
+ def test_limiting_dof(self):
228
+ constraint = testing.build_rotation_constraint(
229
+ use_limit_x=True, min_x=math.radians(-15), max_x=math.radians(30)
230
+ )
231
+ bone = testing.build_bone('bone', constraint=constraint)
232
+ armature = testing.build_armature('bone', bones=[bone])
233
+ bone_ref = blender_scene.ObjectRef.new_bone(armature, bone)
234
+
235
+ dofs = bone_ref.get_rotation_dofs()
236
+ self.assertLen(dofs, 3)
237
+ self.assertTrue(dofs[0].limited)
238
+ self.assertFalse(dofs[1].limited)
239
+ self.assertFalse(dofs[2].limited)
240
+ np.testing.assert_array_almost_equal(dofs[0].limits, (-15, 30), 1e-2)
241
+
242
+
243
+ if __name__ == '__main__':
244
+ absltest.main()
data/dm_control/blender/mujoco_exporter/doc/add_ik_constraint.png ADDED

Git LFS Details

  • SHA256: 827539984a8696966de3e8cd74bf490574fae0a41e741122512ed261ed4859b7
  • Pointer size: 131 Bytes
  • Size of remote file: 124 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_blend.png ADDED

Git LFS Details

  • SHA256: 9dce9ffeb823f6bb427bab4daa4257f763670424ddcb8b66b15aec14c0466e56
  • Pointer size: 130 Bytes
  • Size of remote file: 58 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_mj_hull.png ADDED

Git LFS Details

  • SHA256: 92ae5482e2fa75e20a1b202e0200bebf10d03bb744c57fe59146a09661ee2769
  • Pointer size: 129 Bytes
  • Size of remote file: 8.85 kB
data/dm_control/blender/mujoco_exporter/doc/convhull_mj_rend.png ADDED

Git LFS Details

  • SHA256: d502c2af50033107da06d581b03987a253b82b485f13c8f556ddc1cd4d281d81
  • Pointer size: 130 Bytes
  • Size of remote file: 21 kB
data/dm_control/blender/mujoco_exporter/doc/enable_plugin.png ADDED

Git LFS Details

  • SHA256: d508011ce578fedb03e8d0b1d020b5b751767d8c7f032a911df9c6e411c296e1
  • Pointer size: 130 Bytes
  • Size of remote file: 50.2 kB
data/dm_control/blender/mujoco_exporter/doc/end_effector_selection.png ADDED

Git LFS Details

  • SHA256: fc942988ff433843f7ea15455283c3fc28a7b150005a20acfaf23b1fa5dc996b
  • Pointer size: 130 Bytes
  • Size of remote file: 70.8 kB
data/dm_control/blender/mujoco_exporter/doc/gizmo.png ADDED

Git LFS Details

  • SHA256: 30739e264fbfda7763a5544ebbab8ebe826926e3af43f2bcb54ba7a2d813d991
  • Pointer size: 131 Bytes
  • Size of remote file: 124 kB
data/dm_control/blender/mujoco_exporter/doc/ik_chain_length.png ADDED

Git LFS Details

  • SHA256: 121ab68439a7a1c22cd5fb927c5cfd5300ce9c368d69bac513dc3f89ce8d464e
  • Pointer size: 130 Bytes
  • Size of remote file: 68.5 kB
data/dm_control/blender/mujoco_exporter/doc/ik_target.png ADDED

Git LFS Details

  • SHA256: 8f7a28207cdee6fdf4b09f1eee4ba42627cefbcf2041ee07b942f0bf74768078
  • Pointer size: 131 Bytes
  • Size of remote file: 159 kB
data/dm_control/blender/mujoco_exporter/doc/install_plugin.png ADDED

Git LFS Details

  • SHA256: bd745eaefe02f528bd07b731c1a361a5fc1434e987039e3085426138c525113d
  • Pointer size: 130 Bytes
  • Size of remote file: 98.1 kB
data/dm_control/blender/mujoco_exporter/doc/limits.png ADDED

Git LFS Details

  • SHA256: 864a921e2655f30515dd53acb9b763cfe8f47f596394f9e1772303f48b021141
  • Pointer size: 131 Bytes
  • Size of remote file: 123 kB
data/dm_control/blender/mujoco_exporter/install.sh ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ set -euo pipefail
4
+
5
+ export output_dir="./addons/mujoco_model_exporter"
6
+ rm -rf "${output_dir}"
7
+ mkdir -p "${output_dir}"
8
+
9
+ cp ./*.py "${output_dir}"
10
+ find "${output_dir}" -name "*.py" -exec sed -i "s/from dm_control.blender.fake_core //g" "{}" +;
11
+ find "${output_dir}" -name "*.py" -exec sed -i "s/from dm_control.blender.mujoco_exporter/from ./g" "{}" +;
12
+ echo "Add-on exported to ${output_dir}."
13
+ echo "Copy this to Blender ./scripts/addons - see https://docs.blender.org/manual/en/latest/advanced/blender_directory_layout.html"
data/dm_control/blender/mujoco_exporter/mujoco_assets.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Mujoco asset exporters.
17
+
18
+ Note about Materials.
19
+ Material nodes are not supported, so please use basic Blender materials.
20
+ """
21
+
22
+ import os
23
+ import struct
24
+ from typing import Sequence
25
+ from xml.dom import minidom
26
+
27
+ from dm_control.blender.fake_core import bpy
28
+ from dm_control.blender.mujoco_exporter import blender_scene
29
+
30
+ _MESH = 'MESH'
31
+
32
+
33
+ class MujocoMesh:
34
+ """Mujoco representation of a mesh.
35
+
36
+ Mujoco can't handle meshes that reference multiple materials. Therefore
37
+ an instance of this class represents a submesh that uses a specific material.
38
+ """
39
+
40
+ def __init__(self, mesh: bpy.types.Mesh, material_idx: int, two_sided: bool):
41
+ if mesh.uv_layers.active is None:
42
+ raise ValueError(f'Mesh {mesh.name} does not have an active UV layer.')
43
+
44
+ mesh.calc_loop_triangles()
45
+
46
+ indices = []
47
+ for face in mesh.loop_triangles:
48
+ if face.material_index == material_idx:
49
+ indices.extend([i for i in face.vertices])
50
+
51
+ uv_layer = mesh.uv_layers.active.data
52
+ # pylint: disable=g-complex-comprehension
53
+ self.vertices = [c for i in indices for c in mesh.vertices[i].co]
54
+ self.normals = [c for i in indices for c in mesh.vertices[i].normal]
55
+ self.uvs = [c for i in indices for c in uv_layer[i].uv]
56
+ # pylint: enable=g-complex-comprehension
57
+ self.faces = list(range(len(self.vertices) // 3))
58
+
59
+ if two_sided:
60
+ # For two-sided meshes, duplicate the geometry with flipped normals
61
+ # and reversed triangle winding order.
62
+ base_vertex = len(self.vertices) // 3
63
+ self.vertices += list(self.vertices)
64
+ self.normals += [n * -1.0 for n in self.normals]
65
+ self.uvs += list(self.uvs)
66
+ self.faces += [i + base_vertex for i in reversed(self.faces)]
67
+
68
+ def save(self, filepath: str) -> None:
69
+ """Save the data in the MSH format."""
70
+ nvertex = len(self.vertices)
71
+ nnormal = len(self.normals)
72
+ ntexcoord = len(self.uvs)
73
+ nface = len(self.faces)
74
+ assert nvertex % 3 == 0
75
+ assert nnormal % 3 == 0
76
+ assert ntexcoord % 2 == 0
77
+ assert nface % 3 == 0
78
+
79
+ fmt_msh = '4i{}f{}f{}f{}i'.format(nvertex, nnormal, ntexcoord, nface)
80
+ with open(filepath, 'wb') as f:
81
+ f.write(
82
+ struct.pack(
83
+ fmt_msh,
84
+ nvertex // 3,
85
+ nnormal // 3,
86
+ ntexcoord // 2,
87
+ nface // 3,
88
+ *self.vertices,
89
+ *self.normals,
90
+ *self.uvs,
91
+ *self.faces,
92
+ )
93
+ )
94
+
95
+
96
+ def mesh_asset_builder(
97
+ doc: minidom.Document,
98
+ mesh: bpy.types.Mesh,
99
+ materials: Sequence[bpy.types.Material],
100
+ folder: str,
101
+ ) -> Sequence[minidom.Element]:
102
+ """Exports a mesh associated with the object and creates an 'asset' node."""
103
+ mat_names = blender_scene.map_materials(lambda m: m.name, materials)
104
+ twosidedness = blender_scene.map_materials(
105
+ lambda m: not m.use_backface_culling, materials
106
+ )
107
+ mat_names = mat_names or ['']
108
+ twosidedness = twosidedness or [False]
109
+
110
+ elements = []
111
+ for mat_idx, (mat_name, twosided) in enumerate(zip(mat_names, twosidedness)):
112
+ el_name = blender_scene.get_material_mesh_pair_name(mesh.name, mat_name)
113
+ filename = '{}.msh'.format(el_name)
114
+ filepath = os.path.join(folder, filename)
115
+
116
+ if blender_scene.is_material_mesh_pair_valid(mesh, mat_idx):
117
+ mesh_to_export = MujocoMesh(mesh, mat_idx, twosided)
118
+ mesh_to_export.save(filepath)
119
+
120
+ el = doc.createElement('mesh')
121
+ el.setAttribute('name', el_name)
122
+ el.setAttribute('file', filename)
123
+ elements.append(el)
124
+ return elements
125
+
126
+
127
+ def clip01(value):
128
+ return min(1.0, max(0.0, value))
129
+
130
+
131
+ def material_asset_builder(
132
+ doc: minidom.Document, mat: bpy.types.Material
133
+ ) -> minidom.Element:
134
+ """Builds a material asset node."""
135
+ el = doc.createElement('material')
136
+ el.setAttribute('name', mat.name)
137
+ # el.setAttribute('texture', '')
138
+ el.setAttribute('specular', str(clip01(mat.specular_intensity)))
139
+ el.setAttribute('shininess', str(clip01(1.0 - mat.roughness)))
140
+ el.setAttribute('reflectance', str(clip01(mat.metallic)))
141
+ el.setAttribute('rgba', ' '.join([str(c) for c in mat.diffuse_color]))
142
+ return el
143
+
144
+
145
+ def export_to_xml(
146
+ doc: minidom.Document,
147
+ objects: Sequence[blender_scene.ObjectRef],
148
+ folder: str,
149
+ apply_mesh_modifiers: bool,
150
+ ) -> minidom.Element:
151
+ """converts Blender scene objects to Mujoco assets."""
152
+ asset_el = doc.createElement('asset')
153
+
154
+ unique = set()
155
+ for obj in objects:
156
+ if obj.is_mesh and obj.mesh not in unique:
157
+ # Use the base mesh object as a reference, because that's the reference
158
+ # that will be shared between objects.
159
+ unique.add(obj.mesh)
160
+ if apply_mesh_modifiers:
161
+ # Make sure to export the mesh with modifiers applied, and if that's not
162
+ # possible (it may not be possible and None will be returned), default
163
+ # to the base mesh.
164
+ mesh_for_export = obj.get_modified_mesh() or obj.mesh
165
+ else:
166
+ mesh_for_export = obj.mesh
167
+ for el in mesh_asset_builder(doc, mesh_for_export, obj.materials, folder):
168
+ asset_el.appendChild(el)
169
+
170
+ for material in obj.materials:
171
+ if material not in unique:
172
+ unique.add(material)
173
+ asset_el.appendChild(material_asset_builder(doc, material))
174
+
175
+ return asset_el
data/dm_control/blender/mujoco_exporter/mujoco_assets_test.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for mujoco_assets.py."""
17
+
18
+ import collections
19
+ from unittest import mock
20
+ from xml.dom import minidom
21
+
22
+ from absl.testing import absltest
23
+ from absl.testing import parameterized
24
+ from dm_control.blender.mujoco_exporter import blender_scene
25
+ from dm_control.blender.mujoco_exporter import mujoco_assets
26
+ from dm_control.blender.mujoco_exporter import testing
27
+
28
+ _DEFAULT_SETTINGS = dict(folder='', apply_mesh_modifiers=False)
29
+
30
+
31
+ class MujocoAssetsTest(parameterized.TestCase):
32
+
33
+ def test_building_mesh_asset(self):
34
+ mesh_object = testing.build_mesh_object('mesh')
35
+
36
+ xml_root = mock.MagicMock(spec=minidom.Document)
37
+ xml_root.createElement = mock.MagicMock(spec=minidom.Element)
38
+
39
+ obj = blender_scene.ObjectRef(mesh_object)
40
+ with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()):
41
+ element = mujoco_assets.export_to_xml(
42
+ xml_root, [obj], **_DEFAULT_SETTINGS
43
+ )
44
+
45
+ xml_root.createElement.assert_any_call('mesh')
46
+ element.setAttribute.assert_any_call('name', 'mesh')
47
+ # Note there's no folder in the name.
48
+ # The asset is assumed to be exported into the same folder as the .xml file.
49
+ element.setAttribute.assert_any_call('file', 'mesh.msh')
50
+
51
+ def test_exporting_mesh_asset(self):
52
+ mesh = testing.build_mesh(name='mesh.001')
53
+ mesh_object = testing.build_mesh_object('mesh', mesh=mesh)
54
+ xml_root = mock.MagicMock(spec=minidom.Document)
55
+
56
+ obj = blender_scene.ObjectRef(mesh_object)
57
+ mock_open = mock.mock_open()
58
+ with mock.patch(mujoco_assets.__name__ + '.open', mock_open):
59
+ mujoco_assets.export_to_xml(xml_root, [obj], '/folder', False)
60
+ mock_open.assert_called_once_with('/folder/mesh.001.msh', 'wb')
61
+
62
+ def test_exporting_material_asset(self):
63
+ material = testing.build_material(
64
+ 'mat', color=(0.1, 0.2, 0.3, 0.4), specular=0.5, metallic=0.6
65
+ )
66
+ xml_root = mock.MagicMock(spec=minidom.Document)
67
+
68
+ result = mujoco_assets.material_asset_builder(xml_root, material)
69
+ result.setAttribute.assert_any_call('name', 'mat')
70
+ result.setAttribute.assert_any_call('specular', '0.5')
71
+ result.setAttribute.assert_any_call('reflectance', '0.6')
72
+ result.setAttribute.assert_any_call('rgba', '0.1 0.2 0.3 0.4')
73
+
74
+ @parameterized.parameters([
75
+ [0.0, 1.0],
76
+ [0.25, 0.75],
77
+ [0.5, 0.5],
78
+ [1.0, 0.0],
79
+ [5.0, 0.0],
80
+ [-5.0, 1.0],
81
+ ])
82
+ def test_shininess_is_inverse_of_blender_mat_roughness(self, blender, mujoco):
83
+ material = testing.build_material('mat', roughness=blender)
84
+ xml_root = mock.MagicMock(spec=minidom.Document)
85
+
86
+ result = mujoco_assets.material_asset_builder(xml_root, material)
87
+ result.setAttribute.assert_any_call('shininess', str(mujoco))
88
+
89
+ def test_export_unique_asset_instances(self):
90
+ num_objects = 10
91
+ shared_material = testing.build_material('mat_1')
92
+ shared_mesh = testing.build_mesh('mesh.001', materials=[shared_material])
93
+
94
+ objects = [
95
+ blender_scene.ObjectRef(
96
+ testing.build_mesh_object('mesh', mesh=shared_mesh)
97
+ )
98
+ for _ in range(num_objects)
99
+ ]
100
+ xml_root = mock.MagicMock(spec=minidom.Document)
101
+ with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()):
102
+ mujoco_assets.export_to_xml(xml_root, objects, **_DEFAULT_SETTINGS)
103
+
104
+ create_element_call_counts = collections.Counter(
105
+ [m_[0][0] for m_ in xml_root.createElement.call_args_list]
106
+ )
107
+ self.assertEqual(create_element_call_counts['mesh'], 1)
108
+ self.assertEqual(create_element_call_counts['material'], 1)
109
+
110
+ def test_mesh_with_multiple_materials_split(self):
111
+ mat_1 = testing.build_material('mat_1')
112
+ mat_2 = testing.build_material('mat_2')
113
+ mesh = testing.build_mesh(
114
+ 'mesh',
115
+ materials=[mat_1, mat_2],
116
+ faces=[[0, 1, 2], [3, 4, 5]],
117
+ vert_co=[
118
+ [0.1, 0.1, 0.1],
119
+ [0.2, 0.2, 0.2],
120
+ [0.3, 0.3, 0.3],
121
+ [0.4, 0.4, 0.4],
122
+ [0.5, 0.5, 0.5],
123
+ [0.6, 0.6, 0.6],
124
+ ],
125
+ mat_ids=[0, 1],
126
+ )
127
+
128
+ mesh_obj = blender_scene.ObjectRef(
129
+ testing.build_mesh_object('mesh', mesh=mesh)
130
+ )
131
+
132
+ with mock.patch(mujoco_assets.__name__ + '.open', mock.mock_open()):
133
+ xml_root = mock.MagicMock(spec=minidom.Document)
134
+ xml_elem = mock.MagicMock(spec=minidom.Element)
135
+ xml_root.createElement.return_value = xml_elem
136
+ mujoco_assets.export_to_xml(xml_root, [mesh_obj], **_DEFAULT_SETTINGS)
137
+
138
+ # Verify that two mesh elements were created...
139
+ create_element_call_counts = collections.Counter(
140
+ [m_[0][0] for m_ in xml_root.createElement.call_args_list]
141
+ )
142
+ self.assertEqual(create_element_call_counts['mesh'], 2)
143
+
144
+ # ...and that their names reflect the mesh-material pairing.
145
+ xml_elem.setAttribute.assert_any_call('file', 'mesh_mat_1.msh')
146
+ xml_elem.setAttribute.assert_any_call('file', 'mesh_mat_2.msh')
147
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_mat_1')
148
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_mat_2')
149
+
150
+
151
+ class MujocoMeshTests(parameterized.TestCase):
152
+
153
+ def test_splitting_mesh_with_multiple_materials_into_submeshes(self):
154
+ mat_0 = testing.build_material('mat_0')
155
+ mat_1 = testing.build_material('mat_1')
156
+ mesh = testing.build_mesh(
157
+ 'mesh',
158
+ materials=[mat_0, mat_1],
159
+ faces=[[0, 1, 2], [3, 4, 5]],
160
+ vert_co=[
161
+ [0.1, 0.1, 0.1],
162
+ [0.2, 0.2, 0.2],
163
+ [0.3, 0.3, 0.3],
164
+ [0.4, 0.4, 0.4],
165
+ [0.5, 0.5, 0.5],
166
+ [0.6, 0.6, 0.6],
167
+ ],
168
+ mat_ids=[0, 1],
169
+ )
170
+
171
+ mesh_mat_0 = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=False)
172
+ mesh_mat_1 = mujoco_assets.MujocoMesh(mesh, material_idx=1, two_sided=False)
173
+
174
+ self.assertEqual(
175
+ mesh_mat_0.vertices, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3]
176
+ )
177
+ self.assertEqual(
178
+ mesh_mat_1.vertices, [0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.6, 0.6, 0.6]
179
+ )
180
+ self.assertEqual(mesh_mat_0.faces, [0, 1, 2])
181
+ self.assertEqual(mesh_mat_1.faces, [0, 1, 2])
182
+
183
+ def test_one_sided_mesh(self):
184
+ mesh = testing.build_mesh(
185
+ 'mesh',
186
+ materials=[testing.build_material('mat')],
187
+ faces=[[0, 1, 2]],
188
+ vert_co=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]],
189
+ normals=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]],
190
+ mat_ids=[0],
191
+ )
192
+
193
+ mesh = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=False)
194
+ self.assertEqual(mesh.faces, [0, 1, 2])
195
+ self.assertEqual(
196
+ mesh.vertices, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3]
197
+ )
198
+ self.assertEqual(
199
+ mesh.normals, [0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3]
200
+ )
201
+
202
+ def test_two_sided_mesh(self):
203
+ mesh = testing.build_mesh(
204
+ 'mesh',
205
+ materials=[testing.build_material('mat')],
206
+ faces=[[0, 1, 2]],
207
+ vert_co=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]],
208
+ normals=[[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]],
209
+ mat_ids=[0],
210
+ )
211
+
212
+ mesh = mujoco_assets.MujocoMesh(mesh, material_idx=0, two_sided=True)
213
+ self.assertEqual(mesh.faces, [0, 1, 2, 5, 4, 3])
214
+ self.assertEqual(
215
+ mesh.vertices,
216
+ [.1, .1, .1, .2, .2, .2, .3, .3, .3,
217
+ .1, .1, .1, .2, .2, .2, .3, .3, .3,])
218
+ self.assertEqual(
219
+ mesh.normals,
220
+ [.1, .1, .1, .2, .2, .2, .3, .3, .3,
221
+ -.1, -.1, -.1, -.2, -.2, -.2, -.3, -.3, -.3,])
222
+
223
+
224
+ if __name__ == '__main__':
225
+ absltest.main()
data/dm_control/blender/mujoco_exporter/mujoco_scene.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Mujoco scene element builders and utilities."""
17
+
18
+ from typing import Sequence
19
+ from xml.dom import minidom
20
+
21
+ from dm_control.blender.fake_core import mathutils
22
+ from dm_control.blender.mujoco_exporter import blender_scene
23
+
24
+ _ARMATURE = 'ARMATURE'
25
+ _MESH = 'MESH'
26
+ _VEC_ZERO = mathutils.Vector((0, 0, 0))
27
+ _OZ = mathutils.Vector((0, 0, 1))
28
+
29
+
30
+ def color_to_mjcf(color: mathutils.Color) -> str:
31
+ return '{} {} {}'.format(color.r, color.g, color.b)
32
+
33
+
34
+ def vec_to_mjcf(vec: mathutils.Vector) -> str:
35
+ return '{} {} {}'.format(vec.x, vec.y, vec.z)
36
+
37
+
38
+ def quat_to_mjcf(quat: mathutils.Quaternion) -> str:
39
+ return '{} {} {} {}'.format(quat.w, quat.x, quat.y, quat.z)
40
+
41
+
42
+ def bool_to_mjcf(bool_val: bool):
43
+ return 'true' if bool_val else 'false'
44
+
45
+
46
+ def body_builder(
47
+ doc: minidom.Document, blender_obj: blender_scene.ObjectRef
48
+ ) -> minidom.Element:
49
+ """Builds a mujoco body element."""
50
+ transform = blender_obj.get_local_transform()
51
+
52
+ el = doc.createElement('body')
53
+ el.setAttribute('name', blender_obj.name)
54
+ el.setAttribute('pos', vec_to_mjcf(transform.pos))
55
+ el.setAttribute('quat', quat_to_mjcf(transform.rot))
56
+ return el
57
+
58
+
59
+ def light_builder(
60
+ doc: minidom.Document, light_obj: blender_scene.ObjectRef
61
+ ) -> minidom.Element:
62
+ """Builds an mjcf element that describes a light."""
63
+ assert light_obj.is_light
64
+ light = light_obj.as_light()
65
+
66
+ directional = bool_to_mjcf(light.type == 'SUN' or light.type == 'SPOT')
67
+ attenuation = '0 {} {}'.format(
68
+ light.linear_attenuation, light.quadratic_attenuation
69
+ )
70
+ transform = light_obj.get_local_transform()
71
+
72
+ el = doc.createElement('light')
73
+ el.setAttribute('name', light_obj.name)
74
+ el.setAttribute('pos', vec_to_mjcf(transform.pos))
75
+ el.setAttribute('dir', vec_to_mjcf(transform.rot @ _OZ))
76
+ el.setAttribute('directional', directional)
77
+ el.setAttribute('castshadow', bool_to_mjcf(light.use_shadow)) # pytype: disable=wrong-arg-types
78
+ el.setAttribute('diffuse', color_to_mjcf(light.color))
79
+ el.setAttribute('attenuation', attenuation)
80
+ return el
81
+
82
+
83
+ def mesh_geom_builder(
84
+ doc: minidom.Document, mesh_obj: blender_scene.ObjectRef
85
+ ) -> Sequence[minidom.Element]:
86
+ """Builds a mujoco node for a mesh geom."""
87
+ mesh = mesh_obj.mesh
88
+ transform = mesh_obj.get_local_transform()
89
+
90
+ elements = []
91
+ mat_names = blender_scene.map_materials(lambda m: m.name, mesh_obj.materials)
92
+ # It might be the case that the mesh doesn't have any materials assigned.
93
+ # We still want to export such geom, but we don't want to make a reference to
94
+ # the material in the node.
95
+ # So in that case we're using a fake material without a name
96
+ mat_names = mat_names or ['']
97
+ for mat_idx, mat_name in enumerate(mat_names):
98
+ if not blender_scene.is_material_mesh_pair_valid(mesh, mat_idx):
99
+ continue
100
+
101
+ obj_name = blender_scene.get_material_mesh_pair_name(
102
+ mesh_obj.name, mat_name
103
+ )
104
+ mesh_name = blender_scene.get_material_mesh_pair_name(mesh.name, mat_name)
105
+
106
+ el = doc.createElement('geom')
107
+ el.setAttribute('name', obj_name)
108
+ el.setAttribute('mesh', mesh_name)
109
+ el.setAttribute('pos', vec_to_mjcf(transform.pos))
110
+ el.setAttribute('quat', quat_to_mjcf(transform.rot))
111
+ el.setAttribute('type', 'mesh')
112
+ if mat_name:
113
+ el.setAttribute('material', mat_name)
114
+
115
+ elements.append(el)
116
+
117
+ return elements
118
+
119
+
120
+ def joint_builder(
121
+ doc: minidom.Document,
122
+ dof: blender_scene.Dof,
123
+ dof_type: str,
124
+ ) -> minidom.Element:
125
+ """Builds a mujoco hinge definition."""
126
+ el = doc.createElement('joint')
127
+ el.setAttribute('name', dof.name)
128
+ el.setAttribute('type', dof_type)
129
+ el.setAttribute('limited', bool_to_mjcf(dof.limited))
130
+ el.setAttribute('pos', vec_to_mjcf(_VEC_ZERO))
131
+ el.setAttribute('axis', vec_to_mjcf(dof.axis))
132
+ el.setAttribute('range', '{} {}'.format(dof.limits[0], dof.limits[1]))
133
+ return el
134
+
135
+
136
+ def export_to_xml(
137
+ doc: minidom.Document,
138
+ objects: Sequence[blender_scene.ObjectRef],
139
+ armature_freejoint: bool,
140
+ ) -> minidom.Element:
141
+ """Converts Blender scene objects to Mujoco scene tree nodes."""
142
+ root = doc.createElement('worldbody')
143
+ parent_elements = {blender_scene.NoneRef: root}
144
+
145
+ for obj in objects:
146
+ # Build a subtree corresponding to this Blender object.
147
+ element = None
148
+ if obj.is_armature:
149
+ element = body_builder(doc, obj)
150
+ if armature_freejoint:
151
+ element.appendChild(doc.createElement('freejoint'))
152
+ elif obj.is_mesh:
153
+ if not obj.parent.is_none and not obj.parent.is_bone:
154
+ raise RuntimeError(
155
+ 'Mesh "{}" is parented to an object "{}", which is not a bone. '
156
+ 'Only mesh->bone parenting is supported at the moment'.format(
157
+ obj.name, obj.parent.name
158
+ )
159
+ )
160
+ geom_elements = mesh_geom_builder(doc, obj)
161
+ if len(geom_elements) > 1:
162
+ # If there's more than one geom, introduce a body to aggregate them
163
+ # under a single element. That element will then be associated with this
164
+ # blender object should other blender elements be parented to it.
165
+ element = doc.createElement('body')
166
+ for geom_el in geom_elements:
167
+ element.appendChild(geom_el)
168
+ elif len(geom_elements) == 1:
169
+ # Since there's only one geom, consider it the main element
170
+ element = geom_elements[0]
171
+ elif obj.is_light:
172
+ element = light_builder(doc, obj)
173
+ elif obj.is_bone:
174
+ element = body_builder(doc, obj)
175
+ for dof in obj.get_rotation_dofs():
176
+ element.appendChild(joint_builder(doc, dof, 'hinge'))
177
+
178
+ # Inject it into the scene tree.
179
+ if element:
180
+ parent = obj.parent
181
+ if parent:
182
+ parent_el = parent_elements[parent]
183
+ parent_el.appendChild(element)
184
+ parent_elements[obj] = element
185
+ else:
186
+ root.appendChild(element)
187
+
188
+ return root
data/dm_control/blender/mujoco_exporter/mujoco_scene_test.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Tests for mujoco_scene.py."""
17
+
18
+ import collections
19
+ from unittest import mock
20
+ from xml.dom import minidom
21
+ from absl.testing import absltest
22
+ from absl.testing import parameterized
23
+ from dm_control.blender.mujoco_exporter import blender_scene
24
+ from dm_control.blender.mujoco_exporter import mujoco_scene
25
+ from dm_control.blender.mujoco_exporter import testing
26
+
27
+ _DEFAULT_PARAMS = dict(armature_freejoint=False)
28
+
29
+
30
+ class ConverterTest(parameterized.TestCase):
31
+
32
+ def test_convert_armature(self):
33
+ armature = testing.build_armature('armature')
34
+ xml_root = mock.MagicMock(spec=minidom.Document)
35
+ xml_root.createElement = mock.MagicMock(spec=minidom.Element)
36
+
37
+ obj = blender_scene.ObjectRef(armature)
38
+ created_element = mujoco_scene.export_to_xml(
39
+ xml_root, [obj], **_DEFAULT_PARAMS
40
+ )
41
+
42
+ xml_root.createElement.assert_any_call('body')
43
+ created_element.setAttribute.assert_any_call('name', 'armature')
44
+
45
+ def test_convert_bone_without_constraints_creates_a_body(self):
46
+ bone = testing.build_bone('bone')
47
+ armature = testing.build_armature('armature', bones=[bone])
48
+
49
+ xml_root = mock.MagicMock(spec=minidom.Document)
50
+ xml_root.createElement.side_effect = mock.MagicMock(spec=minidom.Element)
51
+
52
+ bone_obj = blender_scene.ObjectRef(armature, bone)
53
+ armature_obj = blender_scene.ObjectRef(armature)
54
+ created_element = mujoco_scene.export_to_xml(
55
+ xml_root, [armature_obj, bone_obj], **_DEFAULT_PARAMS
56
+ )
57
+
58
+ xml_root.createElement.assert_any_call('body')
59
+ created_element.setAttribute.assert_any_call('name', 'bone_armature')
60
+
61
+ @parameterized.parameters([
62
+ # Point light
63
+ dict(
64
+ args=dict(lin_att=1, quad_att=2, shadow=True, light_type='POINT'),
65
+ out=dict(castshadow='true', attenuation='0 1 2', directional='false'),
66
+ ),
67
+ # Spot light
68
+ dict(
69
+ args=dict(lin_att=3, quad_att=4, shadow=True, light_type='SPOT'),
70
+ out=dict(castshadow='true', attenuation='0 3 4', directional='true'),
71
+ ),
72
+ # Directional light
73
+ dict(
74
+ args=dict(lin_att=5, quad_att=6, shadow=True, light_type='SUN'),
75
+ out=dict(castshadow='true', attenuation='0 5 6', directional='true'),
76
+ ),
77
+ # Shadows off
78
+ dict(
79
+ args=dict(lin_att=7, quad_att=8, shadow=False, light_type='SUN'),
80
+ out=dict(castshadow='false', attenuation='0 7 8', directional='true'),
81
+ ),
82
+ ])
83
+ def test_convert_light(self, args, out):
84
+ light = testing.build_light('light', **args)
85
+
86
+ xml_root = mock.MagicMock(spec=minidom.Document)
87
+ xml_root.createElement = mock.MagicMock(spec=minidom.Element)
88
+
89
+ obj = blender_scene.ObjectRef(light)
90
+ created_element = mujoco_scene.export_to_xml(
91
+ xml_root, [obj], **_DEFAULT_PARAMS
92
+ )
93
+
94
+ xml_root.createElement.assert_any_call('light')
95
+ created_element.setAttribute.assert_any_call('name', 'light')
96
+ for k, v in out.items():
97
+ created_element.setAttribute.assert_any_call(k, v)
98
+
99
+ def test_exported_mesh_references_mesh_asset_by_name(self):
100
+ mesh = testing.build_mesh('mesh_asset_name')
101
+ mesh_obj = testing.build_mesh_object('mesh_object_name', mesh=mesh)
102
+
103
+ xml_root = mock.MagicMock(spec=minidom.Document)
104
+ xml_root.createElement = mock.MagicMock(spec=minidom.Element)
105
+
106
+ obj = blender_scene.ObjectRef(mesh_obj)
107
+ created_element = mujoco_scene.export_to_xml(
108
+ xml_root, [obj], **_DEFAULT_PARAMS
109
+ )
110
+
111
+ xml_root.createElement.assert_any_call('geom')
112
+ created_element.setAttribute.assert_any_call('name', 'mesh_object_name')
113
+ created_element.setAttribute.assert_any_call('mesh', 'mesh_asset_name')
114
+
115
+ def test_mesh_with_no_material_keeps_its_name(self):
116
+ mesh = testing.build_mesh('mesh')
117
+ mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh)
118
+ obj = blender_scene.ObjectRef(mesh_obj)
119
+
120
+ xml_root = mock.MagicMock(spec=minidom.Document)
121
+ xml_elem = mock.MagicMock(spec=minidom.Element)
122
+ xml_root.createElement.return_value = xml_elem
123
+ mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
124
+
125
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_obj')
126
+ xml_elem.setAttribute.assert_any_call('mesh', 'mesh')
127
+
128
+ def test_mesh_with_materials_builds_multiple_geoms(self):
129
+ mesh = testing.build_mesh(
130
+ 'mesh',
131
+ materials=[
132
+ testing.build_material('mat_1'),
133
+ testing.build_material('mat_2'),
134
+ ],
135
+ faces=[[0, 1, 2], [3, 4, 5]],
136
+ vert_co=[
137
+ [0.1, 0.1, 0.1],
138
+ [0.2, 0.2, 0.2],
139
+ [0.3, 0.3, 0.3],
140
+ [0.4, 0.4, 0.4],
141
+ [0.5, 0.5, 0.5],
142
+ [0.6, 0.6, 0.6],
143
+ ],
144
+ mat_ids=[0, 1],
145
+ )
146
+ mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh)
147
+
148
+ xml_root = mock.MagicMock(spec=minidom.Document)
149
+ xml_elem = mock.MagicMock(spec=minidom.Element)
150
+ xml_root.createElement.return_value = xml_elem
151
+
152
+ obj = blender_scene.ObjectRef(mesh_obj)
153
+ mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
154
+
155
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_1')
156
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_2')
157
+ xml_elem.setAttribute.assert_any_call('mesh', 'mesh_mat_1')
158
+ xml_elem.setAttribute.assert_any_call('mesh', 'mesh_mat_2')
159
+
160
+ def test_empty_submeshes_are_not_exported(self):
161
+ mesh = testing.build_mesh(
162
+ 'mesh',
163
+ materials=[
164
+ testing.build_material('mat_1'),
165
+ testing.build_material('mat_2'),
166
+ ],
167
+ faces=[[0, 1, 2], [3, 4, 5]],
168
+ vert_co=[
169
+ [0.1, 0.1, 0.1],
170
+ [0.2, 0.2, 0.2],
171
+ [0.3, 0.3, 0.3],
172
+ [0.4, 0.4, 0.4],
173
+ [0.5, 0.5, 0.5],
174
+ [0.6, 0.6, 0.6],
175
+ ],
176
+ mat_ids=[0, 0],
177
+ ) # All faces reference material 0
178
+ mesh_obj = testing.build_mesh_object('mesh_obj', mesh=mesh)
179
+
180
+ xml_root = mock.MagicMock(spec=minidom.Document)
181
+ xml_elem = mock.MagicMock(spec=minidom.Element)
182
+ xml_root.createElement.return_value = xml_elem
183
+
184
+ obj = blender_scene.ObjectRef(mesh_obj)
185
+ mujoco_scene.export_to_xml(xml_root, [obj], **_DEFAULT_PARAMS)
186
+
187
+ create_element_call_counts = collections.Counter(
188
+ [m_[0][0] for m_ in xml_root.createElement.call_args_list]
189
+ )
190
+ self.assertEqual(create_element_call_counts['geom'], 1)
191
+ xml_elem.setAttribute.assert_any_call('name', 'mesh_obj_mat_1')
192
+
193
+
194
+ if __name__ == '__main__':
195
+ absltest.main()
data/dm_control/blender/mujoco_exporter/testing.py ADDED
@@ -0,0 +1,198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Testing utilities."""
17
+ from typing import Any, Optional, Sequence
18
+ from unittest import mock
19
+
20
+ from dm_control.blender.fake_core import bpy
21
+
22
+
23
+ class FakePropCollection:
24
+ """Collection that simulates bpy_prop_collection.
25
+
26
+ Armature's bone collection is modeled using it, and the tested code depends
27
+ on some of its features - namely the conversion to list produces dict
28
+ values instead of its keys, as well as the collection behaving like a dict
29
+ otherwise.
30
+
31
+ @see
32
+ blender_scene.py : map_blender_tree - iterating over armature.data.bones
33
+ blender_scene.py : ObjectRef.parent.object_parent - dereferencing bone
34
+ by its name armature.data.bones[obj.parent_bone]
35
+ """
36
+
37
+ def __init__(self, objects_with_name):
38
+ if objects_with_name:
39
+ self._keys = [i.name for i in objects_with_name]
40
+ else:
41
+ self._keys = []
42
+ self._values = objects_with_name or []
43
+
44
+ def __len__(self):
45
+ return len(self._values)
46
+
47
+ def __getitem__(self, idx):
48
+ if isinstance(idx, str):
49
+ idx = self._keys.index(idx)
50
+ return self._values[idx]
51
+
52
+ def __iter__(self):
53
+ return iter(self._values)
54
+
55
+ def __contains__(self, key):
56
+ return key in self._keys
57
+
58
+ def keys(self):
59
+ return self._keys
60
+
61
+ def values(self):
62
+ return self._values
63
+
64
+ def items(self):
65
+ return list(zip(self._keys, self._values))
66
+
67
+
68
+ def build_armature(
69
+ name: str,
70
+ parent: Optional[Any] = None,
71
+ parent_bone: Optional[str] = None,
72
+ bones: Optional[Any] = None,
73
+ ):
74
+ """TBD."""
75
+ obj = mock.MagicMock(spec=bpy.types.Object, type='ARMATURE')
76
+ obj.name = name
77
+ obj.parent = parent
78
+ obj.parent_bone = parent_bone
79
+ obj.data = mock.MagicMock()
80
+ obj.data.bones = FakePropCollection(bones)
81
+ obj.pose = mock.MagicMock()
82
+ obj.pose.bones = FakePropCollection(bones)
83
+ return obj
84
+
85
+
86
+ def build_bone(name, parent=None, constraint=None):
87
+ """Builds a mock bone."""
88
+ bone = mock.MagicMock(spec=bpy.types.Bone)
89
+ bone.name = name
90
+ bone.parent = parent
91
+ bone.is_in_ik_chain = constraint is not None
92
+ bone.lock_ik_x = constraint.lock_x if constraint else False
93
+ bone.use_ik_limit_x = constraint.use_limit_x if constraint else False
94
+ bone.ik_min_x = constraint.min_x if constraint else 0.0
95
+ bone.ik_max_x = constraint.max_x if constraint else 0.0
96
+ bone.lock_ik_y = constraint.lock_y if constraint else False
97
+ bone.use_ik_limit_y = constraint.use_limit_y if constraint else False
98
+ bone.ik_min_y = constraint.min_y if constraint else 0.0
99
+ bone.ik_max_y = constraint.max_y if constraint else 0.0
100
+ bone.lock_ik_z = constraint.lock_z if constraint else False
101
+ bone.use_ik_limit_z = constraint.use_limit_z if constraint else False
102
+ bone.ik_min_z = constraint.min_z if constraint else 0.0
103
+ bone.ik_max_z = constraint.max_z if constraint else 0.0
104
+ return bone
105
+
106
+
107
+ def build_rotation_constraint(
108
+ lock_x=False, use_limit_x=False, min_x=0, max_x=1,
109
+ lock_y=False, use_limit_y=False, min_y=0, max_y=1,
110
+ lock_z=False, use_limit_z=False, min_z=0, max_z=1):
111
+ """Builds a mock rotation constraint."""
112
+ c = mock.MagicMock()
113
+ c.lock_x = lock_x
114
+ c.use_limit_x = use_limit_x
115
+ c.min_x = min_x
116
+ c.max_x = max_x
117
+ c.lock_y = lock_y
118
+ c.use_limit_y = use_limit_y
119
+ c.min_y = min_y
120
+ c.max_y = max_y
121
+ c.lock_z = lock_z
122
+ c.use_limit_z = use_limit_z
123
+ c.min_z = min_z
124
+ c.max_z = max_z
125
+ return c
126
+
127
+
128
+ def build_mesh(
129
+ name, materials=None, faces=None, vert_co=None, normals=None, mat_ids=None
130
+ ):
131
+ """Builds a mock triangle mesh."""
132
+ materials = materials or []
133
+ faces = faces or [[0, 1, 2]]
134
+ vert_co = vert_co or [[0.1, 0.1, 0.1], [0.2, 0.2, 0.2], [0.3, 0.3, 0.3]]
135
+ normals = normals or vert_co
136
+ mat_ids = mat_ids or [0] * len(faces)
137
+
138
+ obj = mock.MagicMock(spec=bpy.types.Mesh)
139
+ obj.name = name
140
+ obj.materials = materials
141
+ obj.uv_layers = mock.MagicMock()
142
+ obj.loop_triangles = [
143
+ mock.MagicMock(vertices=f, material_index=i)
144
+ for f, i in zip(faces, mat_ids)
145
+ ]
146
+ obj.vertices = [
147
+ mock.MagicMock(co=c, normal=n) for c, n in zip(vert_co, normals)
148
+ ]
149
+
150
+ return obj
151
+
152
+
153
+ def build_mesh_object(
154
+ name: str,
155
+ mesh: Optional[Any] = None,
156
+ parent: Optional[Any] = None,
157
+ parent_bone: Optional[str] = None,
158
+ ):
159
+ """Builds a mock object with a mesh assigned to it."""
160
+ obj = mock.MagicMock(spec=bpy.types.Object, type='MESH')
161
+ obj.name = name
162
+ obj.parent = parent
163
+ obj.parent_bone = parent_bone
164
+ obj.data = mesh or build_mesh(name)
165
+ return obj
166
+
167
+
168
+ def build_light(name, light_type, lin_att, quad_att, shadow):
169
+ """Builds a mock light."""
170
+ obj = mock.MagicMock(spec=bpy.types.Object, type='LIGHT')
171
+ obj.name = name
172
+ obj.parent = None
173
+ obj.parent_bone = None
174
+ obj.data = mock.MagicMock(spec=bpy.types.Light)
175
+ obj.data.type = light_type
176
+ obj.data.linear_attenuation = lin_att
177
+ obj.data.quadratic_attenuation = quad_att
178
+ obj.data.use_shadow = shadow
179
+ return obj
180
+
181
+
182
+ def build_material(
183
+ name: str,
184
+ color: Sequence[int] = (1, 1, 1, 1),
185
+ specular: float = 0.5,
186
+ metallic: float = 0.0,
187
+ roughness: float = 0.5,
188
+ use_backface_culling: bool = False,
189
+ ):
190
+ """Builds a mock material definition."""
191
+ obj = mock.MagicMock(spec=bpy.types.Material)
192
+ obj.name = name
193
+ obj.diffuse_color = color
194
+ obj.specular_intensity = specular
195
+ obj.metallic = metallic
196
+ obj.roughness = roughness
197
+ obj.use_backface_culling = use_backface_culling
198
+ return obj
data/dm_control/composer/__init__.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018-2019 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """Module containing abstract base classes for Composer environments."""
17
+
18
+ from dm_control.composer.arena import Arena
19
+ from dm_control.composer.constants import * # pylint: disable=wildcard-import
20
+ from dm_control.composer.define import cached_property
21
+ from dm_control.composer.define import observable
22
+ from dm_control.composer.entity import Entity
23
+ from dm_control.composer.entity import FreePropObservableMixin
24
+ from dm_control.composer.entity import ModelWrapperEntity
25
+ from dm_control.composer.entity import Observables
26
+ from dm_control.composer.environment import Environment
27
+ from dm_control.composer.environment import EpisodeInitializationError
28
+ from dm_control.composer.environment import HOOK_NAMES
29
+ from dm_control.composer.environment import ObservationPadding
30
+ from dm_control.composer.initializer import Initializer
31
+ from dm_control.composer.robot import Robot
32
+ from dm_control.composer.task import NullTask
33
+ from dm_control.composer.task import Task
data/dm_control/composer/arena.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2018 The dm_control Authors.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+
16
+ """The base empty arena that defines global settings for Composer."""
17
+
18
+ import os
19
+
20
+ from dm_control import mjcf
21
+ from dm_control.composer import entity as entity_module
22
+
23
+ _ARENA_XML_PATH = os.path.join(os.path.dirname(__file__), 'arena.xml')
24
+
25
+
26
+ class Arena(entity_module.Entity):
27
+ """The base empty arena that defines global settings for Composer."""
28
+
29
+ def __init__(self, *args, **kwargs):
30
+ self._mjcf_root = None # Declare that _mjcf_root exists to allay pytype.
31
+ super().__init__(*args, **kwargs)
32
+
33
+ # _build uses *args and **kwargs rather than named arguments, to get
34
+ # around a signature-mismatch error from pytype in derived classes.
35
+
36
+ def _build(self, *args, **kwargs) -> None:
37
+ """Initializes this arena.
38
+
39
+ The function takes two arguments through args, kwargs:
40
+ name: A string, the name of this arena. If `None`, use the model name
41
+ defined in the MJCF file.
42
+ xml_path: An optional path to an XML file that will override the default
43
+ composer arena MJCF.
44
+
45
+ Args:
46
+ *args: See above.
47
+ **kwargs: See above.
48
+ """
49
+ if args:
50
+ name = args[0]
51
+ else:
52
+ name = kwargs.get('name', None)
53
+ if len(args) > 1:
54
+ xml_path = args[1]
55
+ else:
56
+ xml_path = kwargs.get('xml_path', None)
57
+
58
+ self._mjcf_root = mjcf.from_path(xml_path or _ARENA_XML_PATH)
59
+ if name:
60
+ self._mjcf_root.model = name
61
+
62
+ def add_free_entity(self, entity):
63
+ """Includes an entity in the arena as a free-moving body."""
64
+ frame = self.attach(entity)
65
+ frame.add('freejoint')
66
+ return frame
67
+
68
+ @property
69
+ def mjcf_model(self):
70
+ return self._mjcf_root