..
  AUTOGENERATED: DO NOT EDIT MANUALLY


.. _Parseandcompile:

Parse and compile
^^^^^^^^^^^^^^^^^

The key function here is :ref:`mj_loadXML`. It invokes the built-in parser and compiler, and either returns a pointer to
a valid mjModel, or NULL - in which case the user should check the error information in the user-provided string.
The model and all files referenced in it can be loaded from disk or from a VFS when provided.

.. _mj_loadXML:

`mj_loadXML <#mj_loadXML>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_loadXML

Parse XML file in MJCF or URDF format, compile it; return low-level model.

If vfs is not NULL, look up files in vfs before reading from disk.

If error is not NULL, it must have size error_sz.

*Nullable:* ``vfs``, ``error``

.. _mj_parseXML:

`mj_parseXML <#mj_parseXML>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_parseXML

Parse spec from XML file.

*Nullable:* ``vfs``, ``error``

.. _mj_parseXMLString:

`mj_parseXMLString <#mj_parseXMLString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_parseXMLString

Parse spec from XML string.

*Nullable:* ``vfs``, ``error``

.. _mj_parse:

`mj_parse <#mj_parse>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_parse

Parse spec from a file.

*Nullable:* ``vfs``, ``error``

.. _mj_compile:

`mj_compile <#mj_compile>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_compile

Compile :ref:`mjSpec` to :ref:`mjModel`. A spec can be edited and compiled multiple times, returning a new
:ref:`mjModel` instance that takes the edits into account.
If compilation fails, :ref:`mj_compile` returns ``NULL``; the error can be read with :ref:`mjs_getError`.

.. _mj_copyBack:

`mj_copyBack <#mj_copyBack>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_copyBack

Copy real-valued arrays from model to spec; return 1 on success.

.. _mj_recompile:

`mj_recompile <#mj_recompile>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_recompile

Recompile spec to model, preserving the state. Like :ref:`mj_compile`, this function compiles an :ref:`mjSpec` to an
:ref:`mjModel`, with two differences. First, rather than returning an entirely new model, it will
reallocate existing :ref:`mjModel` and :ref:`mjData` instances in-place. Second, it will preserve the
:ref:`integration state<siIntegrationState>`, as given in the provided :ref:`mjData` instance, while accounting for
newly added or removed degrees of freedom. This allows the user to continue simulation with the same model and data
struct pointers while editing the model programmatically.

:ref:`mj_recompile` returns 0 if compilation succeed. In the case of failure, the given :ref:`mjModel` and :ref:`mjData`
instances will be deleted; as in :ref:`mj_compile`, the compilation error can be read with :ref:`mjs_getError`.

.. _mj_saveLastXML:

`mj_saveLastXML <#mj_saveLastXML>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_saveLastXML

Update XML data structures with info from low-level model created with :ref:`mj_loadXML`, save as MJCF.
If error is not NULL, it must have size error_sz.

Note that this function only saves models that have been loaded with :ref:`mj_loadXML`, the legacy loading mechanism.
See the :ref:`model editing<meOverview>` chapter to understand the difference between the old and new model loading and
saving mechanisms.

.. _mj_freeLastXML:

`mj_freeLastXML <#mj_freeLastXML>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_freeLastXML

Free last XML model if loaded. Called internally at each load.

.. _mj_saveXMLString:

`mj_saveXMLString <#mj_saveXMLString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_saveXMLString

Save spec to XML string, return 0 on success, -1 on failure. If the length of the output buffer is too small, returns
the required size. XML saving automatically compiles the spec before saving.

.. _mj_saveXML:

`mj_saveXML <#mj_saveXML>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_saveXML

Save spec to XML file, return 0 on success, -1 otherwise. XML saving requires that the spec first be compiled.

.. _mju_getXMLDependencies:

`mju_getXMLDependencies <#mju_getXMLDependencies>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_getXMLDependencies

Given MJCF filename, fills dependencies with a list of all other asset files it depends on.

The search is recursive, and the list includes the filename itself.

.. _Mainsimulation:

Main simulation
^^^^^^^^^^^^^^^

These are the main entry points to the simulator. Most users will only need to call :ref:`mj_step`, which computes
everything and advanced the simulation state by one time step. Controls and applied forces must either be set in advance
(in ``mjData.{ctrl, qfrc_applied, xfrc_applied}``), or a control callback :ref:`mjcb_control` must be installed which
will be called just before the controls and applied forces are needed. Alternatively, one can use :ref:`mj_step1` and
:ref:`mj_step2` which break down the simulation pipeline into computations that are executed before and after the
controls are needed; in this way one can set controls that depend on the results from :ref:`mj_step1`. Keep in mind
though that the RK4 solver does not work with mj_step1/2. See :ref:`Pipeline` for a more detailed description.

mj_forward performs the same computations as :ref:`mj_step` but without the integration. It is useful after loading or
resetting a model (to put the entire mjData in a valid state), and also for out-of-order computations that involve
sampling or finite-difference approximations.

:ref:`mj_inverse` runs the inverse dynamics, and writes its output in ``mjData.qfrc_inverse``. Note that ``mjData.qacc``
must be set before calling this function. Given the state (qpos, qvel, act), mj_forward maps from force to acceleration,
while mj_inverse maps from acceleration to force. Mathematically these functions are inverse of each other, but
numerically this may not always be the case because the forward dynamics rely on a constraint optimization algorithm
which is usually terminated early. The difference between the results of forward and inverse dynamics can be computed
with the function :ref:`mj_compareFwdInv`, which can be thought of as another solver accuracy check (as well as a
general sanity check).

The skip version of :ref:`mj_forward` and :ref:`mj_inverse` are useful for example when qpos was unchanged but qvel was
changed (usually in the context of finite differencing). Then there is no point repeating the computations that only
depend on qpos. Calling the dynamics with skipstage = :ref:`mjSTAGE_POS<mjtStage>` will achieve these savings.

.. _mj_step:

`mj_step <#mj_step>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_step

Advance simulation, use control callback to obtain external force and control.

.. _mj_step1:

`mj_step1 <#mj_step1>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_step1

Advance simulation in two steps: before external force and control is set by user.

.. _mj_step2:

`mj_step2 <#mj_step2>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_step2

Advance simulation in two steps: after external force and control is set by user.

.. _mj_forward:

`mj_forward <#mj_forward>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_forward

Forward dynamics: same as mj_step but do not integrate in time.

.. _mj_inverse:

`mj_inverse <#mj_inverse>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_inverse

Inverse dynamics: qacc must be set before calling.

.. _mj_forwardSkip:

`mj_forwardSkip <#mj_forwardSkip>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_forwardSkip

Forward dynamics with skip; skipstage is mjtStage.

.. _mj_inverseSkip:

`mj_inverseSkip <#mj_inverseSkip>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_inverseSkip

Inverse dynamics with skip; skipstage is mjtStage.

.. _Support:

Support
^^^^^^^

These are support functions that need access to :ref:`mjModel` and :ref:`mjData`, unlike the utility functions which do
not need such access. Support functions are called within the simulator but some of them can also be useful for custom
computations, and are documented in more detail below.

.. _mj_stateSize:

`mj_stateSize <#mj_stateSize>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_stateSize

Returns the number of :ref:`mjtNum` |-| s required for a given state signature. The bits of the integer ``sig``
correspond to element fields of :ref:`mjtState`.

.. _mj_getState:

`mj_getState <#mj_getState>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getState

Copy concatenated state components specified by ``sig`` from ``d`` into ``state``. The bits of the integer
``sig`` correspond to element fields of :ref:`mjtState`. Fails with :ref:`mju_error` if ``sig`` is invalid.

.. _mj_extractState:

`mj_extractState <#mj_extractState>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_extractState

Extract into ``dst`` the subset of components specified by ``dstsig`` from a state ``src`` previously obtained via
:ref:`mj_getState` with components specified by ``srcsig``. Fails with :ref:`mju_error` if the bits set in ``dstsig``
is not a subset of the bits set in ``srcsig``.

.. _mj_setState:

`mj_setState <#mj_setState>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setState

Copy concatenated state components specified by ``sig`` from  ``state`` into ``d``. The bits of the integer
``sig`` correspond to element fields of :ref:`mjtState`. Fails with :ref:`mju_error` if ``sig`` is invalid.

.. _mj_copyState:

`mj_copyState <#mj_copyState>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_copyState

Copy state from src to dst.

.. _mj_readCtrl:

`mj_readCtrl <#mj_readCtrl>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_readCtrl

Read the control value for an actuator at a given time, taking delays into account. If no history buffer exists, return
``mjData.ctrl[id]``. If a history buffer exists (:ref:`nsample<actuator-general-nsample>` > 0), read from the delay
buffer at ``time - actuator_delay[id]`` using the requested interpolation order:

- ``interp = 0``: Zero-order hold (piecewise constant)
- ``interp = 1``: Piecewise Linear
- ``interp = 2``: Cubic Spline (Catmull-Rom)
- ``interp = -1``: Use the actuator's :ref:`interp<actuator-general-interp>` value.

Constant extrapolation is used outside of buffer bounds.

Note that the subtraction of the delay changes the semantic of the ``time`` argument from "time at which values were
pushed into the delay buffer" to "time at which values come out of the delay buffer". See :ref:`Delays<CDelay>` for
details.

.. _mj_readSensor:

`mj_readSensor <#mj_readSensor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_readSensor

Read a sensor value at a given time, taking delays into account. If no history buffer exists, return a pointer to the
sensor's slice of ``mjData.sensordata``. If a history buffer exists (:ref:`nsample<sensor-nsample>` > 0), read from the
history buffer at ``time - sensor_delay[id]``. Note that the subtraction of the delay changes the semantic of the
``time`` argument from "time at which values were pushed into the delay buffer" to "time at which values come out of the
delay buffer". See :ref:`Delays<CDelay>` for details.

**Return value semantics:**

- If no history buffer exists (:ref:`nsample<sensor-nsample>` = 0), returns a pointer to the sensor's slice of
  ``mjData.sensordata``.
- If a history buffer exists (:ref:`nsample<sensor-nsample>` > 0) and the requested time matches a stored sample
  (always true for ``interp = 0``), returns a pointer to the data in the history buffer.
- If interpolation is required (``interp = 1 or 2``), returns ``NULL`` and writes the interpolated result to
  ``result`` (must be of size ``dim``).

**Interpolation:**

- ``interp = 0``: Zero-order hold (piecewise constant)
- ``interp = 1``: Piecewise Linear
- ``interp = 2``: Cubic Spline (Catmull-Rom)
- ``interp = -1``: Use the value in :ref:`interp<sensor-interp>`

Constant extrapolation is used outside of buffer bounds.


**Usage:**

.. code-block:: C

   // read sensor 0 of data size `dim` at time t
   mjtNum result[dim];
   const mjtNum* ptr = mj_readSensor(m, d, 0, t, result, /* interp = */ 1);
   const mjtNum* data = ptr ? ptr : result;

.. _mj_initCtrlHistory:

`mj_initCtrlHistory <#mj_initCtrlHistory>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_initCtrlHistory

Initialize the history buffer for an actuator with custom values. The ``times`` array specifies the timestamps for each
sample (must be length :ref:`nsample<actuator-general-nsample>`), and ``values`` specifies the control values. If
``times`` is ``NULL``, the existing timestamps in the buffer are used, and only the values are updated.
See :ref:`Delays<CDelay>` for details.

.. _mj_initSensorHistory:

`mj_initSensorHistory <#mj_initSensorHistory>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_initSensorHistory

Initialize the history buffer for a sensor with custom values. The ``times`` array specifies the timestamps for each
sample (must be length :ref:`nsample<sensor-nsample>`), and ``values`` specifies the sensor values (must be of size
``nsample * dim``). If ``times`` is ``NULL``, the existing timestamps in the buffer are used.
The ``phase`` argument sets the user slot, which stores the last computation time for interval sensors.
See :ref:`Delays<CDelay>` for details.

.. _mj_setKeyframe:

`mj_setKeyframe <#mj_setKeyframe>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setKeyframe

Copy current state to the k-th model keyframe.

.. _mj_addContact:

`mj_addContact <#mj_addContact>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_addContact

Add contact to d->contact list; return 0 if success; 1 if buffer full.

.. _mj_isPyramidal:

`mj_isPyramidal <#mj_isPyramidal>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_isPyramidal

Determine type of friction cone.

.. _mj_isSparse:

`mj_isSparse <#mj_isSparse>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_isSparse

Determine type of constraint Jacobian.

.. _mj_isDual:

`mj_isDual <#mj_isDual>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_isDual

Determine type of solver (PGS is dual, CG and Newton are primal).

.. _mj_mulJacVec:

`mj_mulJacVec <#mj_mulJacVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_mulJacVec

This function multiplies the constraint Jacobian mjData.efc_J by a vector. Note that the Jacobian can be either dense or
sparse; the function is aware of this setting. Multiplication by J maps velocities from joint space to constraint space.

.. _mj_mulJacTVec:

`mj_mulJacTVec <#mj_mulJacTVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_mulJacTVec

Same as mj_mulJacVec but multiplies by the transpose of the Jacobian. This maps forces from constraint space to joint
space.

.. _mj_jac:

`mj_jac <#mj_jac>`__
~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jac

This function computes an end-effector kinematic Jacobian, describing the local linear relationship between the
degrees-of-freedom and a given point. Given a body specified by its integer id (``body``) and a 3D point in the world
frame (``point``) treated as attached to the body, the Jacobian has both translational (``jacp``) and rotational
(``jacr``) components. Passing ``NULL`` for either pointer will skip that part of the computation. Each component is a
3-by-nv matrix. Each row of this matrix is the gradient of the corresponding coordinate of the specified point with
respect to the degrees-of-freedom. The frame with respect to which the Jacobian is computed is centered at the body
center-of-mass but aligned with the world frame. The minimal :ref:`pipeline stages<piForward>` required for Jacobian
computations to be consistent with the current generalized positions ``mjData.qpos`` are :ref:`mj_kinematics` followed
by :ref:`mj_comPos`.

