Creating a simulation scene#
This tutorial shows how to create a basic simulation scene using SimulationManager. It covers the setup of the simulation context, adding rigid objects, and running the simulation loop.
The Code#
The tutorial corresponds to the create_scene.py script in the scripts/tutorials/sim directory.
Code for create_scene.py
1# ----------------------------------------------------------------------------
2# Copyright (c) 2021-2025 DexForce Technology Co., Ltd.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15# ----------------------------------------------------------------------------
16
17"""
18This script demonstrates how to create a simulation scene using SimulationManager.
19It shows the basic setup of simulation context, adding objects, and sensors.
20"""
21
22import argparse
23import time
24
25from embodichain.lab.sim import SimulationManager, SimulationManagerCfg
26from embodichain.lab.sim.cfg import RigidBodyAttributesCfg
27from embodichain.lab.sim.shapes import CubeCfg
28from embodichain.lab.sim.objects import RigidObject, RigidObjectCfg
29
30
31def main():
32 """Main function to create and run the simulation scene."""
33
34 # Parse command line arguments
35 parser = argparse.ArgumentParser(
36 description="Create a simulation scene with SimulationManager"
37 )
38 parser.add_argument(
39 "--headless",
40 action="store_true",
41 default=False,
42 help="Run simulation in headless mode",
43 )
44 parser.add_argument(
45 "--num_envs", type=int, default=1, help="Number of parallel environments"
46 )
47 parser.add_argument(
48 "--device", type=str, default="cpu", help="Simulation device (cuda or cpu)"
49 )
50 parser.add_argument(
51 "--enable_rt",
52 action="store_true",
53 default=False,
54 help="Enable ray tracing for better visuals",
55 )
56 args = parser.parse_args()
57
58 # Configure the simulation
59 sim_cfg = SimulationManagerCfg(
60 width=1920,
61 height=1080,
62 headless=True,
63 physics_dt=1.0 / 100.0, # Physics timestep (100 Hz)
64 sim_device=args.device,
65 enable_rt=args.enable_rt, # Enable ray tracing for better visuals
66 )
67
68 # Create the simulation instance
69 sim = SimulationManager(sim_cfg)
70
71 # Build multiple arenas if requested
72 if args.num_envs > 1:
73 sim.build_multiple_arenas(args.num_envs, space=3.0)
74
75 # Add objects to the scene
76 cube: RigidObject = sim.add_rigid_object(
77 cfg=RigidObjectCfg(
78 uid="cube",
79 shape=CubeCfg(size=[0.1, 0.1, 0.1]),
80 body_type="dynamic",
81 attrs=RigidBodyAttributesCfg(
82 mass=1.0,
83 dynamic_friction=0.5,
84 static_friction=0.5,
85 restitution=0.1,
86 ),
87 init_pos=[0.0, 0.0, 1.0],
88 )
89 )
90
91 print("[INFO]: Scene setup complete!")
92 print(f"[INFO]: Running simulation with {args.num_envs} environment(s)")
93 print("[INFO]: Press Ctrl+C to stop the simulation")
94
95 # Open window when the scene has been set up
96 if not args.headless:
97 sim.open_window()
98
99 # Run the simulation
100 run_simulation(sim)
101
102
103def run_simulation(sim: SimulationManager):
104 """Run the simulation loop.
105
106 Args:
107 sim: The SimulationManager instance to run
108 """
109
110 # Initialize GPU physics if using CUDA
111 if sim.is_use_gpu_physics:
112 sim.init_gpu_physics()
113
114 step_count = 0
115
116 try:
117 last_time = time.time()
118 last_step = 0
119 while True:
120 # Update physics simulation
121 sim.update(step=1)
122 step_count += 1
123
124 # Print FPS every second
125 if step_count % 100 == 0:
126 current_time = time.time()
127 elapsed = current_time - last_time
128 fps = (
129 sim.num_envs * (step_count - last_step) / elapsed
130 if elapsed > 0
131 else 0
132 )
133 print(f"[INFO]: Simulation step: {step_count}, FPS: {fps:.2f}")
134 last_time = current_time
135 last_step = step_count
136
137 except KeyboardInterrupt:
138 print("\n[INFO]: Stopping simulation...")
139 finally:
140 # Clean up resources
141 sim.destroy()
142 print("[INFO]: Simulation terminated successfully")
143
144
145if __name__ == "__main__":
146 main()
The Code Explained#
Configuring the simulation#
The first step is to configure the simulation environment. This is done using the SimulationManagerCfg data class, which allows you to specify various parameters like window dimensions, headless mode, physics timestep, simulation device (CPU/GPU), and rendering options like ray tracing.
Command-line arguments are parsed using argparse to allow for easy customization of the simulation from the terminal.
# Parse command line arguments
parser = argparse.ArgumentParser(
description="Create a simulation scene with SimulationManager"
)
parser.add_argument(
"--headless",
action="store_true",
default=False,
help="Run simulation in headless mode",
)
parser.add_argument(
"--num_envs", type=int, default=1, help="Number of parallel environments"
)
parser.add_argument(
"--device", type=str, default="cpu", help="Simulation device (cuda or cpu)"
)
parser.add_argument(
"--enable_rt",
action="store_true",
default=False,
help="Enable ray tracing for better visuals",
)
args = parser.parse_args()
# Configure the simulation
sim_cfg = SimulationManagerCfg(
width=1920,
height=1080,
headless=True,
physics_dt=1.0 / 100.0, # Physics timestep (100 Hz)
sim_device=args.device,
enable_rt=args.enable_rt, # Enable ray tracing for better visuals
)
# Create the simulation instance
sim = SimulationManager(sim_cfg)
# Build multiple arenas if requested
if args.num_envs > 1:
sim.build_multiple_arenas(args.num_envs, space=3.0)
There are two kinds of physics mode in SimulationManager:
manual: The physics updates only when the user calls the
SimulationManager.update()function. This mode is used for robot learning tasks where precise control over simulation steps is required. Enabled by settingSimulationManager.set_manual_update()to True.auto: The physics updates in a standalone thread, which enable asynchronous rendering and physics stepping. This mode is suitable for visualizations and demos for digital twins applications. This is the default mode.
If num_envs is greater than 1, SimulationManager.build_multiple_arenas() should be used to create multiple simulation arenas.
Adding objects to the scene#
With the simulation context created, we can add objects. This tutorial demonstrates adding a dynamic rigid cube to the scene using the SimulationManager.add_rigid_object() method. The object’s properties, such as its shape, initial position, and physics attributes (mass, friction, restitution), are defined through a configuration object, cfg.RigidObjectCfg.
# Add objects to the scene
cube: RigidObject = sim.add_rigid_object(
cfg=RigidObjectCfg(
uid="cube",
shape=CubeCfg(size=[0.1, 0.1, 0.1]),
body_type="dynamic",
attrs=RigidBodyAttributesCfg(
mass=1.0,
dynamic_friction=0.5,
static_friction=0.5,
restitution=0.1,
),
init_pos=[0.0, 0.0, 1.0],
Running the simulation#
The simulation is advanced through a loop in the run_simulation function. Before starting the loop, GPU physics is initialized if a CUDA device is used.
Inside the loop, SimulationManager.update() is called to step the physics simulation forward. The script also includes logic to calculate and print the Frames Per Second (FPS) to monitor performance. The simulation runs until it’s manually stopped with Ctrl+C.
def run_simulation(sim: SimulationManager):
"""Run the simulation loop.
Args:
sim: The SimulationManager instance to run
"""
# Initialize GPU physics if using CUDA
if sim.is_use_gpu_physics:
sim.init_gpu_physics()
step_count = 0
try:
last_time = time.time()
last_step = 0
while True:
# Update physics simulation
sim.update(step=1)
step_count += 1
# Print FPS every second
if step_count % 100 == 0:
current_time = time.time()
elapsed = current_time - last_time
fps = (
sim.num_envs * (step_count - last_step) / elapsed
if elapsed > 0
else 0
)
print(f"[INFO]: Simulation step: {step_count}, FPS: {fps:.2f}")
last_time = current_time
last_step = step_count
Exiting the simulation#
Upon exiting the simulation loop (e.g., by a KeyboardInterrupt), it’s important to clean up resources. The SimulationManager.destroy() method is called in a finally block to ensure that the simulation is properly terminated and all allocated resources are released.
except KeyboardInterrupt:
print("\n[INFO]: Stopping simulation...")
finally:
# Clean up resources
sim.destroy()
The Code Execution#
To run the script and see the result, execute the following command:
python scripts/tutorials/sim/create_scene.py
A window should appear showing a cube dropping onto a flat plane. To stop the simulation, you can either close the window or press Ctrl+C in the terminal.
You can also pass arguments to customize the simulation. For example, to run in headless mode with n parallel environments using specified device:
python scripts/tutorials/sim/create_scene.py --headless --num_envs <n> --device <cuda/cpu>
Now that we have a basic understanding of how to create a scene, let’s move on to more advanced topics.