Skip to content

Commit 508d13c

Browse files
committed
formatting
1 parent 865d7c0 commit 508d13c

File tree

7 files changed

+113
-141
lines changed

7 files changed

+113
-141
lines changed

python/mujoco/usd/camera.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@
1616

1717
from typing import List, Optional, Tuple
1818

19-
import mujoco.usd.utils as utils_module
20-
2119
import numpy as np
22-
2320
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.
2421
# pytype: disable=module-attr
2522
from pxr import Gf
@@ -28,9 +25,10 @@
2825

2926
import mujoco.usd.utils as utils_module
3027

28+
3129
class USDCamera:
3230
"""Class that handles the cameras in the USD scene"""
33-
31+
3432
def __init__(self, stage: Usd.Stage, camera_name: str):
3533
self.stage = stage
3634

python/mujoco/usd/demo.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -37,16 +37,14 @@ def generate_usd_trajectory(local_args):
3737
)
3838

3939
cam = mujoco.MjvCamera()
40-
40+
4141
# step through the simulation for the given duration of time
4242
while d.time < local_args.duration:
4343
mujoco.mj_step(m, d)
4444
if exp.frame_count < d.time * local_args.framerate:
4545
exp.update_scene(data=d, camera=cam)
4646

47-
exp.add_light(pos=(0, 0, 0),
48-
intensity=2000,
49-
light_type='dome')
47+
exp.add_light(pos=(0, 0, 0), intensity=2000, light_type='dome')
5048

5149
exp.save_scene(filetype=local_args.export_extension)
5250

@@ -81,10 +79,7 @@ def generate_usd_trajectory(local_args):
8179
)
8280

8381
parser.add_argument(
84-
'--camera_names',
85-
type=str,
86-
nargs='+',
87-
help='cameras to include in usd'
82+
'--camera_names', type=str, nargs='+', help='cameras to include in usd'
8883
)
8984