*Nullable:* ``jacp``, ``jacr``

.. _mj_jacBody:

`mj_jacBody <#mj_jacBody>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacBody

This and the remaining variants of the Jacobian function call mj_jac internally, with the center of the body, geom or
site. They are just shortcuts; the same can be achieved by calling mj_jac directly.

*Nullable:* ``jacp``, ``jacr``

.. _mj_jacBodyCom:

`mj_jacBodyCom <#mj_jacBodyCom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacBodyCom

Compute body center-of-mass end-effector Jacobian.

*Nullable:* ``jacp``, ``jacr``

.. _mj_jacSubtreeCom:

`mj_jacSubtreeCom <#mj_jacSubtreeCom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacSubtreeCom

Compute subtree center-of-mass end-effector Jacobian.

.. _mj_jacGeom:

`mj_jacGeom <#mj_jacGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacGeom

Compute geom end-effector Jacobian.

*Nullable:* ``jacp``, ``jacr``

.. _mj_jacSite:

`mj_jacSite <#mj_jacSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacSite

Compute site end-effector Jacobian.

*Nullable:* ``jacp``, ``jacr``

.. _mj_jacPointAxis:

`mj_jacPointAxis <#mj_jacPointAxis>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacPointAxis

Compute translation end-effector Jacobian of point, and rotation Jacobian of axis.

*Nullable:* ``jacPoint``, ``jacAxis``

.. _mj_jacDot:

`mj_jacDot <#mj_jacDot>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_jacDot

This function computes the time-derivative of an end-effector kinematic Jacobian computed by :ref:`mj_jac`.
The minimal :ref:`pipeline stages<piStages>` required for computation to be
consistent with the current generalized positions and velocities ``mjData.{qpos, qvel}`` are
:ref:`mj_kinematics`, :ref:`mj_comPos`, :ref:`mj_comVel` (in that order).

*Nullable:* ``jacp``, ``jacr``

.. _mj_angmomMat:

`mj_angmomMat <#mj_angmomMat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_angmomMat

This function computes the ``3 x nv`` angular momentum matrix :math:`H(q)`, providing the linear mapping from
generalized velocities to subtree angular momentum. More precisely if :math:`h` is the subtree angular momentum of
body index ``body`` in ``mjData.subtree_angmom`` (reported by the :ref:`subtreeangmom<sensor-subtreeangmom>` sensor)
and :math:`\dot q` is the generalized velocity ``mjData.qvel``, then :math:`h = H \dot q`.

.. _mj_name2id:

`mj_name2id <#mj_name2id>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_name2id

Get id of object with the specified :ref:`mjtObj` type and name, returns -1 if id not found.

.. _mj_id2name:

`mj_id2name <#mj_id2name>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_id2name

Get name of object with the specified :ref:`mjtObj` type and id, returns ``NULL`` if name not found.

.. _mj_fullM:

`mj_fullM <#mj_fullM>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fullM

Convert sparse inertia matrix ``M`` into full (i.e. dense) matrix.
|br| ``dst`` must be of size ``nv x nv``, ``M`` must be of the same structure as ``mjData.qM``.

The ``mjData`` members ``qM`` and ``M`` represent the same matrix in different formats; the former is unique to
MuJoCo, the latter is standard Compressed Sparse Row (lower triangle only). The :math:`L^T D L` factor of the inertia
matrix ``mjData.qLD`` uses the same CSR format as ``mjData.M``. See
`engine_support_test <https://github.com/google-deepmind/mujoco/blob/main/test/engine/engine_support_test.cc>`__ for
pedagogical examples.

.. _mj_mulM:

`mj_mulM <#mj_mulM>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_mulM

This function multiplies the joint-space inertia matrix stored in ``mjData.M`` by a vector.

.. _mj_mulM2:

`mj_mulM2 <#mj_mulM2>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_mulM2

Multiply vector by (inertia matrix)^(1/2).

.. _mj_addM:

`mj_addM <#mj_addM>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_addM

Add inertia matrix to destination matrix (lower triangle only).

Destination can be sparse or dense when all int* are NULL.

*Nullable:* ``rownnz``, ``rowadr``, ``colind``

.. _mj_applyFT:

`mj_applyFT <#mj_applyFT>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_applyFT

This function can be used to apply a Cartesian force and torque to a point on a body, and add the result to the vector
mjData.qfrc_applied of all applied forces. Note that the function requires a pointer to this vector, because sometimes
we want to add the result to a different vector.

.. _mj_objectVelocity:

`mj_objectVelocity <#mj_objectVelocity>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_objectVelocity

Compute object 6D velocity (rot:lin) in object-centered frame, world/local orientation.

.. _mj_objectAcceleration:

`mj_objectAcceleration <#mj_objectAcceleration>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_objectAcceleration

Compute object 6D acceleration (rot:lin) in object-centered frame, world/local orientation. If acceleration or force
sensors are not present in the model, :ref:`mj_rnePostConstraint` must be manually called in order to calculate
mjData.cacc -- the total body acceleration, including contributions from the constraint solver.

.. _mj_geomDistance:

`mj_geomDistance <#mj_geomDistance>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_geomDistance

Returns the smallest signed distance between two geoms and optionally the segment from ``geom1`` to ``geom2``.
Returned distances are bounded from above by ``distmax``. |br| If no collision of distance smaller than ``distmax`` is
found, the function will return ``distmax`` and ``fromto``, if given, will be set to (0, 0, 0, 0, 0, 0).

*Nullable:* ``fromto``

.. admonition:: different (correct) behavior under `nativeccd`
   :class: note

   As explained in :ref:`Collision Detection<coDistance>`, distances are inaccurate when using the
   :ref:`legacy CCD pipeline<coCCD>`, and its use is discouraged.

.. _mj_contactForce:

`mj_contactForce <#mj_contactForce>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_contactForce

Extract 6D force:torque given contact id, in the contact frame.

.. _mj_differentiatePos:

`mj_differentiatePos <#mj_differentiatePos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_differentiatePos

This function subtracts two vectors in the format of qpos (and divides the result by dt), while respecting the
properties of quaternions. Recall that unit quaternions represent spatial orientations. They are points on the unit
sphere in 4D. The tangent to that sphere is a 3D plane of rotational velocities. Thus when we subtract two quaternions
in the right way, the result is a 3D vector and not a 4D vector. Thus the output qvel has dimensionality nv while the
inputs have dimensionality nq.

.. _mj_integratePos:

`mj_integratePos <#mj_integratePos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_integratePos

This is the opposite of mj_differentiatePos. It adds a vector in the format of qvel (scaled by dt) to a vector in the
format of qpos.

.. _mj_normalizeQuat:

`mj_normalizeQuat <#mj_normalizeQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_normalizeQuat

Normalize all quaternions in qpos-type vector.

.. _mj_local2Global:

`mj_local2Global <#mj_local2Global>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_local2Global

Map from body local to global Cartesian coordinates, sameframe takes values from mjtSameFrame.

.. _mj_getTotalmass:

`mj_getTotalmass <#mj_getTotalmass>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getTotalmass

Sum all body masses.

.. _mj_setTotalmass:

`mj_setTotalmass <#mj_setTotalmass>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setTotalmass

Scale body masses and inertias to achieve specified total mass.

.. _mj_getPluginConfig:

`mj_getPluginConfig <#mj_getPluginConfig>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getPluginConfig

Return a config attribute value of a plugin instance;

NULL: invalid plugin instance ID or attribute name

.. _mj_loadPluginLibrary:

`mj_loadPluginLibrary <#mj_loadPluginLibrary>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_loadPluginLibrary

Load a dynamic library. The dynamic library is assumed to register one or more plugins.

.. _mj_loadAllPluginLibraries:

`mj_loadAllPluginLibraries <#mj_loadAllPluginLibraries>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_loadAllPluginLibraries

Scan a directory and load all dynamic libraries. Dynamic libraries in the specified directory
are assumed to register one or more plugins. Optionally, if a callback is specified, it is called
for each dynamic library encountered that registers plugins.

.. _mj_version:

`mj_version <#mj_version>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_version

Return version number: 1.0.2 is encoded as 102.

.. _mj_versionString:

`mj_versionString <#mj_versionString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_versionString

Return the current version of MuJoCo as a null-terminated string.

.. _Components:

Components
^^^^^^^^^^

These are components of the simulation pipeline, called internally from :ref:`mj_step`, :ref:`mj_forward` and
:ref:`mj_inverse`. It is unlikely that the user will need to call them.

.. _mj_fwdKinematics:

`mj_fwdKinematics <#mj_fwdKinematics>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdKinematics

Run all kinematics-like computations (kinematics, comPos, camlight, flex, tendon).

.. _mj_fwdPosition:

`mj_fwdPosition <#mj_fwdPosition>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdPosition

Run position-dependent computations.

.. _mj_fwdVelocity:

`mj_fwdVelocity <#mj_fwdVelocity>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdVelocity

Run velocity-dependent computations.

.. _mj_fwdActuation:

`mj_fwdActuation <#mj_fwdActuation>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdActuation

Compute actuator force qfrc_actuator.

.. _mj_fwdAcceleration:

`mj_fwdAcceleration <#mj_fwdAcceleration>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdAcceleration

Add up all non-constraint forces, compute qacc_smooth.

.. _mj_fwdConstraint:

`mj_fwdConstraint <#mj_fwdConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_fwdConstraint

Run selected constraint solver.

.. _mj_Euler:

`mj_Euler <#mj_Euler>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_Euler

Euler integrator, semi-implicit in velocity.

.. _mj_RungeKutta:

`mj_RungeKutta <#mj_RungeKutta>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_RungeKutta

Runge-Kutta explicit order-N integrator.

.. _mj_implicit:

`mj_implicit <#mj_implicit>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_implicit

Integrates the simulation state using an implicit-in-velocity integrator (either "implicit" or "implicitfast", see
:ref:`Numerical Integration<geIntegration>`), and advances simulation time. See `mjdata.h
<https://github.com/google-deepmind/mujoco/blob/main/include/mujoco/mjdata.h>`__ for fields computed by this function.

.. _mj_invPosition:

`mj_invPosition <#mj_invPosition>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_invPosition

Run position-dependent computations in inverse dynamics.

.. _mj_invVelocity:

`mj_invVelocity <#mj_invVelocity>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_invVelocity

Run velocity-dependent computations in inverse dynamics.

.. _mj_invConstraint:

`mj_invConstraint <#mj_invConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_invConstraint

Apply the analytical formula for inverse constraint dynamics.

.. _mj_compareFwdInv:

`mj_compareFwdInv <#mj_compareFwdInv>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_compareFwdInv

Compare forward and inverse dynamics, save results in fwdinv.

.. _Subcomponents:

Sub components
^^^^^^^^^^^^^^

These are sub-components of the simulation pipeline, called internally from the components above.

.. _mj_sensorPos:

`mj_sensorPos <#mj_sensorPos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_sensorPos

Evaluate position-dependent sensors.

.. _mj_sensorVel:

`mj_sensorVel <#mj_sensorVel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_sensorVel

Evaluate velocity-dependent sensors.

.. _mj_sensorAcc:

`mj_sensorAcc <#mj_sensorAcc>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_sensorAcc

Evaluate acceleration and force-dependent sensors.

.. _mj_energyPos:

`mj_energyPos <#mj_energyPos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_energyPos

Evaluate position-dependent energy (potential).

.. _mj_energyVel:

`mj_energyVel <#mj_energyVel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_energyVel

Evaluate velocity-dependent energy (kinetic).

.. _mj_checkPos:

`mj_checkPos <#mj_checkPos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_checkPos

Check qpos, reset if any element is too big or nan.

.. _mj_checkVel:

`mj_checkVel <#mj_checkVel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_checkVel

Check qvel, reset if any element is too big or nan.

.. _mj_checkAcc:

`mj_checkAcc <#mj_checkAcc>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_checkAcc

Check qacc, reset if any element is too big or nan.

.. _mj_kinematics:

`mj_kinematics <#mj_kinematics>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_kinematics

Run forward kinematics.

.. _mj_comPos:

`mj_comPos <#mj_comPos>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_comPos

Map inertias and motion dofs to global frame centered at CoM.

.. _mj_camlight:

`mj_camlight <#mj_camlight>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_camlight

Compute camera and light positions and orientations.

.. _mj_flex:

`mj_flex <#mj_flex>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_flex

Compute flex-related quantities.

.. _mj_tendon:

`mj_tendon <#mj_tendon>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_tendon

Compute tendon lengths, velocities and moment arms.

.. _mj_transmission:

`mj_transmission <#mj_transmission>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_transmission

Compute actuator transmission lengths and moments.

.. _mj_crb:

`mj_crb <#mj_crb>`__
~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_crb

Run composite rigid body inertia algorithm (CRB).

.. _mj_makeM:

`mj_makeM <#mj_makeM>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_makeM

Compute the composite rigid body inertia with :ref:`mj_crb`, add terms due
to :ref:`tendon armature<tendon-spatial-armature>`. The joint-space inertia matrix is stored in both ``mjData.qM`` and
``mjData.M``. These arrays represent the same quantity using different layouts (parent-based and compressed sparse row,
respectively).

.. _mj_factorM:

`mj_factorM <#mj_factorM>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_factorM

Compute sparse :math:`L^T D L` factorizaton of inertia matrix.

.. _mj_solveM:

`mj_solveM <#mj_solveM>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_solveM

Solve linear system :math:`M x = y` using factorization: :math:`x = (L^T D L)^{-1} y`

.. _mj_solveM2:

`mj_solveM2 <#mj_solveM2>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_solveM2

