0
# Connection and Simulation Management
1
2
Core functions for establishing connections to the physics server, controlling simulation execution, and managing the simulation lifecycle. PyBullet supports multiple connection modes for different use cases from headless simulation to interactive visualization.
3
4
## Capabilities
5
6
### Connection Management
7
8
Establish and manage connections to the physics server with support for multiple connection modes.
9
10
```python { .api }
11
def connect(method, *args, **kwargs):
12
"""
13
Connect to physics server using specified method.
14
15
Args:
16
method (int): Connection method constant
17
- p.GUI: Graphical interface with visualization
18
- p.DIRECT: Direct in-process connection (fastest)
19
- p.SHARED_MEMORY: Shared memory connection
20
- p.TCP: TCP network connection
21
- p.UDP: UDP network connection
22
key (int, optional): Shared memory key for SHARED_MEMORY mode
23
hostName (str, optional): Host name for TCP/UDP connections
24
port (int, optional): Port number for TCP/UDP connections
25
options (str, optional): Additional connection options
26
27
Returns:
28
int: Physics client ID (0 for first connection, incremented for additional)
29
30
Raises:
31
Exception: If connection fails or server is not available
32
"""
33
34
def disconnect(physicsClientId=0):
35
"""
36
Disconnect from physics server and clean up resources.
37
38
Args:
39
physicsClientId (int, optional): Physics client ID. Defaults to 0.
40
"""
41
42
def getConnectionInfo(physicsClientId=0):
43
"""
44
Get connection information for the specified client.
45
46
Args:
47
physicsClientId (int, optional): Physics client ID. Defaults to 0.
48
49
Returns:
50
dict: Connection information including method, server info, and status
51
"""
52
53
def isConnected(physicsClientId=0):
54
"""
55
Check if client is connected to physics server.
56
57
Args:
58
physicsClientId (int, optional): Physics client ID. Defaults to 0.
59
60
Returns:
61
bool: True if connected, False otherwise
62
"""
63
```
64
65
### Simulation Control
66
67
Control simulation execution, timing, and behavior for both real-time and stepped simulation modes.
68
69
```python { .api }
70
def stepSimulation(physicsClientId=0):
71
"""
72
Advance simulation by one time step using forward dynamics.
73
74
Args:
75
physicsClientId (int, optional): Physics client ID. Defaults to 0.
76
77
Note:
78
Call this function in a loop for continuous simulation.
79
Time step size is controlled by setTimeStep().
80
"""
81
82
def setRealTimeSimulation(enableRealTimeSimulation, physicsClientId=0):
83
"""
84
Enable or disable real-time simulation mode.
85
86
Args:
87
enableRealTimeSimulation (int): 1 to enable, 0 to disable
88
physicsClientId (int, optional): Physics client ID. Defaults to 0.
89
90
Note:
91
In real-time mode, simulation runs automatically without explicit stepSimulation() calls.
92
Disabled by default for deterministic stepped simulation.
93
"""
94
95
def resetSimulation(physicsClientId=0):
96
"""
97
Reset simulation state and remove all objects from world.
98
99
Args:
100
physicsClientId (int, optional): Physics client ID. Defaults to 0.
101
102
Note:
103
This removes all bodies, constraints, and resets physics state.
104
Gravity and other physics parameters are preserved.
105
"""
106
107
def performCollisionDetection(physicsClientId=0):
108
"""
109
Update collision detection without advancing simulation time.
110
111
Args:
112
physicsClientId (int, optional): Physics client ID. Defaults to 0.
113
114
Note:
115
Useful for getting contact information without stepping dynamics.
116
Automatically called by stepSimulation().
117
"""
118
```
119
120
### API Information
121
122
```python { .api }
123
def getAPIVersion(physicsClientId=0):
124
"""
125
Get PyBullet API version number.
126
127
Args:
128
physicsClientId (int, optional): Physics client ID. Defaults to 0.
129
130
Returns:
131
int: API version number
132
"""
133
```
134
135
## Usage Examples
136
137
### Basic Simulation Setup
138
139
```python
140
import pybullet as p
141
import time
142
143
# Connect to physics server with GUI
144
physicsClient = p.connect(p.GUI)
145
146
# Set up simulation environment
147
p.setGravity(0, 0, -10)
148
p.setTimeStep(1./240.)
149
150
# Load objects
151
planeId = p.loadURDF("plane.urdf")
152
cubeId = p.loadURDF("cube.urdf", [0, 0, 1])
153
154
# Run simulation loop
155
for i in range(1000):
156
p.stepSimulation()
157
time.sleep(1./240.) # Real-time visualization
158
159
p.disconnect()
160
```
161
162
### Headless Simulation for Performance
163
164
```python
165
import pybullet as p
166
167
# Connect without GUI for maximum performance
168
physicsClient = p.connect(p.DIRECT)
169
170
# Fast simulation without visualization overhead
171
p.setGravity(0, 0, -10)
172
p.setTimeStep(1./240.)
173
174
# Load and simulate
175
robotId = p.loadURDF("robot.urdf")
176
177
# Fast simulation loop
178
for i in range(10000):
179
p.stepSimulation()
180
# No sleep needed - runs as fast as possible
181
182
p.disconnect()
183
```
184
185
### Multi-Client Simulation
186
187
```python
188
import pybullet as p
189
190
# Create multiple physics clients
191
client1 = p.connect(p.DIRECT)
192
client2 = p.connect(p.GUI)
193
194
# Configure different simulations
195
p.setGravity(0, 0, -10, physicsClientId=client1)
196
p.setGravity(0, 0, -5, physicsClientId=client2) # Different gravity
197
198
# Load objects in different clients
199
robot1 = p.loadURDF("robot.urdf", physicsClientId=client1)
200
robot2 = p.loadURDF("robot.urdf", physicsClientId=client2)
201
202
# Run parallel simulations
203
for i in range(1000):
204
p.stepSimulation(physicsClientId=client1)
205
p.stepSimulation(physicsClientId=client2)
206
207
p.disconnect(physicsClientId=client1)
208
p.disconnect(physicsClientId=client2)
209
```
210
211
### Network Connection
212
213
```python
214
import pybullet as p
215
216
# Connect to remote physics server via TCP
217
physicsClient = p.connect(p.TCP, hostName="192.168.1.100", port=6667)
218
219
if p.isConnected():
220
print("Connected to remote server")
221
222
# Normal simulation operations
223
p.setGravity(0, 0, -10)
224
# ... simulation code ...
225
226
p.disconnect()
227
else:
228
print("Failed to connect to server")
229
```
230
231
## Connection Methods
232
233
### p.GUI
234
- **Use case**: Interactive simulation with visualization
235
- **Features**: 3D viewer, mouse interaction, debug drawing
236
- **Performance**: Slower due to rendering overhead
237
- **Best for**: Development, debugging, demonstrations
238
239
### p.DIRECT
240
- **Use case**: Headless simulation for maximum performance
241
- **Features**: No visualization, fastest execution
242
- **Performance**: Fastest option
243
- **Best for**: Training, batch processing, server deployments
244
245
### p.SHARED_MEMORY
246
- **Use case**: Communication with separate physics server process
247
- **Features**: Process isolation, crash protection
248
- **Performance**: Good performance with process safety
249
- **Best for**: Production systems requiring stability
250
251
### p.TCP / p.UDP
252
- **Use case**: Network-based physics simulation
253
- **Features**: Remote server connection, distributed simulation
254
- **Performance**: Network latency dependent
255
- **Best for**: Cloud computing, distributed systems
256
257
## Error Handling
258
259
```python
260
import pybullet as p
261
262
try:
263
physicsClient = p.connect(p.GUI)
264
if not p.isConnected():
265
raise ConnectionError("Failed to connect to physics server")
266
267
# Simulation code...
268
269
except Exception as e:
270
print(f"Simulation error: {e}")
271
finally:
272
if p.isConnected():
273
p.disconnect()
274
```
275
276
## Performance Tips
277
278
1. **Use p.DIRECT** for headless simulation when visualization is not needed
279
2. **Set appropriate time step** - smaller steps are more accurate but slower
280
3. **Minimize real-time delays** - avoid time.sleep() in performance-critical loops
281
4. **Use real-time simulation sparingly** - stepped simulation provides better control
282
5. **Batch operations** where possible to reduce API call overhead