samples.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. .. _Sample:
  2. Code samples
  3. ------------
  4. MuJoCo comes with several code samples providing useful functionality. Some of them are quite elaborate
  5. (:ref:`simulate.cc <saSimulate>` in particular) but nevertheless we hope that they will help users learn how to program
  6. with the library.
  7. .. _saTestspeed:
  8. `testspeed <https://github.com/google-deepmind/mujoco/blob/main/sample/testspeed.cc>`_
  9. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  10. This code sample times the simulation of a given model. The timing is straightforward: the simulation of the passive
  11. dynamics (with optional control noise) is rolled-out for the specified number of steps, while collecting statistics
  12. about the number of contacts, scalar constraints, and CPU times from internal profiling. The results are then printed to
  13. the console. To simulate controlled dynamics instead of passive dynamics one can either install a control callback
  14. :ref:`mjcb_control`, or modify the code to set control signals explicitly, as explained in the :ref:`simulation loop
  15. <siSimulation>` section below. This command-line utility is run with
  16. .. code-block:: Shell
  17. testspeed modelfile [nstep nthread ctrlnoise npoolthread]
  18. Where the command line arguments are
  19. .. list-table::
  20. :width: 95%
  21. :align: left
  22. :widths: 1 1 5
  23. :header-rows: 1
  24. * - Argument
  25. - Default
  26. - Meaning
  27. * - ``modelfile``
  28. - (required)
  29. - path to model
  30. * - ``nstep``
  31. - 10000
  32. - number of steps per rollout
  33. * - ``nthread``
  34. - 1
  35. - number of threads running parallel rollouts
  36. * - ``ctrlnoise``
  37. - 0.01
  38. - scale of pseudo-random noise injected into actuators
  39. * - ``npoolthread``
  40. - 1
  41. - number of threads in engine-internal threadpool
  42. **Notes:**
  43. - When ``nthread > 1`` is specified, the code allocates a single mjModel and per-thread mjData, and runs ``nthread``
  44. identical simulations in parallel. This tests performance with all cores active, as in Reinforcement
  45. Learning scenarios where samples are collected in parallel. The optimal ``nthread`` usually equals the number of
  46. logical cores.
  47. - By default, the simulation starts from the model reference configuration with zero velocities. However, if a
  48. keyframe named "test" is present in the model, it is used as the initial state.
  49. - The ``ctrlnoise`` argument prevents models from settling into a static state where, due to warmstarts, one can
  50. measure artificially faster simulation.
  51. - When ``npoolthread > 1`` is specified, an engine-internal :ref:`mjThreadPool` is created with the specified number of
  52. threads, to speed up simulation of large scenes. Note that while it is possible to to use both ``nthread`` and
  53. ``npoolthread``, the scenarios for which one would want these different type of multithreading are usually mutually
  54. exclusive.
  55. - For more repeatable performance statistics, run the tool with the ``performance``
  56. `governor <https://www.kernel.org/doc/Documentation/cpu-freq/governors.txt>`__ on Linux, or the
  57. ``High Performance`` power plan on Windows, to reduce noise from CPU scaling.
  58. - Many modern CPUs contain a mixture of "performance" and "efficiency" cores. Users should consider restricting the
  59. process to only run on the same type of cores for more interpretable performance statistics. This can be done via the
  60. `taskset <https://man7.org/linux/man-pages/man1/taskset.1.html>`__ command on Linux, or the
  61. `start /affinity <https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/start>`__
  62. command on Windows (processor affinity cannot be specified through documented API means on macOS).
  63. .. _saSimulate:
  64. `simulate <https://github.com/google-deepmind/mujoco/blob/main/simulate>`_
  65. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  66. This code sample is a fully-featured interactive simulator. It opens an OpenGL window using the platform-independent
  67. GLFW library, and renders the simulation state in it. There is built-in help, simulation statistics, profiler, sensor
  68. data plots. The model file can be specified as a command-line argument, or loaded at runtime using drag-and-drop
  69. functionality. This code sample uses the native UI to render various controls, and provides an
  70. illustration of how the new UI framework is intended to be used. Below is a screen-capture of ``simulate`` in action:
  71. .. youtube:: P83tKA1iz2Y
  72. :width: 95%
  73. :align: center
  74. Interaction is done with the mouse; built-in help with a summary of available commands is available by pressing the
  75. ``F1`` key. Briefly, an object is selected by left-double-click. The user can then apply forces and torques on the
  76. selected object by holding Ctrl and dragging the mouse. Dragging the mouse alone (without Ctrl) moves the camera. There
  77. are keyboard shortcuts for pausing the simulation, resetting, and re-loading the model file. The latter functionality is
  78. very useful while editing the model in an XML editor.
  79. The code is long yet reasonably commented, so it is best to just read it. Here we provide a high-level overview.
  80. The ``main()`` function initializes both MuJoCo and GLFW, opens a window, and install GLFW callbacks for mouse and
  81. keyboard handling. Note that there is no render callback; GLFW puts the user in charge, instead of running a rendering
  82. loop behind the scenes. The main loop handles UI events and rendering. The simulation is handled in a background
  83. thread, which is synchronized with the main thread.
  84. The mouse and keyboard callbacks perform whatever action is necessary. Many of these actions invoke functionality
  85. provided by MuJoCo's :ref:`abstract visualization <Abstract>` mechanism. Indeed this mechanism is designed to be
  86. hooked to mouse and keyboard events more or less directly, and provides camera as well as perturbation control.
  87. The profiler and sensor data plots illustrate the use of the :ref:`mjr_figure` function
  88. that can plot elaborate 2D figures with grids, annotation, axis scaling etc. The information presented in the profiler
  89. is extracted from the diagnostic fields of mjData. It is a very useful tool for tuning the parameters of the
  90. constraint solver algorithms. The outputs of the sensors defined in the model are visualized as a bar graph.
  91. Note that the profiler shows timing information collected with high-resolution timers. On Windows, depending on the
  92. power settings, the OS may reduce the CPU frequency; this is because :ref:`simulate.cc <saSimulate>` sleeps most of
  93. the time in order to slow down to realtime. This results in inaccurate timings. To avoid this problem, change the
  94. Windows power plan so that the minimum processor state is 100%.
  95. .. _saCompile:
  96. `compile <https://github.com/google-deepmind/mujoco/blob/main/sample/compile.cc>`_
  97. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  98. This code sample evokes the built-in parser and compiler. It implements all possible model conversions from (MJCF, URDF,
  99. MJB) format to (MJCF, MJB, TXT) format. Models saved as MJCF use a canonical subset of our format as described in the
  100. :doc:`../modeling` chapter, and therefore MJCF-to-MJCF conversion will generally result in a different file.
  101. The TXT format is a human-readable road-map to the model. It cannot be loaded by MuJoCo, but can be a very useful aid
  102. during model development. It is in one-to-one correspondence with the compiled mjModel. Note also that one can use the
  103. function :ref:`mj_printData` to create a text file which is in one-to-one correspondence
  104. with mjData, although this is not done by the code sample.
  105. .. _saBasic:
  106. `basic <https://github.com/google-deepmind/mujoco/blob/main/sample/basic.cc>`_
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. This code sample is a minimal interactive simulator. The model file must be provided as command-line argument. It
  109. opens an OpenGL window using the platform-independent GLFW library, and renders the simulation state at 60 fps while
  110. advancing the simulation in real-time. Press Backspace to reset the simulation. The mouse can be used to control the
  111. camera: left drag to rotate, right drag to translate in the vertical plane, shift right drag to translate in the
  112. horizontal plane, scroll or middle drag to zoom.
  113. The :ref:`Visualization` programming guide below explains how visualization works. This code sample is a minimal
  114. illustration of the concepts in that guide.
  115. .. _saRecord:
  116. `record <https://github.com/google-deepmind/mujoco/blob/main/sample/record.cc>`_
  117. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  118. This code sample simulates the passive dynamics of a given model, renders it offscreen, reads the color and depth pixel
  119. values, and saves them into a raw data file that can then be converted into a movie file with tools such as ffmpeg. The
  120. rendering is simplified compared to :ref:`simulate.cc <saSimulate>` because there is no user interaction, visualization
  121. options or timing; instead we simply render with the default settings as fast as possible. The dimensions and number of
  122. multi-samples for the offscreen buffer are specified in the MuJoCo model with the visual/global/{`offwidth
  123. <https://mujoco.readthedocs.io/en/stable/XMLreference.html#visual-global-offwidth>`__, `offheight
  124. <https://mujoco.readthedocs.io/en/stable/XMLreference.html#visual-global-offheight>`__} and visual/quality/`offsamples
  125. <https://mujoco.readthedocs.io/en/stable/XMLreference.html#visual-quality-offsamples>`_ attributes, while the simulation
  126. duration, frames-per-second to be rendered (usually much less than the physics simulation rate), and output file name
  127. are specified as command-line arguments.
  128. .. code-block:: Shell
  129. record modelfile duration fps rgbfile [adddepth]
  130. Where the command line arguments are
  131. .. list-table::
  132. :width: 95%
  133. :align: left
  134. :widths: 1 1 5
  135. :header-rows: 1
  136. * - Argument
  137. - Default
  138. - Meaning
  139. * - ``modelfile``
  140. - (required)
  141. - path to model
  142. * - ``duration``
  143. - (required)
  144. - duration of the recording in seconds
  145. * - ``fps``
  146. - (required)
  147. - number of frames per second
  148. * - ``rgbfile``
  149. - (required)
  150. - path to raw recording file
  151. * - ``adddepth``
  152. - 1
  153. - overlay depth image in the lower left corner (0: none)
  154. For example, a 5 second animation at 60 frames per second is created with:
  155. .. code-block:: Shell
  156. record humanoid.xml 5 60 rgb.out
  157. The default `humanoid.xml <https://github.com/google-deepmind/mujoco/blob/main/model/humanoid/humanoid.xml>`__ model
  158. specifies offscreen rendering with 2560x1440 resolution. With this information in hand, we can compress the (large) raw
  159. data file into a playable movie file:
  160. .. code-block:: Shell
  161. ffmpeg -f rawvideo -pixel_format rgb24 -video_size 2560x1440
  162. -framerate 60 -i rgb.out -vf "vflip,format=yuv420p" video.mp4
  163. Note that the offscreen rendering resolution of the model and ffmpeg's video_size must be the identical.
  164. This sample can be compiled in three ways which differ in how the OpenGL context is created: using GLFW with an
  165. invisible window, using OSMesa, or using EGL. The latter two options are only available on Linux and are envoked by
  166. defining the symbols MJ_OSMESA or MJ_EGL when compiling record.cc. The functions ``initOpenGL`` and ``closeOpenGL``
  167. create and close the OpenGL context in three different ways depending on which of the above symbols is defined.
  168. Note that the MuJoCo rendering code does not depend on how the OpenGL context was created. This is the beauty of
  169. OpenGL: it leaves context creation to the platform, and the actual rendering is then standard and works in the same
  170. way on all platforms. In retrospect, the decision to leave context creation out of the standard has led to unnecessary
  171. proliferation of overlapping technologies, which differ not only between platforms but also within a platform in the
  172. case of Linux. The addition of a couple of extra functions (such as those provided by OSMesa for example) could have
  173. avoided a lot of confusion. EGL is a newer standard from Khronos which aims to do this, and it is gaining popularity.
  174. But we cannot yet assume that all users have it installed.