Half of linear solve: :math:`x = \sqrt{D^{-1}} (L^T)^{-1} y`

.. _mj_comVel:

`mj_comVel <#mj_comVel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_comVel

Compute cvel, cdof_dot.

.. _mj_passive:

`mj_passive <#mj_passive>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_passive

Compute qfrc_passive from spring-dampers, gravity compensation and fluid forces.

.. _mj_subtreeVel:

`mj_subtreeVel <#mj_subtreeVel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_subtreeVel

Sub-tree linear velocity and angular momentum: compute ``subtree_linvel``, ``subtree_angmom``.
This function is triggered automatically if the subtree :ref:`velocity<sensor-subtreelinvel>` or
:ref:`momentum<sensor-subtreeangmom>` sensors are present in the model.
It is also triggered for :ref:`user sensors<sensor-user>` of :ref:`stage<sensor-user-needstage>` "vel".

.. _mj_rne:

`mj_rne <#mj_rne>`__
~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_rne

Recursive Newton Euler: compute :math:`M(q) \ddot q + C(q,\dot q)`. ``flg_acc=0`` removes the inertial term (i.e.
assumes :math:`\ddot q = 0`).

.. _mj_rnePostConstraint:

`mj_rnePostConstraint <#mj_rnePostConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_rnePostConstraint

Recursive Newton Euler with final computed forces and accelerations.
Computes three body-level ``nv x 6`` arrays, all defined in the subtreecom-based
:ref:`c-frame<tyNotesCom>` and arranged in ``[rotation(3), translation(3)]`` order.

- ``cacc``: Body acceleration, required for :ref:`mj_objectAcceleration`.
- ``cfrc_int``: Interaction force with the parent body.
- ``cfrc_ext``: External force acting on the body.

This function is triggered automatically if the following sensors are present in the model:
:ref:`accelerometer<sensor-accelerometer>`, :ref:`force<sensor-force>`, :ref:`torque<sensor-torque>`,
:ref:`framelinacc<sensor-framelinacc>`, :ref:`frameangacc<sensor-frameangacc>`.
It is also triggered for :ref:`user sensors<sensor-user>` of :ref:`stage<sensor-user-needstage>` "acc".

The computed force arrays ``cfrc_int`` and ``cfrc_ext`` currently suffer from a know bug, they do not take into account
the effect of spatial tendons, see :issue:`832`.

.. _mj_collision:

`mj_collision <#mj_collision>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_collision

Run collision detection.

.. _mj_makeConstraint:

`mj_makeConstraint <#mj_makeConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_makeConstraint

Construct constraints.

.. _mj_island:

`mj_island <#mj_island>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_island

Find constraint islands.

.. _mj_projectConstraint:

`mj_projectConstraint <#mj_projectConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_projectConstraint

Compute inverse constraint inertia efc_AR.

.. _mj_referenceConstraint:

`mj_referenceConstraint <#mj_referenceConstraint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_referenceConstraint

Compute efc_vel, efc_aref.

.. _mj_constraintUpdate:

`mj_constraintUpdate <#mj_constraintUpdate>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_constraintUpdate

Compute ``efc_state``, ``efc_force``, ``qfrc_constraint``, and (optionally) cone Hessians.
If ``cost`` is not ``NULL``, set ``*cost = s(jar)`` where ``jar = Jac*qacc - aref``.

*Nullable:* ``cost``

.. _Raycollisions:

Ray casting
^^^^^^^^^^^

Ray collisions, also known as ray casting, find the distance ``x`` of a ray's intersection with a geom, where a ray is
a line emanating from the 3D point ``p`` in the direction ``v`` i.e., ``(p + x*v, x >= 0)``. All functions in this
family return the distance to the nearest geom surface, or -1 if there is no intersection. Note that if ``p`` is inside
a geom, the ray will intersect the surface from the inside which still counts as an intersection.

All ray collision functions rely on quantities computed by :ref:`mj_kinematics` (see :ref:`mjData`), so must be called
after  :ref:`mj_kinematics`, or functions that call it (e.g. :ref:`mj_fwdPosition`). The top level functions, which
intersect with all geoms types, are :ref:`mj_ray` which casts a single ray, and :ref:`mj_multiRay` which casts multiple
rays from a single point.

.. _mj_ray:

`mj_ray <#mj_ray>`__
~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_ray

Intersect ray ``pnt+x*vec, x >= 0`` with geoms.

- Return distance ``x`` to nearest surface, or -1 if no intersection.
- If ``geomid`` is not NULL, write the id of the intersected geom or -1 if not intersection.
- If ``normal`` is not NULL, write the surface normal at the intersection point. The normal always points **out of the
  geometry**, regardless of the ray's direction (i.e., including rays hitting the surface from the inside).
- Exclude geoms in body with id ``bodyexclude``, use -1 to include all bodies.
- ``geomgroup`` is an array of length :ref:`mjNGROUP<glNumeric>`, where 1 means the group should be included. Pass
  NULL to skip geom group exclusion.
- If ``flg_static`` is 0, static geoms will be excluded.

*Nullable:* ``geomgroup``, ``geomid``, ``normal``

.. _mj_multiRay:

`mj_multiRay <#mj_multiRay>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_multiRay

Intersect multiple rays emanating from a single point, compute normals if given.

Similar semantics to mj_ray, but vec, normal and dist are arrays.

Geoms further than cutoff are ignored.

*Nullable:* ``geomgroup``, ``geomid``, ``normal``

.. _mj_rayHfield:

`mj_rayHfield <#mj_rayHfield>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_rayHfield

Intersect ray with hfield; return nearest distance or -1 if no intersection.

*Nullable:* ``normal``

.. _mj_rayMesh:

`mj_rayMesh <#mj_rayMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_rayMesh

Intersect ray with mesh; return nearest distance or -1 if no intersection.

*Nullable:* ``normal``

.. _mju_rayGeom:

`mju_rayGeom <#mju_rayGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_rayGeom

Intersect ray with pure geom; return nearest distance or -1 if no intersection.

*Nullable:* ``normal``

.. _mj_rayFlex:

`mj_rayFlex <#mj_rayFlex>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_rayFlex

Intersect ray with flex; return nearest distance or -1 if no intersection,
and also output nearest vertex id and surface normal.

*Nullable:* ``vertid``, ``normal``

.. _mju_raySkin:

`mju_raySkin <#mju_raySkin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_raySkin

Intersect ray with skin; return nearest distance or -1 if no intersection,
and also output nearest vertex id.

*Nullable:* ``vertid``

.. _Printing:

Printing
^^^^^^^^

These functions can be used to print various quantities to the screen for debugging purposes.

.. _mj_printFormattedModel:

`mj_printFormattedModel <#mj_printFormattedModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printFormattedModel

Print mjModel to text file, specifying format.
float_format must be a valid printf-style format string for a single float value.

.. _mj_printModel:

`mj_printModel <#mj_printModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printModel

Print model to text file.

.. _mj_printFormattedData:

`mj_printFormattedData <#mj_printFormattedData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printFormattedData

Print mjData to text file, specifying format.
float_format must be a valid printf-style format string for a single float value.

.. _mj_printData:

`mj_printData <#mj_printData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printData

Print data to text file.

.. _mju_printMat:

`mju_printMat <#mju_printMat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_printMat

Print matrix to screen.

.. _mju_printMatSparse:

`mju_printMatSparse <#mju_printMatSparse>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_printMatSparse

Print sparse matrix to screen.

.. _mj_printSchema:

`mj_printSchema <#mj_printSchema>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printSchema

Print internal XML schema as plain text or HTML, with style-padding or ``&nbsp;``.

.. _mj_printScene:

`mj_printScene <#mj_printScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printScene

Print scene to text file.

.. _mj_printFormattedScene:

`mj_printFormattedScene <#mj_printFormattedScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_printFormattedScene

Print scene to text file, specifying format.
float_format must be a valid printf-style format string for a single float value.

.. _Virtualfilesystem:

Virtual file system
^^^^^^^^^^^^^^^^^^^

Virtual file system (VFS) enables the user to load all necessary files in memory, including MJB binary model files, XML
files (MJCF, URDF and included files), STL meshes, PNGs for textures and height fields, and HF files in our custom
height field format. Model and resource files in the VFS can also be constructed programmatically (say using a Python
library that writes to memory). Once all desired files are in the VFS, the user can call :ref:`mj_loadModel` or
:ref:`mj_loadXML` with a pointer to the VFS. When this pointer is not NULL, the loaders will first check the VFS for any
files they are about to load, and only access the disk if the file is not found in the VFS.

The VFS must first be allocated using :ref:`mj_defaultVFS` and must be freed with :ref:`mj_deleteVFS`.


.. _mj_defaultVFS:

`mj_defaultVFS <#mj_defaultVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_defaultVFS

Initialize an empty VFS, :ref:`mj_deleteVFS` must be called to deallocate the VFS.

.. _mj_mountVFS:

`mj_mountVFS <#mj_mountVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_mountVFS

Mount a ResourceProvider to handle file operations under the given path; return 0: success,
2: repeated name, -1: invalid resource provider.

.. _mj_unmountVFS:

`mj_unmountVFS <#mj_unmountVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_unmountVFS

Unmount a previously mounted ResourceProvider; return 0: success, -1: not found in VFS.

.. _mj_addFileVFS:

`mj_addFileVFS <#mj_addFileVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_addFileVFS

Add file to VFS. The directory argument is optional and can be NULL or empty. Returns 0 on success,
2 on name collision, or -1 when an internal error occurs.

*Nullable:* ``directory``

.. _mj_addBufferVFS:

`mj_addBufferVFS <#mj_addBufferVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_addBufferVFS

Add file to VFS from buffer; return 0: success, 2: repeated name, -1: failed to load.

.. _mj_deleteFileVFS:

`mj_deleteFileVFS <#mj_deleteFileVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_deleteFileVFS

Delete file from VFS; return 0: success, -1: not found in VFS.

.. _mj_deleteVFS:

`mj_deleteVFS <#mj_deleteVFS>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_deleteVFS

Delete all files from VFS and deallocates VFS internal memory.

.. _Assetcache:

Asset cache
^^^^^^^^^^^

The asset cache is a mechanism for caching assets (e.g. textures, meshes, etc.) to avoid repeated slow recompilation.
The following methods provide way to control the capacity of the cache or to disable it altogether.

.. _mj_getCacheSize:

`mj_getCacheSize <#mj_getCacheSize>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getCacheSize

Get the current size of the asset cache in bytes.

.. _mj_getCacheCapacity:

`mj_getCacheCapacity <#mj_getCacheCapacity>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getCacheCapacity

Get the capacity of the asset cache in bytes.

.. _mj_setCacheCapacity:

`mj_setCacheCapacity <#mj_setCacheCapacity>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setCacheCapacity

Set the capacity of the asset cache in bytes (0 to disable); return the new capacity.

.. _mj_getCache:

`mj_getCache <#mj_getCache>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_getCache

Get the internal asset cache used by the compiler.

.. _mj_clearCache:

`mj_clearCache <#mj_clearCache>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_clearCache

Clear the asset cache.

.. _Resources:

Resources
^^^^^^^^^

Resources are the interface between :ref:`resource providers <exProvider>` and MuJoCo model compilation code.
These functions provide the means to query the resource provider and obtain resources.
.. _mju_openResource:

`mju_openResource <#mju_openResource>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_openResource

Open a resource; if the name doesn't have a prefix matching a registered resource provider,
then the OS filesystem is used.

*Nullable:* ``dir``, ``vfs``, ``error``

.. _mju_closeResource:

`mju_closeResource <#mju_closeResource>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_closeResource

Close a resource; no-op if resource is NULL.

.. _mju_readResource:

`mju_readResource <#mju_readResource>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_readResource

Set buffer to bytes read from the resource and return number of bytes in buffer;
return negative value if error.

.. _mju_getResourceDir:

`mju_getResourceDir <#mju_getResourceDir>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_getResourceDir

For a resource with a name partitioned as {dir}{filename}, get the dir and ndir pointers.

.. _mju_isModifiedResource:

`mju_isModifiedResource <#mju_isModifiedResource>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_isModifiedResource

Compare resource timestamp to provided timestamp.

Return 0 if timestamps match, >0 if resource is newer, <0 if resource is older.

.. _mju_decodeResource:

`mju_decodeResource <#mju_decodeResource>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_decodeResource

Find the decoder for a resource and return the decoded spec.

The caller takes ownership of the spec and is responsible for cleaning it up.

*Nullable:* ``vfs``

.. _Initialization:

Initialization
^^^^^^^^^^^^^^

This section contains functions that load/initialize the model or other data structures. Their use is well illustrated
in the code samples.

.. _mj_defaultLROpt:

`mj_defaultLROpt <#mj_defaultLROpt>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_defaultLROpt

Set default options for length range computation.

.. _mj_defaultSolRefImp:

`mj_defaultSolRefImp <#mj_defaultSolRefImp>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_defaultSolRefImp

Set solver parameters to default values.

*Nullable:* ``solref``, ``solimp``

.. _mj_defaultOption:

`mj_defaultOption <#mj_defaultOption>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_defaultOption

Set physics options to default values.

.. _mj_defaultVisual:

`mj_defaultVisual <#mj_defaultVisual>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_defaultVisual

Set visual options to default values.

.. _mj_copyModel:

`mj_copyModel <#mj_copyModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_copyModel

Copy mjModel, allocate new if dest is NULL.

*Nullable:* ``dest``

.. _mj_saveModel:

`mj_saveModel <#mj_saveModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_saveModel

Save model to binary MJB file or memory buffer; buffer has precedence when given.

*Nullable:* ``filename``, ``buffer``

.. _mj_loadModel:

`mj_loadModel <#mj_loadModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_loadModel

Load model from binary MJB file.

If vfs is not NULL, look up file in vfs before reading from disk.

