ros2_control - humble
Loading...
Searching...
No Matches
mujoco_simulation.hpp
1
20#pragma once
21
22#include <atomic>
23#include <condition_variable>
24#include <functional>
25#include <memory>
26#include <mutex>
27#include <string>
28#include <thread>
29#include <vector>
30
31#include <rclcpp/rclcpp.hpp>
32#include <realtime_tools/realtime_publisher.hpp>
33#include <rosgraph_msgs/msg/clock.hpp>
34
35#include "glfw_adapter.h" // for mj::GlfwAdapter
36#include "simulate.h" // must be on your include path, handled by CMake
37
38#include <mujoco/mujoco.h>
39
40#include <mujoco_ros2_control_msgs/srv/reset_world.hpp>
41#include <mujoco_ros2_control_msgs/srv/set_pause.hpp>
42#include <mujoco_ros2_control_msgs/srv/step_simulation.hpp>
43#include <mujoco_ros2_control_plugins/mujoco_ros2_control_plugins_base.hpp>
44
45namespace mujoco_ros2_control
46{
47
95{
96public:
107 using ResetCallback = std::function<void(bool fill_initial_state)>;
108
112 MujocoSimulation() = default;
113
115
122 bool initialize(rclcpp::Node::SharedPtr node, const std::string& model_path, const std::string& mujoco_model_topic,
123 double sim_speed_factor, bool headless);
124
131 bool apply_keyframe(const std::string& keyframe_name);
132
140
144 void set_reset_callback(ResetCallback callback);
145
150
154 void shutdown();
155
159 mjModel* model()
160 {
161 return mj_model_;
162 }
163
171 mjData* data()
172 {
173 return mj_data_;
174 }
175
180 void reset_world_state(bool fill_initial_state);
181
187 void copy_physics_model(mjModel*& destination);
188
194 void overwrite_physics_data(mjData* source);
195
203 void copy_physics_data(mjData*& destination);
204
222 mjData* acquire_data_snapshot();
223
233 {
234 mjtNum time{ 0.0 };
235 std::vector<mjtNum> qpos;
236 std::vector<mjtNum> qvel;
237 std::vector<mjtNum> act;
238 std::vector<mjtNum> qfrc_actuator;
239 std::vector<mjtNum> sensordata;
240 std::vector<mjtNum> ctrl;
241 };
242
250 void copy_control_state(ControlState& destination);
251
260 void apply_control_data(mjData* control_data);
261
265 std::recursive_mutex& mutex() const
266 {
267 RCLCPP_WARN_EXPRESSION(logger_, sim_mutex_ == nullptr, "Sim recursive mutex is still nullptr");
268 return *sim_mutex_;
269 }
270
276 uint64_t step_count() const
277 {
278 return step_count_.load();
279 }
280
281private:
287 void apply_staged_control_inputs();
288
295 void publish_control_state();
296
304 void refresh_data_snapshot();
305
309 void physics_loop();
310
314 void publish_clock();
315
319 void update_sim_display();
320
321 // Service callbacks
322 void reset_world_callback(const std::shared_ptr<mujoco_ros2_control_msgs::srv::ResetWorld::Request> request,
323 std::shared_ptr<mujoco_ros2_control_msgs::srv::ResetWorld::Response> response);
324 void set_pause_callback(const std::shared_ptr<mujoco_ros2_control_msgs::srv::SetPause::Request> request,
325 std::shared_ptr<mujoco_ros2_control_msgs::srv::SetPause::Response> response);
326 void step_simulation_callback(const std::shared_ptr<mujoco_ros2_control_msgs::srv::StepSimulation::Request> request,
327 std::shared_ptr<mujoco_ros2_control_msgs::srv::StepSimulation::Response> response);
328
329 rclcpp::Logger get_logger() const
330 {
331 return logger_;
332 }
333
334 // Logger
335 rclcpp::Logger logger_ = rclcpp::get_logger("MujocoSimulation");
336
337 // ROS node (owned by the HW interface, used here for services and clock publisher).
338 rclcpp::Node::SharedPtr node_;
339
340 // System information
341 std::string model_path_;
342 std::string mujoco_model_topic_;
343
344 // MuJoCo data pointers, these are the primary containers used by the physics simulation.
345 // It is generally not recommended to interact with them directly.
346 mjModel* mj_model_{ nullptr };
347
348 // Primary data container for the physics loop. We do not recommend interacting with this
349 // directly unless you are sure of what you are doing.
350 mjData* mj_data_{ nullptr };
351
352 // Double-buffered snapshot of mj_data_: the physics loop pays for all scene-sized copies,
353 // the consumer borrows the result via acquire_data_snapshot() and performs no copy at all.
354 // The producer (any writer holding the sim mutex) fills snapshot_write_ outside any shared
355 // lock and raises snapshot_ready_; the consumer, when the flag is up, swaps the two pointers
356 // under data_exchange_mutex_ and reads snapshot_read_ in place.
357 mjData* snapshot_write_{ nullptr };
358 mjData* snapshot_read_{ nullptr };
359 bool snapshot_ready_{ false };
360
361 // Control inputs staged by apply_control_data, applied to mj_data_ before each step.
362 std::vector<mjtNum> ctrl_staged_;
363 std::vector<mjtNum> qfrc_applied_staged_;
364
365 // False until apply_control_data is first called (and cleared on reset), so that initial /
366 // reset ctrl values in mj_data_ are not clobbered by stale staging buffers.
367 bool control_inputs_staged_{ false };
368
369 // Buffers to track actively applied Cartesian forces from both the plugins and the Simulate /
370 // viewer-only drag forces.
371 std::vector<mjtNum> xfrc_plugin_desired_; // Tracks forces from plugins
372 std::vector<mjtNum> xfrc_viewer_capture_; // Tracks forces from the viewer
373 std::vector<mjtNum> xfrc_last_written_; // tracks the last value written to xfrc_applied
374
375 // Guards only the snapshot pointer swap and snapshot_ready_ flag.
376 // Lock order: sim_mutex_ (if needed) is always taken before this one.
377 std::mutex data_exchange_mutex_;
378
379 // Set by acquire_data_snapshot when a consumer takes the snapshot; the physics loop only
380 // runs the expensive full refresh when this is set, so refresh bandwidth tracks consumer
381 // demand instead of the batch rate. Starts true so the first refresh happens.
382 std::atomic<bool> snapshot_refresh_requested_{ true };
383
384 // Guards the staged control inputs (ctrl_staged_, qfrc_applied_staged_, xfrc_plugin_desired_,
385 // control_inputs_staged_). Separate from data_exchange_mutex_ so that staging commands in
386 // write() and applying them before each physics step never queue behind a full mjData copy.
387 // Critical sections are all small buffer copies.
388 // Lock order: sim_mutex_ (if needed) before this one; never held with data_exchange_mutex_.
389 std::mutex control_staging_mutex_;
390
391 // Per-step control state served by copy_control_state. Guarded by its own mutex, separate
392 // from data_exchange_mutex_, so the reduced control-state copies never queue behind a full
393 // mjData snapshot copy.
394 // Lock order: sim_mutex_ (if needed) before this one; never held with data_exchange_mutex_.
395 ControlState control_state_;
396 std::mutex control_state_mutex_;
397
398 // For rendering
399 mjvCamera cam_;
400 mjvOption opt_;
401 mjvPerturb pert_;
402
403 // Speed scaling parameter. if set to >0 then we ignore the value set in the simulate app and instead
404 // attempt to loop at whatever this is set to. If this is <0, then we use the value from the app.
405 double sim_speed_factor_{ -1.0 };
406
407 // True when running without a display (no GLFW window)
408 bool headless_{ false };
409
410 // Primary simulate object
411 std::unique_ptr<mujoco::Simulate> sim_;
412
413 // Threads for rendering physics and the UI simulation
414 std::thread physics_thread_;
415 std::thread ui_thread_;
416
417 // Primary clock publisher for the world
418 std::shared_ptr<rclcpp::Publisher<rosgraph_msgs::msg::Clock>> clock_publisher_;
420
421 // Mutex used inside simulate.h for protecting model/data, we keep a reference
422 // here to protect access to shared data.
423 // TODO: It would be far better to put all relevant data into a single container with accessors
424 // in a common location rather than passing around the raw pointer to the mutex, but it would
425 // require more work to pull it out of simulate.h.
426 std::recursive_mutex* sim_mutex_{ nullptr };
427
428 // Reset world service
429 rclcpp::CallbackGroup::SharedPtr reset_world_cb_group_;
430 rclcpp::Service<mujoco_ros2_control_msgs::srv::ResetWorld>::SharedPtr reset_world_service_;
431
432 // Set pause service
433 rclcpp::CallbackGroup::SharedPtr set_pause_cb_group_;
434 rclcpp::Service<mujoco_ros2_control_msgs::srv::SetPause>::SharedPtr set_pause_service_;
435
436 // Step simulation service
437 rclcpp::CallbackGroup::SharedPtr step_simulation_cb_group_;
438 rclcpp::Service<mujoco_ros2_control_msgs::srv::StepSimulation>::SharedPtr step_simulation_service_;
439
440 // Pending steps to execute while paused, and synchronization for blocking callers
441 std::atomic<uint32_t> pending_steps_{ 0 };
442 std::atomic<bool> step_diverged_{ false };
443 std::atomic<bool> steps_interrupted_{ false };
444 std::atomic<bool> keyboard_step_requested_{ false };
445 std::atomic<uint64_t> step_count_{ 0 };
446 std::mutex steps_cv_mutex_;
447 std::condition_variable steps_cv_;
448
449 // Storage for initial state (used for reset_world)
450 std::vector<mjtNum> initial_qpos_;
451 std::vector<mjtNum> initial_qvel_;
452 std::vector<mjtNum> initial_ctrl_;
453
454 // Callback into the HW interface to perform component-side reset bookkeeping.
455 ResetCallback reset_callback_;
456};
457
458} // namespace mujoco_ros2_control
ROS 2-based container for the mujoco Simulate application.
Definition mujoco_simulation.hpp:95
void capture_initial_state()
Can be called by consumers of this class to store the current state as the "initial" state.
Definition mujoco_simulation.cpp:747
void reset_world_state(bool fill_initial_state)
Reset simulation state (qpos/qvel/ctrl/sensors/forces) to the captured initial state.
Definition mujoco_simulation.cpp:816
std::recursive_mutex & mutex() const
Accessor for the mutex which locks access to the data and model.
Definition mujoco_simulation.hpp:265
void start_physics_thread()
Start the physics thread. Must be called after load_model().
Definition mujoco_simulation.cpp:760
std::function< void(bool fill_initial_state)> ResetCallback
Callback invoked when the simulation's state must be reset.
Definition mujoco_simulation.hpp:107
void apply_control_data(mjData *control_data)
Stages control fields from control_data for the physics loop in a thread safe way.
Definition mujoco_simulation.cpp:1053
mjData * acquire_data_snapshot()
Borrows the latest completed post-step snapshot of mj_data_ (producer-pays copying).
Definition mujoco_simulation.cpp:1033
void copy_physics_data(mjData *&destination)
Copies mj_data_ into the provided container in a thread safe way.
Definition mujoco_simulation.cpp:1018
void shutdown()
Stop the physics and UI threads if they are running.
Definition mujoco_simulation.cpp:797
bool apply_keyframe(const std::string &keyframe_name)
Apply a keyframe to the simulation by name.
Definition mujoco_simulation.cpp:729
void copy_control_state(ControlState &destination)
Copies the latest per-step control state into the provided container.
Definition mujoco_simulation.cpp:1091
void copy_physics_model(mjModel *&destination)
Copies mj_model_ into the provided container in a thread safe way.
Definition mujoco_simulation.cpp:1004
MujocoSimulation()=default
Construct a new Mujoco Simulation object. This is a no-op until initialization.
mjModel * model()
Accessor for the mujoco model.
Definition mujoco_simulation.hpp:159
mjData * data()
Accessor for the raw mujoco simulation data.
Definition mujoco_simulation.hpp:171
uint64_t step_count() const
Returns the number of steps takein by the physics simulation.
Definition mujoco_simulation.hpp:276
void overwrite_physics_data(mjData *source)
Copies the provided mjData into mj_data_ in a thread safe way.
Definition mujoco_simulation.cpp:1010
void set_reset_callback(ResetCallback callback)
Register a callback function to be called on reset_world_state.
Definition mujoco_simulation.cpp:755
bool initialize(rclcpp::Node::SharedPtr node, const std::string &model_path, const std::string &mujoco_model_topic, double sim_speed_factor, bool headless)
Construct the Simulate application and start the UI thread (if not headless).
Definition mujoco_simulation.cpp:528
Definition realtime_publisher.hpp:54
Definition data.hpp:31
Small snapshot of the state the hardware interface needs every control cycle.
Definition mujoco_simulation.hpp:233