-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathphysics_manager.py
More file actions
372 lines (297 loc) · 12.4 KB
/
physics_manager.py
File metadata and controls
372 lines (297 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
"""Base class for physics managers with unified callback system."""
from __future__ import annotations
import logging
import weakref
from abc import ABC, abstractmethod
from collections.abc import Callable
from enum import Enum
from typing import TYPE_CHECKING, Any, ClassVar
if TYPE_CHECKING:
from isaaclab.sim.simulation_context import SimulationContext
logger = logging.getLogger(__name__)
class PhysicsEvent(Enum):
"""Physics simulation lifecycle events.
These are general events that apply across all physics backends.
Backend-specific events (e.g., PhysX step events, timeline events) are handled
by the respective manager classes via their own event enums (e.g., IsaacEvents).
Lifecycle order: MODEL_INIT -> PHYSICS_READY -> STOP
"""
MODEL_INIT = "model_init"
"""Physics model is being constructed.
Fired during scene building, before simulation can run. Use this to register
physics representations (rigid bodies, joints, constraints) with the solver.
"""
PHYSICS_READY = "physics_ready"
"""Physics is initialized and queryable.
Fired after all physics data structures are created and the simulation is
ready to step. Assets can now read initial state (positions, velocities).
"""
STOP = "stop"
"""Simulation is stopping."""
class CallbackHandle:
"""Handle for a registered callback, allowing deregistration."""
def __init__(self, callback_id: int, manager: type[PhysicsManager]):
self._id = callback_id
self._manager = manager
@property
def id(self) -> int:
return self._id
def deregister(self) -> None:
"""Remove this callback from the manager."""
self._manager.deregister_callback(self._id)
class PhysicsManager(ABC):
"""Abstract base class for physics simulation managers.
Physics managers handle the lifecycle of a physics simulation backend,
including initialization, stepping, and cleanup.
This base class provides:
- Unified callback management system
- Common state variables (_sim, _cfg, _device)
- Default accessor implementations
Lifecycle: initialize() -> reset() -> step() (repeated) -> close()
"""
_sim: ClassVar[SimulationContext | None] = None
_cfg: ClassVar[Any] = None
_device: ClassVar[str] = "cuda:0"
_sim_time: ClassVar[float] = 0.0
_callbacks: ClassVar[dict[int, tuple[Any, Callable, int, str | None, Any]]] = {}
_callback_id: ClassVar[int] = 0
@classmethod
def register_callback(
cls,
callback: Callable[[Any], None],
event: PhysicsEvent,
order: int = 0,
name: str | None = None,
wrap_weak_ref: bool = True,
) -> CallbackHandle:
"""Register a callback for a physics event.
Args:
callback: The callback function. Receives event payload as argument.
event: The event to listen for.
order: Priority order (lower = earlier). Default 0.
name: Optional name for debugging.
wrap_weak_ref: If True, wrap bound methods with weak references
to prevent preventing garbage collection. Default True.
Returns:
CallbackHandle that can be used to deregister the callback.
Example:
>>> def on_physics_ready(payload):
... print("Physics is ready!")
>>> handle = PhysxManager.register_callback(on_physics_ready, PhysicsEvent.PHYSICS_READY)
>>> # Later, to remove:
>>> handle.deregister()
"""
cid = cls._callback_id
cls._callback_id += 1
if wrap_weak_ref:
callback = cls._wrap_weak_ref(callback)
subscription = cls._subscribe_to_event(cid, callback, event, order, name)
cls._callbacks[cid] = (event, callback, order, name, subscription)
return CallbackHandle(cid, cls)
@classmethod
def deregister_callback(cls, callback_id: int | CallbackHandle) -> None:
"""Remove a registered callback.
Args:
callback_id: The ID or CallbackHandle returned by register_callback().
"""
cid = callback_id.id if isinstance(callback_id, CallbackHandle) else callback_id
if cid not in cls._callbacks:
return
event, callback, order, name, subscription = cls._callbacks.pop(cid)
cls._unsubscribe_from_event(cid, event, subscription)
@classmethod
def dispatch_event(cls, event: PhysicsEvent, payload: Any = None) -> None:
"""Dispatch an event to all registered callbacks.
This is the default implementation using simple callback lists.
Subclasses may override or extend with platform-specific dispatch.
Args:
event: The event to dispatch.
payload: Optional data to pass to callbacks.
"""
matching = [(cid, cb, order) for cid, (ev, cb, order, name, sub) in cls._callbacks.items() if ev == event]
matching.sort(key=lambda x: x[2])
for _, callback, _ in matching:
callback(payload)
@classmethod
def clear_callbacks(cls) -> None:
"""Remove all registered callbacks."""
for cid in list(cls._callbacks.keys()):
cls.deregister_callback(cid)
cls._callbacks.clear()
cls._callback_id = 0
@classmethod
def _wrap_weak_ref(cls, callback: Callable) -> Callable:
"""Wrap bound methods with weak references to prevent leaks.
Args:
callback: The callback to wrap.
Returns:
Wrapped callback if it's a bound method, otherwise original.
"""
if hasattr(callback, "__self__"):
obj_ref = weakref.proxy(callback.__self__)
method_name = callback.__name__
def weak_callback(payload: Any) -> Any:
return getattr(obj_ref, method_name)(payload)
return weak_callback
return callback
@classmethod
def _subscribe_to_event(
cls,
callback_id: int,
callback: Callable,
event: PhysicsEvent,
order: int,
name: str | None,
) -> Any:
"""Subscribe to a platform-specific event.
Override in subclasses to integrate with platform event systems
(e.g., Omniverse event bus, timeline events).
Args:
callback_id: Unique ID for this callback.
callback: The callback function.
event: The event to subscribe to.
order: Priority order.
name: Optional name.
Returns:
Platform-specific subscription object (stored for cleanup).
"""
return None
@classmethod
def _unsubscribe_from_event(
cls,
callback_id: int,
event: PhysicsEvent,
subscription: Any,
) -> None:
"""Unsubscribe from a platform-specific event.
Override in subclasses to clean up platform subscriptions.
Args:
callback_id: The callback ID being removed.
event: The event that was subscribed to.
subscription: The subscription object from _subscribe_to_event().
"""
pass
@classmethod
@abstractmethod
def initialize(cls, sim_context: SimulationContext) -> None:
"""Initialize the physics manager with simulation context.
Subclasses should call super().initialize() first, then do backend-specific setup.
Args:
sim_context: Parent simulation context.
"""
# Set on PhysicsManager explicitly so PhysicsManager.get_*() works
# regardless of which subclass is active (Python class vars are per-class)
PhysicsManager._sim = sim_context
PhysicsManager._cfg = sim_context.cfg.physics
PhysicsManager._device = sim_context.cfg.device
PhysicsManager._sim_time = 0.0
@classmethod
@abstractmethod
def reset(cls, soft: bool = False) -> None:
"""Reset physics simulation.
Args:
soft: If True, skip full reinitialization.
"""
pass
@classmethod
@abstractmethod
def forward(cls) -> None:
"""Update kinematics without stepping physics (for rendering)."""
pass
@classmethod
@abstractmethod
def step(cls) -> None:
"""Step physics simulation by one timestep (physics only, no rendering)."""
pass
@classmethod
def pre_render(cls) -> None:
"""Sync deferred physics state to the rendering backend.
Called by :meth:`~isaaclab.sim.SimulationContext.render` before cameras
and visualizers read scene data. The default implementation is a no-op.
Backends that defer transform writes (e.g. Newton's dirty-flag pattern)
should override this to flush pending updates.
"""
pass
@classmethod
def after_visualizers_render(cls) -> None:
"""Hook after visualizers have stepped during :meth:`~isaaclab.sim.SimulationContext.render`.
Use for physics-backend sync (e.g. fabric) if needed. Recording pipelines (Kit/RTX,
Newton GL video, etc.) run from :mod:`isaaclab.envs.utils.recording_hooks` so they are not
tied to a specific physics manager. Default is a no-op.
"""
pass
@classmethod
def close(cls) -> None:
"""Clean up physics resources.
Subclasses should call super().close() after backend-specific cleanup.
"""
cls.dispatch_event(PhysicsEvent.STOP) # notify listeners before cleanup
cls.clear_callbacks()
# Reset on PhysicsManager explicitly (matches initialize())
PhysicsManager._sim = None
PhysicsManager._cfg = None
PhysicsManager._sim_time = 0.0
@classmethod
def get_physics_dt(cls) -> float:
"""Get the physics timestep in seconds."""
return PhysicsManager._sim.cfg.dt if PhysicsManager._sim else 1.0 / 60.0
@classmethod
def get_device(cls) -> str:
"""Get the physics simulation device."""
return PhysicsManager._device
@classmethod
def get_simulation_time(cls) -> float:
"""Get the current simulation time in seconds."""
return PhysicsManager._sim_time
@classmethod
def get_physics_sim_view(cls) -> Any:
"""Get the physics simulation view. Override in subclasses."""
return None
@classmethod
def play(cls) -> None:
"""Start or resume physics simulation. Default is no-op."""
pass
@classmethod
def pause(cls) -> None:
"""Pause physics simulation. Default is no-op."""
pass
@classmethod
def stop(cls) -> None:
"""Stop physics simulation. Default is no-op."""
pass
@classmethod
def wait_for_playing(cls) -> None:
"""Block until the timeline is playing. Default is no-op."""
pass
@classmethod
def get_backend(cls) -> str:
"""Get the tensor backend being used ("numpy" or "torch")."""
return "torch" if "cuda" in PhysicsManager._device else "numpy"
@staticmethod
def safe_callback_invoke(fn: Callable, *args, physics_manager: type[PhysicsManager] | None = None) -> None:
"""Invoke a callback, catching exceptions that would be swallowed by external event buses.
Ignores ``ReferenceError`` (from garbage-collected weakref proxies). All other
exceptions are forwarded to *physics_manager*.``store_callback_exception`` when
available (see note below), or re-raised immediately otherwise.
Note (Octi):
The carb event bus used by PhysX/Omniverse silently swallows exceptions raised
inside callbacks. ``PhysxManager`` works around this by storing the exception
and re-raising it after event dispatch completes (in ``reset()`` / ``step()``).
Backends that dispatch events directly (e.g. Newton) don't need this — exceptions
propagate normally — so ``store_callback_exception`` is not called for them.
This is a known wart; a cleaner solution is actively being explored.
"""
try:
fn(*args)
except ReferenceError:
pass
except Exception as e:
store_fn = getattr(physics_manager, "store_callback_exception", None)
if callable(store_fn):
store_fn(e)
else:
raise