*Nullable:* ``vfs``

.. _mj_loadModelBuffer:

`mj_loadModelBuffer <#mj_loadModelBuffer>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_loadModelBuffer

Load model from memory buffer.

.. _mj_deleteModel:

`mj_deleteModel <#mj_deleteModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_deleteModel

Free memory allocation in model.

.. _mj_sizeModel:

`mj_sizeModel <#mj_sizeModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_sizeModel

Return size of buffer needed to hold model.

.. _mj_makeData:

`mj_makeData <#mj_makeData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_makeData

Allocate mjData corresponding to given model.

If the model buffer is unallocated the initial configuration will not be set.

.. _mj_copyData:

`mj_copyData <#mj_copyData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_copyData

Copy mjData.
m is only required to contain the size fields from MJMODEL_INTS.

.. _mjv_copyData:

`mjv_copyData <#mjv_copyData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_copyData

Copy mjData, skip large arrays not required for visualization.

.. _mj_resetData:

`mj_resetData <#mj_resetData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_resetData

Reset data to defaults.

.. _mj_resetDataDebug:

`mj_resetDataDebug <#mj_resetDataDebug>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_resetDataDebug

Reset data to defaults, fill everything else with debug_value.

.. _mj_resetDataKeyframe:

`mj_resetDataKeyframe <#mj_resetDataKeyframe>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_resetDataKeyframe

Reset data. If 0 <= key < nkey, set fields from specified keyframe.

.. _mj_markStack:

`mj_markStack <#mj_markStack>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_markStack

Mark a new frame on the mjData stack.

.. _mj_freeStack:

`mj_freeStack <#mj_freeStack>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_freeStack

Free the current mjData stack frame. All pointers returned by mj_stackAlloc since the last call
to mj_markStack must no longer be used afterwards.

.. _mj_stackAllocByte:

`mj_stackAllocByte <#mj_stackAllocByte>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_stackAllocByte

Allocate a number of bytes on mjData stack at a specific alignment.

Call mju_error on stack overflow.

.. _mj_stackAllocNum:

`mj_stackAllocNum <#mj_stackAllocNum>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_stackAllocNum

Allocate array of mjtNums on mjData stack. Call mju_error on stack overflow.

.. _mj_stackAllocInt:

`mj_stackAllocInt <#mj_stackAllocInt>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_stackAllocInt

Allocate array of ints on mjData stack. Call mju_error on stack overflow.

.. _mj_deleteData:

`mj_deleteData <#mj_deleteData>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_deleteData

Free memory allocation in mjData.

.. _mj_resetCallbacks:

`mj_resetCallbacks <#mj_resetCallbacks>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_resetCallbacks

Reset all callbacks to NULL pointers (NULL is the default).

.. _mj_setConst:

`mj_setConst <#mj_setConst>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setConst

Set constant fields of mjModel, corresponding to qpos0 configuration.

.. _mj_setLengthRange:

`mj_setLengthRange <#mj_setLengthRange>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_setLengthRange

Set actuator_lengthrange for specified actuator; return 1 if ok, 0 if error.

*Nullable:* ``error``

.. _mj_makeSpec:

`mj_makeSpec <#mj_makeSpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_makeSpec

Create empty spec.

.. _mj_copySpec:

`mj_copySpec <#mj_copySpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_copySpec

Copy spec.

.. _mj_deleteSpec:

`mj_deleteSpec <#mj_deleteSpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_deleteSpec

Free memory allocation in mjSpec.

.. _mjs_activatePlugin:

`mjs_activatePlugin <#mjs_activatePlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_activatePlugin

Activate plugin; return 0 on success.

.. _mjs_setDeepCopy:

`mjs_setDeepCopy <#mjs_setDeepCopy>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setDeepCopy

Turn deep copy on or off attach; return 0 on success.

.. _Errorandmemory:

Error and memory
^^^^^^^^^^^^^^^^

.. _mju_error:

`mju_error <#mju_error>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_error

Main error function; does not return to caller.

.. _mju_error_i:

`mju_error_i <#mju_error_i>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_error_i

Deprecated: use mju_error.

.. _mju_error_s:

`mju_error_s <#mju_error_s>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_error_s

Deprecated: use mju_error.

.. _mju_warning:

`mju_warning <#mju_warning>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_warning

Main warning function; returns to caller.

.. _mju_warning_i:

`mju_warning_i <#mju_warning_i>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_warning_i

Deprecated: use mju_warning.

.. _mju_warning_s:

`mju_warning_s <#mju_warning_s>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_warning_s

Deprecated: use mju_warning.

.. _mju_clearHandlers:

`mju_clearHandlers <#mju_clearHandlers>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_clearHandlers

Clear user error and memory handlers.

.. _mju_malloc:

`mju_malloc <#mju_malloc>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_malloc

Allocate memory; byte-align on 64; pad size to multiple of 64.

.. _mju_free:

`mju_free <#mju_free>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_free

Free memory, using free() by default.

.. _mj_warning:

`mj_warning <#mj_warning>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mj_warning

High-level warning function: count warnings in mjData, print only the first.

.. _mju_writeLog:

`mju_writeLog <#mju_writeLog>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_writeLog

Write [datetime, type: message] to MUJOCO_LOG.TXT.

.. _mjs_getError:

`mjs_getError <#mjs_getError>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getError

Get compiler error message from spec.

.. _mjs_isWarning:

`mjs_isWarning <#mjs_isWarning>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_isWarning

Return 1 if compiler error is a warning.

.. _Miscellaneous:

Miscellaneous
^^^^^^^^^^^^^

.. _mju_muscleGain:

`mju_muscleGain <#mju_muscleGain>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_muscleGain

Muscle active force, prm = (range[2], force, scale, lmin, lmax, vmax, fpmax, fvmax).

.. _mju_muscleBias:

`mju_muscleBias <#mju_muscleBias>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_muscleBias

Muscle passive force, prm = (range[2], force, scale, lmin, lmax, vmax, fpmax, fvmax).

.. _mju_muscleDynamics:

`mju_muscleDynamics <#mju_muscleDynamics>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_muscleDynamics

Muscle activation dynamics, prm = (tau_act, tau_deact, smoothing_width).

.. _mju_encodePyramid:

`mju_encodePyramid <#mju_encodePyramid>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_encodePyramid

Convert contact force to pyramid representation.

.. _mju_decodePyramid:

`mju_decodePyramid <#mju_decodePyramid>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_decodePyramid

Convert pyramid representation to contact force.

.. _mju_springDamper:

`mju_springDamper <#mju_springDamper>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_springDamper

Integrate spring-damper analytically; return pos(dt).

.. _mju_min:

`mju_min <#mju_min>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_min

Return min(a,b) with single evaluation of a and b.

.. _mju_max:

`mju_max <#mju_max>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_max

Return max(a,b) with single evaluation of a and b.

.. _mju_clip:

`mju_clip <#mju_clip>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_clip

Clip x to the range [min, max].

.. _mju_sign:

`mju_sign <#mju_sign>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sign

Return sign of x: +1, -1 or 0.

.. _mju_round:

`mju_round <#mju_round>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_round

Round x to nearest integer.

.. _mju_type2Str:

`mju_type2Str <#mju_type2Str>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_type2Str

Convert type id (mjtObj) to type name.

.. _mju_str2Type:

`mju_str2Type <#mju_str2Type>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_str2Type

Convert type name to type id (mjtObj).

.. _mju_writeNumBytes:

`mju_writeNumBytes <#mju_writeNumBytes>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_writeNumBytes

Return human readable number of bytes using standard letter suffix.

.. _mju_warningText:

`mju_warningText <#mju_warningText>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_warningText

Construct a warning message given the warning type and info.

.. _mju_isBad:

`mju_isBad <#mju_isBad>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_isBad

Return 1 if nan or abs(x)>mjMAXVAL, 0 otherwise. Used by check functions.

.. _mju_isZero:

`mju_isZero <#mju_isZero>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_isZero

Return 1 if all elements are 0.

.. _mju_standardNormal:

`mju_standardNormal <#mju_standardNormal>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_standardNormal

Standard normal random number generator (optional second number).

.. _mju_f2n:

`mju_f2n <#mju_f2n>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_f2n

Convert from float to mjtNum.

.. _mju_n2f:

`mju_n2f <#mju_n2f>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_n2f

Convert from mjtNum to float.

.. _mju_d2n:

`mju_d2n <#mju_d2n>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_d2n

Convert from double to mjtNum.

.. _mju_n2d:

`mju_n2d <#mju_n2d>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_n2d

Convert from mjtNum to double.

.. _mju_insertionSort:

`mju_insertionSort <#mju_insertionSort>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_insertionSort

Insertion sort, resulting list is in increasing order.

.. _mju_insertionSortInt:

`mju_insertionSortInt <#mju_insertionSortInt>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_insertionSortInt

Integer insertion sort, resulting list is in increasing order.

.. _mju_Halton:

`mju_Halton <#mju_Halton>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_Halton

Generate Halton sequence.

.. _mju_strncpy:

`mju_strncpy <#mju_strncpy>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_strncpy

Call strncpy, then set dst[n-1] = 0.

.. _mju_sigmoid:

`mju_sigmoid <#mju_sigmoid>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sigmoid

Twice continuously differentiable sigmoid function using a quintic polynomial:

.. math::
   s(x) =
   \begin{cases}
      0,                    &       & x \le 0  \\
      6x^5 - 15x^4 + 10x^3, & 0 \lt & x \lt 1  \\
      1,                    & 1 \le & x \qquad
   \end{cases}

.. _Interaction:

Interaction
^^^^^^^^^^^

These functions implement abstract mouse interactions, allowing control over cameras and perturbations. Their use is well
illustrated in :ref:`simulate<saSimulate>`.

.. _mjv_defaultCamera:

`mjv_defaultCamera <#mjv_defaultCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultCamera

Set default camera.

.. _mjv_defaultFreeCamera:

`mjv_defaultFreeCamera <#mjv_defaultFreeCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultFreeCamera

Set default free camera.

.. _mjv_defaultPerturb:

`mjv_defaultPerturb <#mjv_defaultPerturb>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultPerturb

Set default perturbation.

.. _mjv_room2model:

`mjv_room2model <#mjv_room2model>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_room2model

Transform pose from room to model space.

.. _mjv_model2room:

`mjv_model2room <#mjv_model2room>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_model2room

Transform pose from model to room space.

.. _mjv_cameraInModel:

`mjv_cameraInModel <#mjv_cameraInModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_cameraInModel

Get camera info in model space; average left and right OpenGL cameras.

.. _mjv_cameraInRoom:

`mjv_cameraInRoom <#mjv_cameraInRoom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_cameraInRoom

Get camera info in room space; average left and right OpenGL cameras.

.. _mjv_frustumHeight:

`mjv_frustumHeight <#mjv_frustumHeight>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_frustumHeight

Get frustum height at unit distance from camera; average left and right OpenGL cameras.

.. _mjv_alignToCamera:

`mjv_alignToCamera <#mjv_alignToCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_alignToCamera

Rotate 3D vec in horizontal plane by angle between (0,1) and (forward_x,forward_y).

.. _mjv_moveCamera:

`mjv_moveCamera <#mjv_moveCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_moveCamera

Move camera with mouse; action is mjtMouse.

.. _mjv_movePerturb:

`mjv_movePerturb <#mjv_movePerturb>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_movePerturb

Move perturb object with mouse; action is mjtMouse.

.. _mjv_moveModel:

`mjv_moveModel <#mjv_moveModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_moveModel

Move model with mouse; action is mjtMouse.

.. _mjv_initPerturb:

`mjv_initPerturb <#mjv_initPerturb>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_initPerturb

Copy perturb pos,quat from selected body; set scale for perturbation.

.. _mjv_applyPerturbPose:

`mjv_applyPerturbPose <#mjv_applyPerturbPose>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_applyPerturbPose

Set perturb pos,quat in d->mocap when selected body is mocap, and in d->qpos otherwise.

Write d->qpos only if flg_paused and subtree root for selected body has free joint.

.. _mjv_applyPerturbForce:

`mjv_applyPerturbForce <#mjv_applyPerturbForce>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_applyPerturbForce

Set perturb force,torque in d->xfrc_applied, if selected body is dynamic.

.. _mjv_averageCamera:

`mjv_averageCamera <#mjv_averageCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_averageCamera

Return the average of two OpenGL cameras.

.. _mjv_select:

`mjv_select <#mjv_select>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_select

This function is used for mouse selection, relying on ray intersections. aspectratio is the viewport width/height. relx
and rely are the relative coordinates of the 2D point of interest in the viewport (usually mouse cursor). The function
returns the id of the geom under the specified 2D point, or -1 if there is no geom (note that they skybox if present is
not a model geom). The 3D coordinates of the clicked point are returned in selpnt. See :ref:`simulate<saSimulate>` for
an illustration.

.. _Visualization-api:

Visualization
^^^^^^^^^^^^^

The functions in this section implement abstract visualization. The results are used by the OpenGL renderer, and can
also be used by users wishing to implement their own renderer, or hook up MuJoCo to advanced rendering tools such as
Unity or Unreal Engine. See :ref:`simulate<saSimulate>` for illustration of how to use these functions.

.. _mjv_defaultOption:

`mjv_defaultOption <#mjv_defaultOption>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultOption

Set default visualization options.

.. _mjv_defaultFigure:

`mjv_defaultFigure <#mjv_defaultFigure>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultFigure

Set default figure.

.. _mjv_initGeom:

`mjv_initGeom <#mjv_initGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_initGeom

Initialize given geom fields when not NULL, set the rest to their default values.

*Nullable:* ``size``, ``pos``, ``mat``, ``rgba``

.. _mjv_connector:

`mjv_connector <#mjv_connector>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_connector

Set (type, size, pos, mat) for connector-type geom between given points.

