nepyope commited on
Commit
afeca72
·
verified ·
1 Parent(s): 3415ae9

Update env.py

Browse files
Files changed (1) hide show
  1. env.py +46 -99
env.py CHANGED
@@ -1,109 +1,56 @@
1
- # env.py
2
-
3
-
4
- from pathlib import Path
5
- import yaml
6
- from huggingface_hub import snapshot_download
7
- import os
8
- import gymnasium as gym
9
- from gymnasium import spaces
10
- import numpy as np
11
- snapshot_download(repo_id='lerobot/unitree-g1-mujoco', revision=None, cache_dir=None)
12
-
13
- from sim.simulator_factory import SimulatorFactory, init_channel
14
-
15
-
16
- class UnitreeG1SimulationEnvironment:
17
- """
18
- Unitree G1 Simulation Environment for EnvHub.
19
- """
20
- def __init__(self, config_path=None):
21
- # Load config
22
- config_path = Path(__file__).parent / "config.yaml"
23
- with open(config_path) as f:
24
- self.config = yaml.safe_load(f)
25
-
26
-
27
-
28
- # optional cleanup
29
- def close(self):
30
- self.sim.close()
31
-
32
- def make_env(n_envs=1, use_async_envs: bool = False,
33
- publish_images=True, camera_port=5555, cameras=None, **kwargs):
34
- """
35
- Required entrypoint for EnvHub.
36
- Returns an environment instance with running simulator.
37
- """
38
- # Fix module path for multiprocessing subprocess
39
- import sys
40
- import os
41
- from pathlib import Path
42
-
43
- # Add Hub directory to PYTHONPATH so subprocess can find 'sim' module
44
- hub_dir = str(Path(__file__).parent)
45
- if hub_dir not in sys.path:
46
- sys.path.insert(0, hub_dir)
47
 
48
- # Also set PYTHONPATH environment variable for spawned subprocess
49
- if 'PYTHONPATH' in os.environ:
50
- if hub_dir not in os.environ['PYTHONPATH']:
51
- os.environ['PYTHONPATH'] = f"{hub_dir}:{os.environ['PYTHONPATH']}"
52
- else:
53
- os.environ['PYTHONPATH'] = hub_dir
54
- # Create the simulation environment
55
  config_path = Path(__file__).parent / "config.yaml"
56
  with open(config_path) as f:
57
  config = yaml.safe_load(f)
58
- # init DDS/communication
59
- init_channel(config=config)
60
- # Configure cameras if publishing is enabled
 
 
 
 
 
 
 
 
 
61
  camera_configs = {}
62
- enable_offscreen = False
63
- if publish_images:
64
  camera_list = cameras or ["head_camera"]
65
  for cam_name in camera_list:
66
  camera_configs[cam_name] = {"height": 480, "width": 640}
67
- enable_offscreen = True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- # Recreate simulator with camera configs if needed
70
- if publish_images:
71
- # Try to enable both onscreen and offscreen rendering
72
- # Note: This may cause OpenGL conflicts on some systems
73
- sim = SimulatorFactory.create_simulator(
74
- config=config,
75
- env_name="default",
76
- onscreen=config.get("ENABLE_ONSCREEN", True),
77
- offscreen=enable_offscreen,
78
- camera_configs=camera_configs,
79
  )
80
-
81
- try:
82
- SimulatorFactory.start_simulator(
83
- sim,
84
- as_thread=False,
85
- enable_image_publish=publish_images,
86
- camera_port=camera_port,
87
- )
88
- except KeyboardInterrupt:
89
- print("\nShutting down simulator...")
90
- sim.close()
91
- import time
92
- time.sleep(1000000)
93
- class DummyEnv(gym.Env):
94
- def __init__(self):
95
- super().__init__()
96
- self.action_space = spaces.Box(-1, 1, shape=(1,), dtype=np.float32)
97
- self.observation_space = spaces.Box(-1, 1, shape=(1,), dtype=np.float32)
98
-
99
- def reset(self, seed=None, options=None):
100
- super().reset(seed=seed)
101
- return np.zeros(1, dtype=np.float32), {}
102
-
103
- def step(self, action):
104
- return np.zeros(1, dtype=np.float32), 0.0, False, False, {}
105
-
106
- def run(self):
107
- pass
108
-
109
- return DummyEnv()
 
1
+ # Use default values
2
+ publish_images = True
3
+ camera_port = 5555
4
+ cameras = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ # Load config
 
 
 
 
 
 
7
  config_path = Path(__file__).parent / "config.yaml"
8
  with open(config_path) as f:
9
  config = yaml.safe_load(f)
10
+
11
+ # Override config with default values
12
+ enable_offscreen = publish_images or config.get("ENABLE_OFFSCREEN", False)
13
+
14
+ print("="*60)
15
+ print("🤖 Starting Unitree G1 MuJoCo Simulator")
16
+ print("="*60)
17
+ print(f"📁 Scene: {config['ROBOT_SCENE']}")
18
+ print(f"⏱️ Timestep: {config['SIMULATE_DT']}s ({int(1/config['SIMULATE_DT'])} Hz)")
19
+ print(f"👁️ Visualization: {'ON' if config.get('ENABLE_ONSCREEN', True) else 'OFF'}")
20
+
21
+ # Configure cameras if requested
22
  camera_configs = {}
23
+ if enable_offscreen:
 
24
  camera_list = cameras or ["head_camera"]
25
  for cam_name in camera_list:
26
  camera_configs[cam_name] = {"height": 480, "width": 640}
27
+ print(f"📷 Cameras: {', '.join(camera_list)} → ZMQ port {camera_port}")
28
+
29
+ print("="*60)
30
+
31
+ # Initialize DDS channel
32
+ init_channel(config=config)
33
+
34
+ # Create simulator
35
+ sim = SimulatorFactory.create_simulator(
36
+ config=config,
37
+ env_name="default",
38
+ onscreen=config.get("ENABLE_ONSCREEN", True),
39
+ offscreen=enable_offscreen,
40
+ camera_configs=camera_configs,
41
+ )
42
 
43
+ # Start simulator (blocking)
44
+ print("\nSimulator running. Press Ctrl+C to exit.")
45
+ if enable_offscreen and publish_images:
46
+ print(f"Camera images publishing on tcp://localhost:{camera_port}")
47
+ try:
48
+ SimulatorFactory.start_simulator(
49
+ sim,
50
+ as_thread=False,
51
+ enable_image_publish=publish_images,
52
+ camera_port=camera_port,
53
  )
54
+ except KeyboardInterrupt:
55
+ print("\nShutting down simulator...")
56
+ sim.close()