9085
parser.add_argument(

python/mujoco/usd/exporter.py

Lines changed: 53 additions & 80 deletions
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,27 @@
1717
import os
1818
from typing import List, Optional, Tuple, Union
1919

20-
import mujoco
21-
from mujoco import _structs, _enums, _functions
22-
23-
import mujoco.usd.camera as camera_module
24-
import mujoco.usd.lights as light_module
25-
import mujoco.usd.objects as object_module
26-
import mujoco.usd.shapes as shapes_module
27-
import mujoco.usd.utils as utils_module
2820
import numpy as np
2921
from PIL import Image as im
3022
from PIL import ImageOps
31-
3223
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.
3324
# pytype: disable=module-attr
3425
from pxr import Sdf
3526
from pxr import Usd
3627
from pxr import UsdGeom
3728

29+
import mujoco
30+
from mujoco import _enums
31+
from mujoco import _functions
32+
from mujoco import _structs
33+
import mujoco.usd.camera as camera_module
34+
import mujoco.usd.lights as light_module
35+
import mujoco.usd.objects as object_module
36+
import mujoco.usd.shapes as shapes_module
37+
3838
PRIMARY_CAMERA_NAME = "primary_camera"
3939

40+
4041
class USDExporter:
4142
"""MuJoCo to USD exporter for porting scenes to external renderers."""
4243

@@ -139,48 +140,6 @@ def _initialize_output_directories(self):
139140
if self.verbose:
140141
print(f"Writing output frames and assets to {self.output_directory_path}")
141142

142-
def _update_scene(
143-
self,
144-
data: mujoco.MjData,
145-
camera: Union[int, str] = -1,
146-
scene_option: Optional[mujoco.MjvOption] = None,
147-
):
148-
"""Updates the scene."""
149-
camera_id = camera
150-
if isinstance(camera_id, str):
151-
camera_id = mujoco.mj_name2id(
152-
self.model, mujoco.mjtObj.mjOBJ_CAMERA.value, camera_id
153-
)
154-
if camera_id == -1:
155-
raise ValueError(f"The camera '{camera}' does not exist.")
156-
if camera_id < -1 or camera_id >= self.model.ncam:
157-
raise ValueError(
158-
f"The camera id {camera_id} is out of range [-1, {self.model.ncam})."
159-
)
160-
161-
# Render camera.
162-
camera = mujoco.MjvCamera()
163-
camera.fixedcamid = camera_id
164-
165-
# Defaults to mjCAMERA_FREE, otherwise mjCAMERA_FIXED refers to a
166-
# camera explicitly defined in the model.
167-
if camera_id == -1:
168-
camera.type = mujoco.mjtCamera.mjCAMERA_FREE
169-
mujoco.mjv_defaultFreeCamera(self.model, camera)
170-
else:
171-
camera.type = mujoco.mjtCamera.mjCAMERA_FIXED
172-
173-
scene_option = scene_option or self._scene_option
174-
mujoco.mjv_updateScene(
175-
self.model,
176-
data,
177-
scene_option,
178-
None,
179-
camera,
180-
mujoco.mjtCatBit.mjCAT_ALL.value,
181-
self._scene,
182-
)
183-
184143
def _update_scene(
185144
self,
186145
data: mujoco.MjData,
@@ -189,7 +148,7 @@ def _update_scene(
189148
) -> None:
190149
if not isinstance(camera, _structs.MjvCamera):
191150
if self.model.ncam == 0:
192-
raise ValueError(f'No fixed cameras defined in mujoco model.')
151+
raise ValueError(f"No fixed cameras defined in mujoco model.")
193152
camera_id = camera
194153
if isinstance(camera_id, str):
195154
camera_id = _functions.mj_name2id(
@@ -198,10 +157,12 @@ def _update_scene(
198157
if camera_id == -1:
199158
raise ValueError(f'The camera "{camera}" does not exist.')
200159
if camera_id == -1:
201-
raise ValueError('Free cameras are not supported during USD export.')
160+
raise ValueError("Free cameras are not supported during USD export.")
202161
if camera_id < 0 or camera_id >= self.model.ncam:
203-
raise ValueError(f'The camera id {camera_id} is out of'
204-
f' range [-1, {self.model.ncam}).')
162+
raise ValueError(
163+
f"The camera id {camera_id} is out of"
164+
f" range [-1, {self.model.ncam})."
165+
)
205166

206167
assert camera_id != -1
207168

@@ -216,7 +177,8 @@ def _update_scene(
216177
data,
217178
scene_option,
218179
None,
219-
camera, _enums.mjtCatBit.mjCAT_ALL.value,
180+
camera,
181+
_enums.mjtCatBit.mjCAT_ALL.value,
220182
self._scene,
221183
)
222184

@@ -274,9 +236,7 @@ def _load_textures(self):
274236
relative_path = os.path.relpath(
275237
self.assets_directory, self.frames_directory
276238
)
277-
img_path = os.path.join(
278-
relative_path, texture_file_name
279-
)
239+
img_path = os.path.join(relative_path, texture_file_name)
280240

281241
self.texture_files.append(img_path)
282242

@@ -297,7 +257,9 @@ def _load_geom(self, geom: mujoco.MjvGeom):
297257
geom_textures = []
298258
else:
299259
geom_textures = [
300-
(self.texture_files[i.item()], self.model.tex_type[i.item()]) if i.item() != -1 else None
260+
(self.texture_files[i.item()], self.model.tex_type[i.item()])
261+
if i.item() != -1
262+
else None
301263
for i in self.model.mat_texid[geom.matid]
302264
]
303265

@@ -319,7 +281,7 @@ def _load_geom(self, geom: mujoco.MjvGeom):
319281
name=geom_name,
320282
geom_type=geom.type,
321283
size=np.array([1.0, 1.0, 1.0]),
322-
decouple=True
284+
decouple=True,
323285
)
324286
usd_geom = object_module.USDTendon(
325287
mesh_config=mesh_config,
@@ -333,9 +295,7 @@ def _load_geom(self, geom: mujoco.MjvGeom):
333295
# handling primitives in our scene
334296
else:
335297
mesh_config = shapes_module.mesh_config_generator(
336-
name=geom_name,
337-
geom_type=geom.type,
338-
size=geom.size
298+
name=geom_name, geom_type=geom.type, size=geom.size
339299
)
340300
usd_geom = object_module.USDPrimitiveMesh(
341301
mesh_config=mesh_config,
@@ -408,15 +368,21 @@ def _update_lights(self) -> None:
408368

409369
def _load_cameras(self) -> None:
410370
self.usd_cameras = {}
411-
371+
412372
# add a primary camera for which the scene will be rendered
413-
self.usd_cameras[PRIMARY_CAMERA_NAME] = camera_module.USDCamera(stage=self.stage, camera_name=PRIMARY_CAMERA_NAME)
373+
self.usd_cameras[PRIMARY_CAMERA_NAME] = camera_module.USDCamera(
374+
stage=self.stage, camera_name=PRIMARY_CAMERA_NAME
375+
)
414376
if self.camera_names is not None:
415377
for camera_name in self.camera_names:
416-
self.usd_cameras[camera_name] = camera_module.USDCamera(stage=self.stage, camera_name=camera_name)
378+
self.usd_cameras[camera_name] = camera_module.USDCamera(
379+
stage=self.stage, camera_name=camera_name
380+
)
417381

418382
def _get_camera_orientation(self) -> Tuple[_structs.MjvGLCamera, np.ndarray]:
419-
avg_camera = mujoco.mjv_averageCamera(self._scene.camera[0], self._scene.camera[1])
383+
avg_camera = mujoco.mjv_averageCamera(
384+
self._scene.camera[0], self._scene.camera[1]
385+
)
420386

421387
forward = avg_camera.forward
422388
up = avg_camera.up
@@ -437,19 +403,23 @@ def _update_cameras(
437403
) -> None:
438404
# first, update the primary camera given the new scene
439405
self._update_scene(
440-
data, camera=camera, scene_option=scene_option,
406+
data,
407+
camera=camera,
408+
scene_option=scene_option,
441409
)
442410
avg_camera, R = self._get_camera_orientation()
443-
self.usd_cameras[PRIMARY_CAMERA_NAME].update(cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates)
411+
self.usd_cameras[PRIMARY_CAMERA_NAME].update(
412+
cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates
413+
)
444414

445415
# update the names of the fixed cameras in the scene
446416
if self.camera_names is not None:
447417
for camera_name in self.camera_names:
448-
self._update_scene(
449-
data, camera=camera_name, scene_option=scene_option
450-
)
418+
self._update_scene(data, camera=camera_name, scene_option=scene_option)
451419
avg_camera, R = self._get_camera_orientation()
452-
self.usd_cameras[camera_name].update(cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates)
420+
self.usd_cameras[camera_name].update(
421+
cam_pos=avg_camera.pos, cam_mat=R, frame=self.updates
422+
)
453423

454424
def add_light(
455425
self,
@@ -479,7 +449,9 @@ def add_light(
479449
pos=np.array(pos), intensity=intensity, color=color, frame=0
480450
)
481451
elif light_type == "dome":
482-
new_light = light_module.USDDomeLight(stage=self.stage, light_name=light_name)
452+
new_light = light_module.USDDomeLight(
453+
stage=self.stage, light_name=light_name
454+
)
483455
new_light.update(intensity=intensity, color=color)
484456

485457
def add_camera(
@@ -496,7 +468,8 @@ def add_camera(
496468
camera_name: name of the camera to be stored in USD
497469
"""
498470
new_camera = camera_module.USDCamera(
499-
stage=self.stage, camera_name=camera_name)
471+
stage=self.stage, camera_name=camera_name
472+
)
500473

501474
rotation = np.zeros(9)
502475
quat = np.zeros(4)
@@ -507,18 +480,18 @@ def add_camera(
507480
def save_scene(self, filetype: str = "usd") -> None:
508481
"""Saves the current scene as a USD trajectory
509482
Args:
510-
filetype: type of USD file to save the scene as (options include
483+
filetype: type of USD file to save the scene as (options include
511484
"usd", "usda", and "usdc")
512485
"""
513486
self.stage.SetEndTimeCode(self.frame_count)
514487

515488
# post-processing for visibility of geoms in scene
516489
for _, geom_ref in self.geom_refs.items():
517-
geom_ref.update_visibility(False, geom_ref.last_visible_frame+1)
490+
geom_ref.update_visibility(False, geom_ref.last_visible_frame + 1)
518491

519492
self.stage.Export(
520-
f"{self.output_directory_root}/{self.output_directory}/" +
521-
f"frames/frame_{self.frame_count}.{filetype}"
493+
f"{self.output_directory_root}/{self.output_directory}/"
494+
+ f"frames/frame_{self.frame_count}.{filetype}"
522495
)
523496
if self.verbose:
524497
print(f"Completed writing frame_{self.frame_count}.{filetype}")

python/mujoco/usd/exporter_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
from absl.testing import absltest
2121
from etils import epath
22+
2223
import mujoco
2324

2425
try:

python/mujoco/usd/lights.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
from typing import Optional
1818

1919
import numpy as np
20-
2120
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.
2221
# pytype: disable=module-attr
2322
from pxr import Gf

python/mujoco/usd/objects.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,12 +18,7 @@
1818
import collections
1919
from typing import Any, Dict, Optional, Sequence, Tuple
2020

21-
import mujoco
22-
import mujoco.usd.shapes as shapes_module
23-
import mujoco.usd.utils as utils_module
2421
import numpy as np
25-
26-
2722
# TODO: b/288149332 - Remove once USD Python Binding works well with pytype.
2823
# pytype: disable=module-attr
2924
from pxr import Gf
@@ -33,6 +28,10 @@
3328
from pxr import UsdShade
3429
from pxr import Vt
3530

31+
import mujoco
32+
import mujoco.usd.shapes as shapes_module
33+
import mujoco.usd.utils as utils_module
34+
3635

3736
class USDObject(abc.ABC):
3837
"""Abstract interface for all USD objects including meshes and primitives.
@@ -55,7 +54,7 @@ def __init__(
5554
geom: mujoco.MjvGeom,
5655
obj_name: str,
5756
rgba: np.ndarray = np.array([1, 1, 1, 1]),
58-
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = ()
57+
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = (),
5958
):
6059
self.stage = stage
6160
self.model = model
@@ -225,7 +224,7 @@ def __init__(
225224
obj_name: str,
226225
dataid: int,
227226
rgba: np.ndarray = np.array([1, 1, 1, 1]),
228-
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = ()
227+
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = (),
229228
):
230229
super().__init__(stage, model, geom, obj_name, rgba, geom_textures)
231230

@@ -324,7 +323,7 @@ def __init__(
324323
geom: mujoco.MjvGeom,
325324
obj_name: str,
326325
rgba: np.ndarray = np.array([1, 1, 1, 1]),
327-
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = ()
326+
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = (),
328327
):
329328
super().__init__(stage, model, geom, obj_name, rgba, geom_textures)
330329

@@ -424,7 +423,7 @@ def __init__(
424423
geom: mujoco.MjvGeom,
425424
obj_name: str,
426425
rgba: np.ndarray = np.array([1, 1, 1, 1]),
427-
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = ()
426+
geom_textures: Sequence[Optional[Tuple[str, mujoco.mjtTexture]]] = (),
428427
):
429428
super().__init__(stage, model, geom, obj_name, rgba, geom_textures)
430429

0 commit comments

Comments
 (0)