Assume that mjv_initGeom was already called to set all other properties.

Width of mjGEOM_LINE is denominated in pixels.

.. _mjv_defaultScene:

`mjv_defaultScene <#mjv_defaultScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_defaultScene

Set default abstract scene.

.. _mjv_makeScene:

`mjv_makeScene <#mjv_makeScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_makeScene

Allocate resources in abstract scene.

.. _mjv_freeScene:

`mjv_freeScene <#mjv_freeScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_freeScene

Free abstract scene.

.. _mjv_updateScene:

`mjv_updateScene <#mjv_updateScene>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_updateScene

Update entire scene given model state.

.. _mjv_copyModel:

`mjv_copyModel <#mjv_copyModel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_copyModel

Copy mjModel, skip large arrays not required for abstract visualization.

*Nullable:* ``dest``

.. _mjv_addGeoms:

`mjv_addGeoms <#mjv_addGeoms>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_addGeoms

Add geoms from selected categories.

.. _mjv_makeLights:

`mjv_makeLights <#mjv_makeLights>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_makeLights

Make list of lights.

.. _mjv_updateCamera:

`mjv_updateCamera <#mjv_updateCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_updateCamera

Update camera.

.. _mjv_updateSkin:

`mjv_updateSkin <#mjv_updateSkin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_updateSkin

Update skins.

.. _mjv_cameraFrame:

`mjv_cameraFrame <#mjv_cameraFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_cameraFrame

Compute camera position and forward, up, and right vectors.

*Nullable:* ``headpos``, ``forward``, ``up``, ``right``

.. _mjv_cameraFrustum:

`mjv_cameraFrustum <#mjv_cameraFrustum>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjv_cameraFrustum

Compute camera frustum: vertical, horizontal, and clip planes.

*Nullable:* ``zver``, ``zhor``, ``zclip``

.. _OpenGLrendering:

OpenGL rendering
^^^^^^^^^^^^^^^^

These functions expose the OpenGL renderer. See :ref:`simulate<saSimulate>` for an illustration
of how to use these functions.

.. _mjr_defaultContext:

`mjr_defaultContext <#mjr_defaultContext>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_defaultContext

Set default mjrContext.

.. _mjr_makeContext:

`mjr_makeContext <#mjr_makeContext>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_makeContext

Allocate resources in custom OpenGL context; fontscale is mjtFontScale.

.. _mjr_changeFont:

`mjr_changeFont <#mjr_changeFont>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_changeFont

Change font of existing context.

.. _mjr_addAux:

`mjr_addAux <#mjr_addAux>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_addAux

Add Aux buffer with given index to context; free previous Aux buffer.

.. _mjr_freeContext:

`mjr_freeContext <#mjr_freeContext>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_freeContext

Free resources in custom OpenGL context, set to default.

.. _mjr_resizeOffscreen:

`mjr_resizeOffscreen <#mjr_resizeOffscreen>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_resizeOffscreen

Resize offscreen buffers.

.. _mjr_uploadTexture:

`mjr_uploadTexture <#mjr_uploadTexture>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_uploadTexture

Upload texture to GPU, overwriting previous upload if any.

.. _mjr_uploadMesh:

`mjr_uploadMesh <#mjr_uploadMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_uploadMesh

Upload mesh to GPU, overwriting previous upload if any.

.. _mjr_uploadHField:

`mjr_uploadHField <#mjr_uploadHField>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_uploadHField

Upload height field to GPU, overwriting previous upload if any.

.. _mjr_restoreBuffer:

`mjr_restoreBuffer <#mjr_restoreBuffer>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_restoreBuffer

Make con->currentBuffer current again.

.. _mjr_setBuffer:

`mjr_setBuffer <#mjr_setBuffer>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_setBuffer

Set OpenGL framebuffer for rendering: mjFB_WINDOW or mjFB_OFFSCREEN.

If only one buffer is available, set that buffer and ignore framebuffer argument.

.. _mjr_readPixels:

`mjr_readPixels <#mjr_readPixels>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_readPixels

Read pixels from current OpenGL framebuffer to client buffer.

Viewport is in OpenGL framebuffer; client buffer starts at (0,0).

.. _mjr_drawPixels:

`mjr_drawPixels <#mjr_drawPixels>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_drawPixels

Draw pixels from client buffer to current OpenGL framebuffer.

Viewport is in OpenGL framebuffer; client buffer starts at (0,0).

.. _mjr_blitBuffer:

`mjr_blitBuffer <#mjr_blitBuffer>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_blitBuffer

Blit from src viewpoint in current framebuffer to dst viewport in other framebuffer.

If src, dst have different size and flg_depth==0, color is interpolated with GL_LINEAR.

.. _mjr_setAux:

`mjr_setAux <#mjr_setAux>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_setAux

Set Aux buffer for custom OpenGL rendering (call restoreBuffer when done).

.. _mjr_blitAux:

`mjr_blitAux <#mjr_blitAux>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_blitAux

Blit from Aux buffer to con->currentBuffer.

.. _mjr_text:

`mjr_text <#mjr_text>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_text

Draw text at (x,y) in relative coordinates; font is mjtFont.

.. _mjr_overlay:

`mjr_overlay <#mjr_overlay>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_overlay

Draw text overlay; font is mjtFont; gridpos is mjtGridPos.

.. _mjr_maxViewport:

`mjr_maxViewport <#mjr_maxViewport>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_maxViewport

Get maximum viewport for active buffer.

.. _mjr_rectangle:

`mjr_rectangle <#mjr_rectangle>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_rectangle

Draw rectangle.

.. _mjr_label:

`mjr_label <#mjr_label>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_label

Draw rectangle with centered text.

.. _mjr_figure:

`mjr_figure <#mjr_figure>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_figure

Draw 2D figure.

.. _mjr_render:

`mjr_render <#mjr_render>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_render

Render 3D scene.

.. _mjr_finish:

`mjr_finish <#mjr_finish>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_finish

Call glFinish.

.. _mjr_getError:

`mjr_getError <#mjr_getError>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_getError

Call glGetError and return result.

.. _mjr_findRect:

`mjr_findRect <#mjr_findRect>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjr_findRect

Find first rectangle containing mouse, -1: not found.

.. _UIframework:

UI framework
^^^^^^^^^^^^

For a high-level description of the UI framework, see :ref:`UI`.

.. _mjui_themeSpacing:

`mjui_themeSpacing <#mjui_themeSpacing>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_themeSpacing

Get builtin UI theme spacing (ind: 0-1).

.. _mjui_themeColor:

`mjui_themeColor <#mjui_themeColor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_themeColor

Get builtin UI theme color (ind: 0-3).

.. _mjui_add:

`mjui_add <#mjui_add>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_add

This is the helper function used to construct a UI. The second argument points to an array of :ref:`mjuiDef` structs,
each corresponding to one item. The last (unused) item has its type set to -1, to mark termination. The items are added
after the end of the last used section. There is also another version of this function
(:ref:`mjui_addToSection<mjui_addToSection>`) which adds items to a specified section instead of adding them at the end
of the UI. Keep in mind that there is a maximum preallocated number of sections and items per section, given by
:ref:`mjMAXUISECT<glNumeric>` and :ref:`mjMAXUIITEM<glNumeric>`. Exceeding these maxima results in low-level errors.

.. _mjui_addToSection:

`mjui_addToSection <#mjui_addToSection>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_addToSection

Add definitions to UI section.

.. _mjui_resize:

`mjui_resize <#mjui_resize>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_resize

Compute UI sizes.

.. _mjui_update:

`mjui_update <#mjui_update>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_update

This is the main UI update function. It needs to be called whenever the user data (pointed to by the item data pointers)
changes, or when the UI state itself changes. It is normally called by a higher-level function implemented by the user
(``UiModify`` in :ref:`simulate.cc <saSimulate>`) which also recomputes the layout of all rectangles and associated
auxiliary buffers. The function updates the pixels in the offscreen OpenGL buffer. To perform minimal updates, the user
specifies the section and the item that was modified. A value of -1 means all items and/or sections need to be updated
(which is needed following major changes.)

.. _mjui_event:

`mjui_event <#mjui_event>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_event

This function is the low-level event handler. It makes the necessary changes in the UI and returns a pointer to the item
that received the event (or ``NULL`` if no valid event was recorded). This is normally called within the event handler
implemented by the user (``UiEvent`` in :ref:`simulate.cc <saSimulate>`), and then some action is taken by user code
depending on which UI item was modified and what the state of that item is after the event is handled.

.. _mjui_render:

`mjui_render <#mjui_render>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjui_render

This function is called in the screen refresh loop. It copies the offscreen OpenGL buffer to the window framebuffer. If
there are multiple UIs in the application, it should be called once for each UI. Thus ``mjui_render`` is called all the
time, while :ref:`mjui_update` is called only when changes in the UI take place. dsffsdg

.. _Derivatives-api:

Derivatives
^^^^^^^^^^^

The functions below provide useful derivatives of various functions, both analytic and
finite-differenced. The latter have names with the suffix ``FD``. Note that unlike much of the API,
outputs of derivative functions are the trailing rather than leading arguments.

.. _mjd_transitionFD:

`mjd_transitionFD <#mjd_transitionFD>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjd_transitionFD

Compute finite-differenced discrete-time transition matrices.

Letting :math:`x, u` denote the current :ref:`state<siPhysicsState>` and :ref:`control<siInput>`
vector in an mjData instance, and letting :math:`y, s` denote the next state and sensor
values, the top-level :ref:`mj_step` function computes :math:`(x,u) \rightarrow (y,s)`
:ref:`mjd_transitionFD` computes the four associated Jacobians using finite-differencing.
These matrices and their dimensions are:

.. csv-table::
   :header: "matrix", "Jacobian", "dimension"
   :widths: auto
   :align: left

   ``A``, :math:`\partial y / \partial x`, ``2*nv+na x 2*nv+na``
   ``B``, :math:`\partial y / \partial u`, ``2*nv+na x nu``
   ``C``, :math:`\partial s / \partial x`, ``nsensordata x 2*nv+na``
   ``D``, :math:`\partial s / \partial u`, ``nsensordata x nu``

- All outputs are optional (can be NULL).
- ``eps`` is the finite-differencing epsilon.
- ``flg_centered`` denotes whether to use forward (0) or centered (1) differences.
- The Runge-Kutta integrator (:ref:`mjINT_RK4<mjtIntegrator>`) is not supported.

.. admonition:: Improving speed and accuracy
   :class: tip

   warmstart
     If warm-starts are not :ref:`disabled<option-flag-warmstart>`, the warm-start accelerations
     ``mjData.qacc_warmstart`` which are present at call-time are loaded at the start of every relevant pipeline call,
     to preserve determinism. If solver computations are an expensive part of the simulation, the following trick can
     lead to significant speed-ups: First call :ref:`mj_forward` to let the solver converge, then reduce :ref:`solver
     iterations<option-iterations>` significantly, then call :ref:`mjd_transitionFD`, finally, restore the original
     value of :ref:`iterations<option-iterations>`. Because we are already near the solution, few iteration are required
     to find the new minimum. This is especially true for the :ref:`Newton<option-solver>` solver, where the required
     number of iteration for convergence near the minimum can be as low as 1.

   tolerance
      Accuracy can be improved if solver :ref:`tolerance<option-tolerance>` is set to 0. This means that all calls to
      the solver will perform exactly the same number of iterations, preventing numerical errors due to early
      termination. Of course, this means that :ref:`solver iterations<option-iterations>` should be small, to not tread
      water at the minimum. This method and the one described above can and should be combined.

*Nullable:* ``A``, ``B``, ``D``, ``C``

.. _mjd_inverseFD:

`mjd_inverseFD <#mjd_inverseFD>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjd_inverseFD

Finite differenced continuous-time inverse-dynamics Jacobians.

Letting :math:`x, a` denote the current :ref:`state<siPhysicsState>` and acceleration vectors in an mjData instance, and
letting :math:`f, s` denote the forces computed by the inverse dynamics (``qfrc_inverse``), the function
:ref:`mj_inverse` computes :math:`(x,a) \rightarrow (f,s)`. :ref:`mjd_inverseFD` computes seven associated Jacobians
using finite-differencing. These matrices and their dimensions are:

.. csv-table::
   :header: "matrix", "Jacobian", "dimension"
   :widths: auto
   :align: left

   ``DfDq``, :math:`\partial f / \partial q`, ``nv x nv``
   ``DfDv``, :math:`\partial f / \partial v`, ``nv x nv``
   ``DfDa``, :math:`\partial f / \partial a`, ``nv x nv``
   ``DsDq``, :math:`\partial s / \partial q`, ``nv x nsensordata``
   ``DsDv``, :math:`\partial s / \partial v`, ``nv x nsensordata``
   ``DsDa``, :math:`\partial s / \partial a`, ``nv x nsensordata``
   ``DmDq``, :math:`\partial M / \partial q`, ``nv x nM``

- All outputs are optional (can be NULL).
- All outputs are transposed relative to Control Theory convention (i.e., column major).
- ``DmDq``, which contains a sparse representation of the ``nv x nv x nv`` tensor :math:`\partial M / \partial q`, is
  not strictly an inverse dynamics Jacobian but is useful in related applications. It is provided as a convenience to
  the user, since the required values are already computed if either of the other two :math:`\partial / \partial q`
  Jacobians are requested.
- ``eps`` is the (forward) finite-differencing epsilon.
- ``flg_actuation`` denotes whether to subtract actuation forces (``qfrc_actuator``) from the output of the inverse
  dynamics. If this flag is positive, actuator forces are not considered as external.
- The model option flag ``invdiscrete`` should correspond to the representation of ``mjData.qacc`` in order to compute
  the correct derivative information.

.. attention::
   - The Runge-Kutta 4th-order integrator (``mjINT_RK4``) is not supported.
   - The noslip solver is not supported.

*Nullable:* ``DfDq``, ``DfDv``, ``DfDa``, ``DsDq``, ``DsDv``, ``DsDa``, ``DmDq``

.. _mjd_subQuat:

`mjd_subQuat <#mjd_subQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjd_subQuat

Derivatives of :ref:`mju_subQuat` (quaternion difference).

*Nullable:* ``Da``, ``Db``

.. _mjd_quatIntegrate:

`mjd_quatIntegrate <#mjd_quatIntegrate>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjd_quatIntegrate

Derivatives of :ref:`mju_quatIntegrate`.

:math:`{\tt \small mju\_quatIntegrate}(q, v, h)` performs the in-place rotation :math:`q \leftarrow q + v h`,
where :math:`q \in \mathbf{S}^3` is a unit quaternion, :math:`v \in \mathbf{R}^3` is a 3D angular velocity and
:math:`h \in \mathbf{R^+}` is a timestep. This is equivalent to :math:`{\tt \small mju\_quatIntegrate}(q, s, 1.0)`,
where :math:`s` is the scaled velocity :math:`s = h v`.

:math:`{\tt \small mjd\_quatIntegrate}(v, h, D_q, D_v, D_h)` computes the Jacobians of the output :math:`q` with respect
to the inputs. Below, :math:`\bar q` denotes the pre-modified quaternion:

.. math::
   \begin{aligned}
      D_q &= \partial q / \partial \bar q \\
      D_v &= \partial q / \partial v \\
      D_h &= \partial q / \partial h
   \end{aligned}

Note that derivatives depend only on :math:`h` and :math:`v` (in fact, on :math:`s = h v`).
All outputs are optional.

*Nullable:* ``Dquat``, ``Dvel``, ``Dscale``

.. _Plugins-api:

Plugins
^^^^^^^
.. _mjp_defaultPlugin:

`mjp_defaultPlugin <#mjp_defaultPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_defaultPlugin

Set default plugin definition.

.. _mjp_registerPlugin:

`mjp_registerPlugin <#mjp_registerPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_registerPlugin

Globally register a plugin. This function is thread-safe.

If an identical mjpPlugin is already registered, this function does nothing.

If a non-identical mjpPlugin with the same name is already registered, an mju_error is raised.

Two mjpPlugins are considered identical if all member function pointers and numbers are equal,
and the name and attribute strings are all identical, however the char pointers to the strings
need not be the same.

.. _mjp_pluginCount:

`mjp_pluginCount <#mjp_pluginCount>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_pluginCount

Return the number of globally registered plugins.

.. _mjp_getPlugin:

`mjp_getPlugin <#mjp_getPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_getPlugin

Look up a plugin by name. If slot is not NULL, also write its registered slot number into it.

.. _mjp_getPluginAtSlot:

`mjp_getPluginAtSlot <#mjp_getPluginAtSlot>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_getPluginAtSlot

Look up a plugin by the registered slot number that was returned by mjp_registerPlugin.

.. _mjp_defaultResourceProvider:

`mjp_defaultResourceProvider <#mjp_defaultResourceProvider>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_defaultResourceProvider

Set default resource provider definition.

.. _mjp_registerResourceProvider:

`mjp_registerResourceProvider <#mjp_registerResourceProvider>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_registerResourceProvider

Globally register a resource provider in a thread-safe manner. The provider must have a prefix
that is not a sub-prefix or super-prefix of any current registered providers.

Return a slot number >= 0 on success, -1 on failure.

.. _mjp_resourceProviderCount:

`mjp_resourceProviderCount <#mjp_resourceProviderCount>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_resourceProviderCount

Return the number of globally registered resource providers.

.. _mjp_getResourceProvider:

`mjp_getResourceProvider <#mjp_getResourceProvider>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_getResourceProvider

Return the resource provider with the prefix that matches against the resource name.

If no match, return NULL.

.. _mjp_getResourceProviderAtSlot:

`mjp_getResourceProviderAtSlot <#mjp_getResourceProviderAtSlot>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_getResourceProviderAtSlot

Look up a resource provider by slot number returned by mjp_registerResourceProvider.

If invalid slot number, return NULL.

.. _mjp_registerDecoder:

`mjp_registerDecoder <#mjp_registerDecoder>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_registerDecoder

Globally register a decoder. This function is thread-safe.

If an identical mjpDecoder is already registered, this function does nothing.

If a non-identical mjpDecoder with the same name is already registered, an mju_error is raised.

.. _mjp_defaultDecoder:

`mjp_defaultDecoder <#mjp_defaultDecoder>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_defaultDecoder

Set default resource decoder definition.

.. _mjp_findDecoder:

`mjp_findDecoder <#mjp_findDecoder>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjp_findDecoder

Return the resource provider with the prefix that matches against the resource name.

If no match, return NULL.

.. _Thread:

Threads
^^^^^^^
.. _mju_threadPoolCreate:

`mju_threadPoolCreate <#mju_threadPoolCreate>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_threadPoolCreate

Create a thread pool with the specified number of threads running.

.. _mju_bindThreadPool:

`mju_bindThreadPool <#mju_bindThreadPool>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_bindThreadPool

Adds a thread pool to mjData and configures it for multi-threaded use.

.. _mju_threadPoolEnqueue:

`mju_threadPoolEnqueue <#mju_threadPoolEnqueue>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_threadPoolEnqueue

Enqueue a task in a thread pool.

.. _mju_threadPoolDestroy:

`mju_threadPoolDestroy <#mju_threadPoolDestroy>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_threadPoolDestroy

Destroy a thread pool.

.. _mju_defaultTask:

`mju_defaultTask <#mju_defaultTask>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_defaultTask

Initialize an mjTask.

.. _mju_taskJoin:

`mju_taskJoin <#mju_taskJoin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_taskJoin

Wait for a task to complete.

.. _Standardmath:

Standard math
^^^^^^^^^^^^^

The "functions" in this section are preprocessor macros replaced with the corresponding C standard library math
functions. When MuJoCo is compiled with single precision (which is not currently available to the public, but we
sometimes use it internally) these macros are replaced with the corresponding single-precision functions (not shown
here). So one can think of them as having inputs and outputs of type mjtNum, where mjtNum is defined as double or float
depending on how MuJoCo is compiled. We will not document these functions here; see the C standard library
specification.

mju_sqrt
~~~~~~~~

.. code-block:: C

   #define mju_sqrt    sqrt

mju_exp
~~~~~~~

.. code-block:: C

   #define mju_exp     exp

mju_sin
~~~~~~~

.. code-block:: C

   #define mju_sin     sin

mju_cos
~~~~~~~

.. code-block:: C

   #define mju_cos     cos

mju_tan
~~~~~~~

.. code-block:: C

   #define mju_tan     tan

mju_asin
~~~~~~~~

.. code-block:: C

   #define mju_asin    asin

mju_acos
~~~~~~~~

.. code-block:: C

   #define mju_acos    acos

mju_atan2
~~~~~~~~~

.. code-block:: C

   #define mju_atan2   atan2

mju_tanh
~~~~~~~~

.. code-block:: C

   #define mju_tanh    tanh

mju_pow
~~~~~~~

.. code-block:: C

   #define mju_pow     pow

mju_abs
~~~~~~~

.. code-block:: C

   #define mju_abs     fabs

mju_log
~~~~~~~

.. code-block:: C

   #define mju_log     log

mju_log10
~~~~~~~~~

.. code-block:: C

   #define mju_log10   log10

mju_floor
~~~~~~~~~

.. code-block:: C

   #define mju_floor   floor

mju_ceil
~~~~~~~~

.. code-block:: C

   #define mju_ceil    ceil

.. _Vectormath:

Vector math
^^^^^^^^^^^

.. _mju_zero3:

`mju_zero3 <#mju_zero3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_zero3

Set res = 0.

.. _mju_copy3:

`mju_copy3 <#mju_copy3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_copy3

Set res = vec.

.. _mju_scl3:

`mju_scl3 <#mju_scl3>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_scl3

Set res = vec*scl.

.. _mju_add3:

`mju_add3 <#mju_add3>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_add3

Set res = vec1 + vec2.

.. _mju_sub3:

`mju_sub3 <#mju_sub3>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sub3

Set res = vec1 - vec2.

.. _mju_addTo3:

`mju_addTo3 <#mju_addTo3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addTo3

Set res = res + vec.

.. _mju_subFrom3:

`mju_subFrom3 <#mju_subFrom3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_subFrom3

Set res = res - vec.

.. _mju_addToScl3:

`mju_addToScl3 <#mju_addToScl3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addToScl3

Set res = res + vec*scl.

.. _mju_addScl3:

`mju_addScl3 <#mju_addScl3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addScl3

Set res = vec1 + vec2*scl.

.. _mju_normalize3:

`mju_normalize3 <#mju_normalize3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_normalize3

Normalize vector; return length before normalization.

.. _mju_norm3:

`mju_norm3 <#mju_norm3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_norm3

Return vector length (without normalizing the vector).

.. _mju_dot3:

`mju_dot3 <#mju_dot3>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_dot3

Return dot-product of vec1 and vec2.

.. _mju_dist3:

`mju_dist3 <#mju_dist3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_dist3

Return Cartesian distance between 3D vectors pos1 and pos2.

.. _mju_mulMatVec3:

`mju_mulMatVec3 <#mju_mulMatVec3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatVec3

Multiply 3-by-3 matrix by vector: res = mat * vec.

.. _mju_mulMatTVec3:

`mju_mulMatTVec3 <#mju_mulMatTVec3>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatTVec3

Multiply transposed 3-by-3 matrix by vector: res = mat' * vec.

.. _mju_cross:

`mju_cross <#mju_cross>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cross

Compute cross-product: res = cross(a, b).

.. _mju_zero4:

`mju_zero4 <#mju_zero4>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_zero4

Set res = 0.

.. _mju_unit4:

`mju_unit4 <#mju_unit4>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_unit4

Set res = (1,0,0,0).

.. _mju_copy4:

`mju_copy4 <#mju_copy4>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_copy4

Set res = vec.

.. _mju_normalize4:

`mju_normalize4 <#mju_normalize4>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_normalize4

Normalize vector; return length before normalization.

.. _mju_zero:

`mju_zero <#mju_zero>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_zero

Set res = 0.

.. _mju_fill:

`mju_fill <#mju_fill>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_fill

Set res = val.

.. _mju_copy:

`mju_copy <#mju_copy>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_copy

Set res = vec.

.. _mju_sum:

`mju_sum <#mju_sum>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sum

Return sum(vec).

.. _mju_L1:

`mju_L1 <#mju_L1>`__
~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_L1

Return L1 norm: sum(abs(vec)).

.. _mju_scl:

`mju_scl <#mju_scl>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_scl

Set res = vec*scl.

.. _mju_add:

`mju_add <#mju_add>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_add

Set res = vec1 + vec2.

.. _mju_sub:

`mju_sub <#mju_sub>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sub

Set res = vec1 - vec2.

.. _mju_addTo:

`mju_addTo <#mju_addTo>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addTo

Set res = res + vec.

.. _mju_subFrom:

`mju_subFrom <#mju_subFrom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_subFrom

Set res = res - vec.

.. _mju_addToScl:

`mju_addToScl <#mju_addToScl>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addToScl

Set res = res + vec*scl.

.. _mju_addScl:

`mju_addScl <#mju_addScl>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_addScl

Set res = vec1 + vec2*scl.

.. _mju_normalize:

`mju_normalize <#mju_normalize>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_normalize

Normalize vector; return length before normalization.

.. _mju_norm:

`mju_norm <#mju_norm>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_norm

Return vector length (without normalizing vector).

.. _mju_dot:

`mju_dot <#mju_dot>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_dot

Return dot-product of vec1 and vec2.

.. _mju_mulMatVec:

`mju_mulMatVec <#mju_mulMatVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatVec

Multiply matrix and vector: res = mat * vec.

.. _mju_mulMatTVec:

`mju_mulMatTVec <#mju_mulMatTVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatTVec

Multiply transposed matrix and vector: res = mat' * vec.

.. _mju_mulVecMatVec:

`mju_mulVecMatVec <#mju_mulVecMatVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulVecMatVec

Multiply square matrix with vectors on both sides: return vec1' * mat * vec2.

.. _mju_transpose:

`mju_transpose <#mju_transpose>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_transpose

Transpose matrix: res = mat'.

.. _mju_symmetrize:

`mju_symmetrize <#mju_symmetrize>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_symmetrize

Symmetrize square matrix :math:`R = \frac{1}{2}(M + M^T)`.

.. _mju_eye:

`mju_eye <#mju_eye>`__
~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_eye

Set mat to the identity matrix.

.. _mju_mulMatMat:

`mju_mulMatMat <#mju_mulMatMat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatMat

Multiply matrices: res = mat1 * mat2.

.. _mju_mulMatMatT:

`mju_mulMatMatT <#mju_mulMatMatT>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatMatT

Multiply matrices, second argument transposed: res = mat1 * mat2'.

.. _mju_mulMatTMat:

`mju_mulMatTMat <#mju_mulMatTMat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulMatTMat

Multiply matrices, first argument transposed: res = mat1' * mat2.

.. _mju_sqrMatTD:

`mju_sqrMatTD <#mju_sqrMatTD>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sqrMatTD

Set res = mat' * diag * mat if diag is not NULL, and res = mat' * mat otherwise.

.. _mju_transformSpatial:

`mju_transformSpatial <#mju_transformSpatial>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_transformSpatial

Coordinate transform of 6D motion or force vector in rotation:translation format.
rotnew2old is 3-by-3, NULL means no rotation; flg_force specifies force or motion type.

*Nullable:* ``rotnew2old``

.. _Sparsemath:

Sparse math
^^^^^^^^^^^
.. _mju_dense2sparse:

`mju_dense2sparse <#mju_dense2sparse>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_dense2sparse

Convert matrix from dense to sparse.
 nnz is size of res and colind; return 1 if too small, 0 otherwise.

.. _mju_sparse2dense:

`mju_sparse2dense <#mju_sparse2dense>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_sparse2dense

Convert matrix from sparse to dense.

.. _Quaternions:

Quaternions
^^^^^^^^^^^

.. _mju_rotVecQuat:

`mju_rotVecQuat <#mju_rotVecQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_rotVecQuat

Rotate vector by quaternion.

.. _mju_negQuat:

`mju_negQuat <#mju_negQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_negQuat

Conjugate quaternion, corresponding to opposite rotation.

.. _mju_mulQuat:

`mju_mulQuat <#mju_mulQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulQuat

Multiply quaternions.

.. _mju_mulQuatAxis:

`mju_mulQuatAxis <#mju_mulQuatAxis>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulQuatAxis

Multiply quaternion and axis.

.. _mju_axisAngle2Quat:

`mju_axisAngle2Quat <#mju_axisAngle2Quat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_axisAngle2Quat

Convert axisAngle to quaternion.

.. _mju_quat2Vel:

`mju_quat2Vel <#mju_quat2Vel>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_quat2Vel

Convert quaternion (corresponding to orientation difference) to 3D velocity.

.. _mju_subQuat:

`mju_subQuat <#mju_subQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_subQuat

Subtract quaternions, express as 3D velocity: qb*quat(res) = qa.

.. _mju_quat2Mat:

`mju_quat2Mat <#mju_quat2Mat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_quat2Mat

Convert quaternion to 3D rotation matrix.

.. _mju_mat2Quat:

`mju_mat2Quat <#mju_mat2Quat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mat2Quat

Convert 3D rotation matrix to quaternion.

.. _mju_derivQuat:

`mju_derivQuat <#mju_derivQuat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_derivQuat

Compute time-derivative of quaternion, given 3D rotational velocity.

.. _mju_quatIntegrate:

`mju_quatIntegrate <#mju_quatIntegrate>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_quatIntegrate

Integrate quaternion given 3D angular velocity.

.. _mju_quatZ2Vec:

`mju_quatZ2Vec <#mju_quatZ2Vec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_quatZ2Vec

Construct quaternion performing rotation from z-axis to given vector.

.. _mju_mat2Rot:

`mju_mat2Rot <#mju_mat2Rot>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mat2Rot

Extract 3D rotation from an arbitrary 3x3 matrix by refining the input quaternion.

Return the number of iterations required to converge.

.. _mju_euler2Quat:

`mju_euler2Quat <#mju_euler2Quat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_euler2Quat

Convert sequence of Euler angles (radians) to quaternion.
seq[0,1,2] must be in 'xyzXYZ', lower/upper-case mean intrinsic/extrinsic rotations.

.. _Poses:

Poses
^^^^^

.. _mju_mulPose:

`mju_mulPose <#mju_mulPose>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_mulPose

Multiply two poses.

.. _mju_negPose:

`mju_negPose <#mju_negPose>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_negPose

Conjugate pose, corresponding to the opposite spatial transformation.

.. _mju_trnVecPose:

`mju_trnVecPose <#mju_trnVecPose>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_trnVecPose

Transform vector by pose.

.. _Decompositions:

Decompositions / Solvers
^^^^^^^^^^^^^^^^^^^^^^^^

.. _mju_cholFactor:

`mju_cholFactor <#mju_cholFactor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cholFactor

Cholesky decomposition: mat = L*L'; return rank, decomposition performed in-place into mat.

.. _mju_cholSolve:

`mju_cholSolve <#mju_cholSolve>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cholSolve

Solve (mat*mat') * res = vec, where mat is a Cholesky factor.

.. _mju_cholUpdate:

`mju_cholUpdate <#mju_cholUpdate>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cholUpdate

Cholesky rank-one update: L*L' +/- x*x'; return rank.

.. _mju_cholFactorBand:

`mju_cholFactorBand <#mju_cholFactorBand>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cholFactorBand

Band-dense Cholesky decomposition.
|br| Add ``diagadd + diagmul*mat_ii`` to diagonal before decomposition.
|br| Returns the minimum value of the factorized diagonal or 0 if rank-deficient.

   **Symmetric band-dense matrices**

   :ref:`mju_cholFactorBand` and subsequent functions containing the substring "band" operate on matrices which are a
   generalization of symmetric `band matrices <https://en.wikipedia.org/wiki/Band_matrix>`_. *Symmetric band-dense* or
   "arrowhead" matrices have non-zeros along proximal diagonal bands and dense blocks on the bottom rows and right
   columns. These matrices have the property that Cholesky factorization creates no fill-in and can therefore be
   performed efficiently in-place. Matrix structure is defined by three integers:

   - ``ntotal``: the number of rows (columns) of the symmetric matrix.
   - ``nband``: the number of bands under (over) the diagonal, inclusive of the diagonal.
   - ``ndense``: the number of dense rows (columns) at the bottom (right).

   The non-zeros are stored in memory as two contiguous row-major blocks, colored green and blue in the illustration
   below. The first block has size ``nband x (ntotal-ndense)`` and contains the diagonal and the bands below it. The
   second block has size ``ndense x ntotal`` and contains the dense part. Total required memory is the sum of the block
   sizes.

   .. figure:: /images/APIreference/arrowhead.svg
      :width: 750px
      :align: left

   For example, consider an arrowhead matrix with ``nband = 3``, ``ndense = 2`` and ``ntotal = 8``. In this example, the
   total memory required is ``3*(8-2) + 2*8 = 34`` mjtNum's, laid out as follows:

   .. code-block::

      0   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


   The diagonal elements are ``2, 5, 8, 11, 14, 17, 24, 33``.
   |br| Elements ``0, 1, 3, 25`` are present in memory but never touched.

.. _mju_cholSolveBand:

`mju_cholSolveBand <#mju_cholSolveBand>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_cholSolveBand

Solve (mat*mat')*res = vec where mat is a band-dense Cholesky factor.

.. _mju_band2Dense:

`mju_band2Dense <#mju_band2Dense>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_band2Dense

Convert banded matrix to dense matrix, fill upper triangle if flg_sym>0.

.. _mju_dense2Band:

`mju_dense2Band <#mju_dense2Band>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_dense2Band

Convert dense matrix to banded matrix.

.. _mju_bandMulMatVec:

`mju_bandMulMatVec <#mju_bandMulMatVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_bandMulMatVec

Multiply band-diagonal matrix with nvec vectors, include upper triangle if flg_sym>0.

.. _mju_bandDiag:

`mju_bandDiag <#mju_bandDiag>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_bandDiag

Address of diagonal element i in band-dense matrix representation.

.. _mju_eig3:

`mju_eig3 <#mju_eig3>`__
~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_eig3

Eigenvalue decomposition of symmetric 3x3 matrix, mat = eigvec * diag(eigval) * eigvec'.

.. _mju_boxQP:

`mju_boxQP <#mju_boxQP>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_boxQP

Minimize :math:`\tfrac{1}{2} x^T H x + x^T g \quad \text{s.t.} \quad l \le x \le u`, return rank or -1 if failed.

inputs:
  ``n``           - problem dimension

  ``H``           - SPD matrix                ``n*n``

  ``g``           - bias vector               ``n``

  ``lower``       - lower bounds              ``n``

  ``upper``       - upper bounds              ``n``

  ``res``         - solution warmstart        ``n``

return value:
  ``nfree <= n``  - rank of unconstrained subspace, -1 if failure

outputs (required):
  ``res``         - solution                  ``n``

  ``R``           - subspace Cholesky factor  ``nfree*nfree``,    allocated: ``n*(n+7)``

outputs (optional):
  ``index``       - set of free dimensions    ``nfree``,          allocated: ``n``

notes:
  The initial value of ``res`` is used to warmstart the solver.
  ``R`` must have allocated size ``n*(n+7)``, but only ``nfree*nfree`` values are used as output.
  ``index`` (if given) must have allocated size ``n``, but only ``nfree`` values are used as output.
  The convenience function :ref:`mju_boxQPmalloc` allocates the required data structures.
  Only the lower triangles of H and R are read from and written to, respectively.

.. _mju_boxQPmalloc:

`mju_boxQPmalloc <#mju_boxQPmalloc>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mju_boxQPmalloc

Allocate heap memory for box-constrained Quadratic Program.
As in :ref:`mju_boxQP`, ``index``, ``lower``, and ``upper`` are optional.
Free all pointers with ``mju_free()``.

.. _Attachment:

Attachment
^^^^^^^^^^
.. _mjs_attach:

`mjs_attach <#mjs_attach>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_attach

Attach child to a parent; return the attached element if success or NULL otherwise.

.. _AddTreeElements:

Tree elements
^^^^^^^^^^^^^
.. _mjs_addBody:

`mjs_addBody <#mjs_addBody>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addBody

Add child body to body; return child.

*Nullable:* ``def``

.. _mjs_addSite:

`mjs_addSite <#mjs_addSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addSite

Add site to body; return site spec.

*Nullable:* ``def``

.. _mjs_addJoint:

`mjs_addJoint <#mjs_addJoint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addJoint

Add joint to body.

*Nullable:* ``def``

.. _mjs_addFreeJoint:

`mjs_addFreeJoint <#mjs_addFreeJoint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addFreeJoint

Add freejoint to body.

.. _mjs_addGeom:

`mjs_addGeom <#mjs_addGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addGeom

Add geom to body.

*Nullable:* ``def``

.. _mjs_addCamera:

`mjs_addCamera <#mjs_addCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addCamera

Add camera to body.

*Nullable:* ``def``

.. _mjs_addLight:

`mjs_addLight <#mjs_addLight>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addLight

Add light to body.

*Nullable:* ``def``

.. _mjs_addFrame:

`mjs_addFrame <#mjs_addFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addFrame

Add frame to body.

.. _mjs_delete:

`mjs_delete <#mjs_delete>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_delete

Remove object corresponding to the given element; return 0 on success.

.. _AddNonTreeElements:

Non-tree elements
^^^^^^^^^^^^^^^^^
.. _mjs_addActuator:

`mjs_addActuator <#mjs_addActuator>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addActuator

Add actuator.

*Nullable:* ``def``

.. _mjs_addSensor:

`mjs_addSensor <#mjs_addSensor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addSensor

Add sensor.

.. _mjs_addFlex:

`mjs_addFlex <#mjs_addFlex>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addFlex

Add flex.

.. _mjs_addPair:

`mjs_addPair <#mjs_addPair>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addPair

Add contact pair.

*Nullable:* ``def``

.. _mjs_addExclude:

`mjs_addExclude <#mjs_addExclude>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addExclude

Add excluded body pair.

.. _mjs_addEquality:

`mjs_addEquality <#mjs_addEquality>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addEquality

Add equality.

*Nullable:* ``def``

.. _mjs_addTendon:

`mjs_addTendon <#mjs_addTendon>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addTendon

Add tendon.

*Nullable:* ``def``

.. _mjs_wrapSite:

`mjs_wrapSite <#mjs_wrapSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_wrapSite

Wrap site using tendon.

.. _mjs_wrapGeom:

`mjs_wrapGeom <#mjs_wrapGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_wrapGeom

Wrap geom using tendon.

.. _mjs_wrapJoint:

`mjs_wrapJoint <#mjs_wrapJoint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_wrapJoint

Wrap joint using tendon.

.. _mjs_wrapPulley:

`mjs_wrapPulley <#mjs_wrapPulley>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_wrapPulley

Wrap pulley using tendon.

.. _mjs_addNumeric:

`mjs_addNumeric <#mjs_addNumeric>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addNumeric

Add numeric.

.. _mjs_addText:

`mjs_addText <#mjs_addText>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addText

Add text.

.. _mjs_addTuple:

`mjs_addTuple <#mjs_addTuple>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addTuple

Add tuple.

.. _mjs_addKey:

`mjs_addKey <#mjs_addKey>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addKey

Add keyframe.

.. _mjs_addPlugin:

`mjs_addPlugin <#mjs_addPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addPlugin

Add plugin.

.. _mjs_addDefault:

`mjs_addDefault <#mjs_addDefault>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addDefault

Add default.

*Nullable:* ``parent``

.. _AddAssets:

Assets
^^^^^^
.. _mjs_addMesh:

`mjs_addMesh <#mjs_addMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addMesh

Add mesh.

*Nullable:* ``def``

.. _mjs_addHField:

`mjs_addHField <#mjs_addHField>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addHField

Add height field.

.. _mjs_addSkin:

`mjs_addSkin <#mjs_addSkin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addSkin

Add skin.

.. _mjs_addTexture:

`mjs_addTexture <#mjs_addTexture>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addTexture

Add texture.

.. _mjs_addMaterial:

`mjs_addMaterial <#mjs_addMaterial>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_addMaterial

Add material.

*Nullable:* ``def``

.. _mjs_makeMesh:

`mjs_makeMesh <#mjs_makeMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_makeMesh

Sets the vertices and normals of a mesh.

.. _FindAndGetUtilities:

Find and get utilities
^^^^^^^^^^^^^^^^^^^^^^
.. _mjs_getSpec:

`mjs_getSpec <#mjs_getSpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getSpec

Get spec from body.

.. _mjs_findSpec:

`mjs_findSpec <#mjs_findSpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findSpec

Find spec (model asset) by name.

.. _mjs_findBody:

`mjs_findBody <#mjs_findBody>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findBody

Find body in spec by name.

.. _mjs_findElement:

`mjs_findElement <#mjs_findElement>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findElement

Find element in spec by name.

.. _mjs_findChild:

`mjs_findChild <#mjs_findChild>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findChild

Find child body by name.

.. _mjs_getParent:

`mjs_getParent <#mjs_getParent>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getParent

Get parent body.

.. _mjs_getFrame:

`mjs_getFrame <#mjs_getFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getFrame

Get parent frame.

.. _mjs_findFrame:

`mjs_findFrame <#mjs_findFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findFrame

Find frame by name.

.. _mjs_getDefault:

`mjs_getDefault <#mjs_getDefault>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getDefault

Get default corresponding to an element.

.. _mjs_findDefault:

`mjs_findDefault <#mjs_findDefault>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_findDefault

Find default in model by class name.

.. _mjs_getSpecDefault:

`mjs_getSpecDefault <#mjs_getSpecDefault>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getSpecDefault

Get global default from model.

.. _mjs_getId:

`mjs_getId <#mjs_getId>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getId

Get element id.

.. _mjs_firstChild:

`mjs_firstChild <#mjs_firstChild>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_firstChild

Return body's first child of given type. If recurse is nonzero, also search the body's subtree.

.. _mjs_nextChild:

`mjs_nextChild <#mjs_nextChild>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_nextChild

Return body's next child of the same type; return NULL if child is last.

If recurse is nonzero, also search the body's subtree.

.. _mjs_firstElement:

`mjs_firstElement <#mjs_firstElement>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_firstElement

Return spec's first element of selected type.

.. _mjs_nextElement:

`mjs_nextElement <#mjs_nextElement>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_nextElement

Return spec's next element; return NULL if element is last.

.. _mjs_getWrapTarget:

`mjs_getWrapTarget <#mjs_getWrapTarget>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrapTarget

Get wrapped element in tendon path.

.. _mjs_getWrapSideSite:

`mjs_getWrapSideSite <#mjs_getWrapSideSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrapSideSite

Get wrapped element side site in tendon path if it has one, nullptr otherwise.

.. _mjs_getWrapDivisor:

`mjs_getWrapDivisor <#mjs_getWrapDivisor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrapDivisor

Get divisor of mjsWrap wrapping a puller.

.. _mjs_getWrapCoef:

`mjs_getWrapCoef <#mjs_getWrapCoef>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrapCoef

Get coefficient of mjsWrap wrapping a joint.

.. _AttributeSetters:

Attribute setters
^^^^^^^^^^^^^^^^^
.. _mjs_setName:

`mjs_setName <#mjs_setName>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setName

Set element's name; return 0 on success.

.. _mjs_setBuffer:

`mjs_setBuffer <#mjs_setBuffer>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setBuffer

Copy buffer.

.. _mjs_setString:

`mjs_setString <#mjs_setString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setString

Copy text to string.

.. _mjs_setStringVec:

`mjs_setStringVec <#mjs_setStringVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setStringVec

Split text to entries and copy to string vector.

.. _mjs_setInStringVec:

`mjs_setInStringVec <#mjs_setInStringVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setInStringVec

Set entry in string vector.

.. _mjs_appendString:

`mjs_appendString <#mjs_appendString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_appendString

Append text entry to string vector.

.. _mjs_setInt:

`mjs_setInt <#mjs_setInt>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setInt

Copy int array to vector.

.. _mjs_appendIntVec:

`mjs_appendIntVec <#mjs_appendIntVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_appendIntVec

Append int array to vector of arrays.

.. _mjs_setFloat:

`mjs_setFloat <#mjs_setFloat>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setFloat

Copy float array to vector.

.. _mjs_appendFloatVec:

`mjs_appendFloatVec <#mjs_appendFloatVec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_appendFloatVec

Append float array to vector of arrays.

.. _mjs_setDouble:

`mjs_setDouble <#mjs_setDouble>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setDouble

Copy double array to vector.

.. _mjs_setPluginAttributes:

`mjs_setPluginAttributes <#mjs_setPluginAttributes>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setPluginAttributes

Set plugin attributes.

.. _AttributeGetters:

Attribute getters
^^^^^^^^^^^^^^^^^
.. _mjs_getName:

`mjs_getName <#mjs_getName>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getName

Get element's name.

.. _mjs_getString:

`mjs_getString <#mjs_getString>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getString

Get string contents.

.. _mjs_getDouble:

`mjs_getDouble <#mjs_getDouble>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getDouble

Get double array contents and optionally its size.

*Nullable:* ``size``

.. _mjs_getWrapNum:

`mjs_getWrapNum <#mjs_getWrapNum>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrapNum

Get number of elements a tendon wraps.

.. _mjs_getWrap:

`mjs_getWrap <#mjs_getWrap>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getWrap

Get mjsWrap element at position i in the tendon path.

.. _mjs_getPluginAttributes:

`mjs_getPluginAttributes <#mjs_getPluginAttributes>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getPluginAttributes

Get plugin attributes.

.. _SpecUtilities:

Spec utilities
^^^^^^^^^^^^^^
.. _mjs_setDefault:

`mjs_setDefault <#mjs_setDefault>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setDefault

Set element's default.

.. _mjs_setFrame:

`mjs_setFrame <#mjs_setFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setFrame

Set element's enclosing frame; return 0 on success.

.. _mjs_resolveOrientation:

`mjs_resolveOrientation <#mjs_resolveOrientation>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_resolveOrientation

Resolve alternative orientations to quat; return error if any.

.. _mjs_bodyToFrame:

`mjs_bodyToFrame <#mjs_bodyToFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_bodyToFrame

Transform body into a frame.

.. _mjs_setUserValue:

`mjs_setUserValue <#mjs_setUserValue>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setUserValue

Set user payload, overriding the existing value for the specified key if present.

.. _mjs_setUserValueWithCleanup:

`mjs_setUserValueWithCleanup <#mjs_setUserValueWithCleanup>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_setUserValueWithCleanup

Set user payload, overriding the existing value for the specified key if
present. This version differs from mjs_setUserValue in that it takes a
cleanup function that will be called when the user payload is deleted.

.. _mjs_getUserValue:

`mjs_getUserValue <#mjs_getUserValue>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_getUserValue

Return user payload or NULL if none found.

.. _mjs_deleteUserValue:

`mjs_deleteUserValue <#mjs_deleteUserValue>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_deleteUserValue

Delete user payload.

.. _mjs_sensorDim:

`mjs_sensorDim <#mjs_sensorDim>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_sensorDim

Return sensor dimension.

.. _ElementInitialization:

Element initialization
^^^^^^^^^^^^^^^^^^^^^^
.. _mjs_defaultSpec:

`mjs_defaultSpec <#mjs_defaultSpec>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultSpec

Default spec attributes.

.. _mjs_defaultOrientation:

`mjs_defaultOrientation <#mjs_defaultOrientation>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultOrientation

Default orientation attributes.

.. _mjs_defaultBody:

`mjs_defaultBody <#mjs_defaultBody>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultBody

Default body attributes.

.. _mjs_defaultFrame:

`mjs_defaultFrame <#mjs_defaultFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultFrame

Default frame attributes.

.. _mjs_defaultJoint:

`mjs_defaultJoint <#mjs_defaultJoint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultJoint

Default joint attributes.

.. _mjs_defaultGeom:

`mjs_defaultGeom <#mjs_defaultGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultGeom

Default geom attributes.

.. _mjs_defaultSite:

`mjs_defaultSite <#mjs_defaultSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultSite

Default site attributes.

.. _mjs_defaultCamera:

`mjs_defaultCamera <#mjs_defaultCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultCamera

Default camera attributes.

.. _mjs_defaultLight:

`mjs_defaultLight <#mjs_defaultLight>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultLight

Default light attributes.

.. _mjs_defaultFlex:

`mjs_defaultFlex <#mjs_defaultFlex>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultFlex

Default flex attributes.

.. _mjs_defaultMesh:

`mjs_defaultMesh <#mjs_defaultMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultMesh

Default mesh attributes.

.. _mjs_defaultHField:

`mjs_defaultHField <#mjs_defaultHField>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultHField

Default height field attributes.

.. _mjs_defaultSkin:

`mjs_defaultSkin <#mjs_defaultSkin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultSkin

Default skin attributes.

.. _mjs_defaultTexture:

`mjs_defaultTexture <#mjs_defaultTexture>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultTexture

Default texture attributes.

.. _mjs_defaultMaterial:

`mjs_defaultMaterial <#mjs_defaultMaterial>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultMaterial

Default material attributes.

.. _mjs_defaultPair:

`mjs_defaultPair <#mjs_defaultPair>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultPair

Default pair attributes.

.. _mjs_defaultEquality:

`mjs_defaultEquality <#mjs_defaultEquality>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultEquality

Default equality attributes.

.. _mjs_defaultTendon:

`mjs_defaultTendon <#mjs_defaultTendon>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultTendon

Default tendon attributes.

.. _mjs_defaultActuator:

`mjs_defaultActuator <#mjs_defaultActuator>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultActuator

Default actuator attributes.

.. _mjs_defaultSensor:

`mjs_defaultSensor <#mjs_defaultSensor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultSensor

Default sensor attributes.

.. _mjs_defaultNumeric:

`mjs_defaultNumeric <#mjs_defaultNumeric>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultNumeric

Default numeric attributes.

.. _mjs_defaultText:

`mjs_defaultText <#mjs_defaultText>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultText

Default text attributes.

.. _mjs_defaultTuple:

`mjs_defaultTuple <#mjs_defaultTuple>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultTuple

Default tuple attributes.

.. _mjs_defaultKey:

`mjs_defaultKey <#mjs_defaultKey>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultKey

Default keyframe attributes.

.. _mjs_defaultPlugin:

`mjs_defaultPlugin <#mjs_defaultPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_defaultPlugin

Default plugin attributes.

.. _ElementCasting:

Element casting
^^^^^^^^^^^^^^^
.. _mjs_asBody:

`mjs_asBody <#mjs_asBody>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asBody

Safely cast an element as mjsBody, or return NULL if the element is not an mjsBody.

.. _mjs_asGeom:

`mjs_asGeom <#mjs_asGeom>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asGeom

Safely cast an element as mjsGeom, or return NULL if the element is not an mjsGeom.

.. _mjs_asJoint:

`mjs_asJoint <#mjs_asJoint>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asJoint

Safely cast an element as mjsJoint, or return NULL if the element is not an mjsJoint.

.. _mjs_asSite:

`mjs_asSite <#mjs_asSite>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asSite

Safely cast an element as mjsSite, or return NULL if the element is not an mjsSite.

.. _mjs_asCamera:

`mjs_asCamera <#mjs_asCamera>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asCamera

Safely cast an element as mjsCamera, or return NULL if the element is not an mjsCamera.

.. _mjs_asLight:

`mjs_asLight <#mjs_asLight>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asLight

Safely cast an element as mjsLight, or return NULL if the element is not an mjsLight.

.. _mjs_asFrame:

`mjs_asFrame <#mjs_asFrame>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asFrame

Safely cast an element as mjsFrame, or return NULL if the element is not an mjsFrame.

.. _mjs_asActuator:

`mjs_asActuator <#mjs_asActuator>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asActuator

Safely cast an element as mjsActuator, or return NULL if the element is not an mjsActuator.

.. _mjs_asSensor:

`mjs_asSensor <#mjs_asSensor>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asSensor

Safely cast an element as mjsSensor, or return NULL if the element is not an mjsSensor.

.. _mjs_asFlex:

`mjs_asFlex <#mjs_asFlex>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asFlex

Safely cast an element as mjsFlex, or return NULL if the element is not an mjsFlex.

.. _mjs_asPair:

`mjs_asPair <#mjs_asPair>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asPair

Safely cast an element as mjsPair, or return NULL if the element is not an mjsPair.

.. _mjs_asEquality:

`mjs_asEquality <#mjs_asEquality>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asEquality

Safely cast an element as mjsEquality, or return NULL if the element is not an mjsEquality.

.. _mjs_asExclude:

`mjs_asExclude <#mjs_asExclude>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asExclude

Safely cast an element as mjsExclude, or return NULL if the element is not an mjsExclude.

.. _mjs_asTendon:

`mjs_asTendon <#mjs_asTendon>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asTendon

Safely cast an element as mjsTendon, or return NULL if the element is not an mjsTendon.

.. _mjs_asNumeric:

`mjs_asNumeric <#mjs_asNumeric>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asNumeric

Safely cast an element as mjsNumeric, or return NULL if the element is not an mjsNumeric.

.. _mjs_asText:

`mjs_asText <#mjs_asText>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asText

Safely cast an element as mjsText, or return NULL if the element is not an mjsText.

.. _mjs_asTuple:

`mjs_asTuple <#mjs_asTuple>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asTuple

Safely cast an element as mjsTuple, or return NULL if the element is not an mjsTuple.

.. _mjs_asKey:

`mjs_asKey <#mjs_asKey>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asKey

Safely cast an element as mjsKey, or return NULL if the element is not an mjsKey.

.. _mjs_asMesh:

`mjs_asMesh <#mjs_asMesh>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asMesh

Safely cast an element as mjsMesh, or return NULL if the element is not an mjsMesh.

.. _mjs_asHField:

`mjs_asHField <#mjs_asHField>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asHField

Safely cast an element as mjsHField, or return NULL if the element is not an mjsHField.

.. _mjs_asSkin:

`mjs_asSkin <#mjs_asSkin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asSkin

Safely cast an element as mjsSkin, or return NULL if the element is not an mjsSkin.

.. _mjs_asTexture:

`mjs_asTexture <#mjs_asTexture>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asTexture

Safely cast an element as mjsTexture, or return NULL if the element is not an mjsTexture.

.. _mjs_asMaterial:

`mjs_asMaterial <#mjs_asMaterial>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asMaterial

Safely cast an element as mjsMaterial, or return NULL if the element is not an mjsMaterial.

.. _mjs_asPlugin:

`mjs_asPlugin <#mjs_asPlugin>`__
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. mujoco-include:: mjs_asPlugin

Safely cast an element as mjsPlugin, or return NULL if the element is not an mjsPlugin.

