### Minimal MJWarp Simulation Example
Source: https://mujoco.readthedocs.io/en/latest/mjwarp/index.html
This example demonstrates a basic simulation setup in MJWarp, initializing a model and data, setting initial velocities, and running the simulation.
```python
# Throw a ball at 100 different velocities.
import mujoco
import mujoco_warp as mjw
import warp as wp
_MJCF=r"""
"
mjm = mujoco.MjModel.from_xml_string(_MJCF)
m = mjw.put_model(mjm)
d = mjw.make_data(mjm, nworld=100)
# initialize velocities
wp.copy(d.qvel, wp.array([[float(i) / 100, 0, 0, 0, 0, 0] for i in range(100)], dtype=float))
# simulate physics
mjw.step(m, d)
print(f'qpos:\n{d.qpos.numpy()}')
```
--------------------------------
### Run MuJoCo Simulate Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/index.rst.txt
Execute the precompiled MuJoCo simulate executable with a sample model. This command verifies the simulator installation and basic functionality.
```text
Windows: simulate ..\model\humanoid\humanoid.xml
Linux and macOS: ./simulate ../model/humanoid/humanoid.xml
```
--------------------------------
### Minimal MJWarp Simulation Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/mjwarp/index.rst.txt
This example demonstrates a basic simulation setup in MJWarp, including model loading, data creation for multiple worlds, initializing velocities, and performing a simulation step. It's useful for understanding the core workflow.
```python
# Throw a ball at 100 different velocities.
import mujoco
import mujoco_warp as mjw
import warp as wp
_MJCF=r"""
"
mjm = mujoco.MjModel.from_xml_string(_MJCF)
m = mjw.put_model(mjm)
d = mjw.make_data(mjm, nworld=100)
# initialize velocities
wp.copy(d.qvel, wp.array([[float(i) / 100, 0, 0, 0, 0, 0] for i in range(100)], dtype=float)))
# simulate physics
mjw.step(m, d)
print(f'qpos:\n{d.qpos.numpy()}')
```
--------------------------------
### Example Record Command
Source: https://mujoco.readthedocs.io/en/latest/programming/samples.html
An example of how to run the record sample to create a 5-second animation at 60 frames per second, saving the output to rgb.out.
```bash
record humanoid.xml 5 60 rgb.out
```
--------------------------------
### Install mujoco-mjx
Source: https://mujoco.readthedocs.io/en/latest/mjx.html
Install the MuJoCo XLA package via PyPI. This is the recommended installation method.
```bash
pip install mujoco-mjx
```
--------------------------------
### Install mujoco-warp from source
Source: https://mujoco.readthedocs.io/en/latest/_sources/mjwarp/index.rst.txt
Clone the repository and install dependencies to build mujoco-warp from source.
```shell
git clone https://github.com/google-deepmind/mujoco_warp.git
cd mujoco_warp
uv sync --all-extras
```
--------------------------------
### Minimal MuJoCo Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
A basic example demonstrating how to load an XML model, create a data instance, run the simulation, and print geom positions. Ensure the 'gizmo.stl' asset is correctly placed at '/path/to/gizmo.stl'.
```python
import mujoco
XML=r"""
"
ASSETS=dict()
with open('/path/to/gizmo.stl', 'rb') as f:
ASSETS['gizmo.stl'] = f.read()
model = mujoco.MjModel.from_xml_string(XML, ASSETS)
data = mujoco.MjData(model)
while data.time < 1:
mujoco.mj_step(model, data)
print(data.geom_xpos)
```
--------------------------------
### Install mujoco-warp from Source
Source: https://mujoco.readthedocs.io/en/latest/mjwarp/index.html
Clone the repository and install mujoco-warp from source. This is useful for development or if you need the latest changes.
```bash
git clone https://github.com/google-deepmind/mujoco_warp.git
cd mujoco_warp
uv sync --all-extras
```
--------------------------------
### Install MuJoCo
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/index.rst.txt
Install the built MuJoCo files to the specified installation directory.
```shell
cmake --install .
```
--------------------------------
### MuJoCo Basic Simulation Setup (C)
Source: https://mujoco.readthedocs.io/en/latest/_sources/overview.rst.txt
This C code snippet demonstrates the basic setup for simulating a MuJoCo model without rendering. It includes the necessary headers and initializes the mjModel and mjData structures.
```c
#include "mujoco.h"
#include "stdio.h"
char error[1000];
mjModel* m;
mjData* d;
```
--------------------------------
### Minimal MuJoCo Viewer Launch Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
A basic example demonstrating how to launch the MuJoCo viewer, step the physics, and modify viewer options within a time limit. The viewer is automatically closed upon exiting the context manager.
```python
import time
import mujoco
import mujoco.viewer
m = mujoco.MjModel.from_xml_path('/path/to/mjcf.xml')
d = mujoco.MjData(m)
with mujoco.viewer.launch_passive(m, d) as viewer:
# Close the viewer automatically after 30 wall-seconds.
start = time.time()
while viewer.is_running() and time.time() - start < 30:
step_start = time.time()
# mj_step can be replaced with code that also evaluates
# a policy and applies a control signal before stepping the physics.
mujoco.mj_step(m, d)
# Example modification of a viewer option: toggle contact points every two seconds.
with viewer.lock():
viewer.opt.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = int(d.time % 2)
```
--------------------------------
### Minimal MuJoCo XLA (MJX) Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/mjx.rst.txt
A minimal example demonstrating how to use MJX to simulate throwing a ball at different velocities. It involves setting up a model, creating data on device, and stepping the simulation using JAX's vmap and jit for batched and compiled execution.
```python
# Throw a ball at 100 different velocities.
import jax
import mujoco
from mujoco import mjx
XML=r"""
"""
model = mujoco.MjModel.from_xml_string(XML)
mjx_model = mjx.put_model(model)
@jax.vmap
def batched_step(vel):
mjx_data = mjx.make_data(mjx_model)
qvel = mjx_data.qvel.at[0].set(vel)
mjx_data = mjx_data.replace(qvel=qvel)
pos = mjx.step(mjx_model, mjx_data).qpos[0]
return pos
vel = jax.numpy.arange(0.0, 1.0, 0.01)
pos = jax.jit(batched_step)(vel)
print(pos)
```
--------------------------------
### Minimal MuJoCo XLA (MJX) Example
Source: https://mujoco.readthedocs.io/en/latest/mjx.html
A minimal example demonstrating how to use MJX to simulate throwing a ball at different velocities. It shows model loading, data creation, and simulation stepping using JAX.
```python
# Throw a ball at 100 different velocities.
import jax
import mujoco
from mujoco import mjx
XML=r"""
"
model = mujoco.MjModel.from_xml_string(XML)
mjx_model = mjx.put_model(model)
@jax.vmap
def batched_step(vel):
mjx_data = mjx.make_data(mjx_model)
qvel = mjx_data.qvel.at[0].set(vel)
mjx_data = mjx_data.replace(qvel=qvel)
pos = mjx.step(mjx_model, mjx_data).qpos[0]
return pos
vel = jax.numpy.arange(0.0, 1.0, 0.01)
pos = jax.jit(batched_step)(vel)
print(pos)
```
--------------------------------
### Install Mujoco with USD Exporter Dependencies
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Install the Mujoco library with optional dependencies for the USD exporter using pip. This command installs `usd-core` and `pillow`.
```shell
pip install mujoco[usd]
```
--------------------------------
### Minimal MuJoCo Simulation Example
Source: https://mujoco.readthedocs.io/en/latest/python.html
A basic example demonstrating how to load an XML model, create a simulation data object, and run a simple simulation loop, printing geom positions.
```python
import mujoco
XML=r"""
"
ASSETS=dict()
with open('/path/to/gizmo.stl', 'rb') as f:
ASSETS['gizmo.stl'] = f.read()
model = mujoco.MjModel.from_xml_string(XML, ASSETS)
data = mujoco.MjData(model)
while data.time < 1:
mujoco.mj_step(model, data)
print(data.geom_xpos)
```
--------------------------------
### Read Sensor Example Usage - C
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Example demonstrating how to read sensor data, handling cases where interpolation is required.
```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;
```
--------------------------------
### Install MuJoCo Python Bindings
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Install the MuJoCo Python bindings from the generated source distribution. Ensure MUJOCO_PATH and MUJOCO_PLUGIN_PATH environment variables are set correctly.
```shell
cd dist
MUJOCO_PATH=/PATH/TO/MUJOCO \
MUJOCO_PLUGIN_PATH=/PATH/TO/MUJOCO/PLUGIN \
pip install mujoco-x.y.z.tar.gz
```
--------------------------------
### Install mujoco-mjx with Warp support
Source: https://mujoco.readthedocs.io/en/latest/mjx.html
Install the MuJoCo XLA package with support for MuJoCo Warp, an optimized implementation for NVIDIA GPUs.
```bash
pip install mujoco-mjx[warp]
```
--------------------------------
### Basic MuJoCo MJCF Model Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/overview.rst.txt
This is a simple example of a MuJoCo MJCF file defining a world with a plane, a light, and a floating box. It serves as a basic introduction to the MJCF format.
```xml
```
--------------------------------
### Get Wrap Divisor
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Retrieves the divisor value for a mjsWrap that is wrapping a puller. This is relevant for calculating forces in complex tendon setups.
```c
double mjs_getWrapDivisor(mjsWrap* wrap);
```
--------------------------------
### Sphere Bouncing on Plane with Restitution
Source: https://mujoco.readthedocs.io/en/latest/_sources/modeling.rst.txt
Example XML configuration for a sphere bouncing on a plane with a restitution coefficient of 1. This setup uses solref to achieve near-perfect energy preservation during contact.
```xml
```
--------------------------------
### Named Access for MuJoCo Geometries
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Accessing MuJoCo model and data fields using object names instead of IDs. This example shows how to get the RGBA color and ID of a geom named 'gizmo'.
```python
m.geom('gizmo').rgba
```
```python
m.geom('gizmo').id
```
```python
m.geom(i).name
```
--------------------------------
### Initialize Default Abstract Scene
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Sets up an abstract scene with default properties.
```c
void mjv_defaultScene(mjvScene* scn);
```
--------------------------------
### Install MuJoCo XLA (MJX)
Source: https://mujoco.readthedocs.io/en/latest/_sources/mjx.rst.txt
Install the MJX package using pip. To use MuJoCo Warp with MJX, install with the 'warp' extra.
```shell
pip install mujoco-mjx
```
```shell
pip install mujoco-mjx[warp]
```
--------------------------------
### Install MuJoCo Python Package
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Install the MuJoCo Python package using pip. This command installs the package and includes a copy of the MuJoCo library.
```shell
pip install mujoco
```
--------------------------------
### Render Context Camera Configuration in XML
Source: https://mujoco.readthedocs.io/en/latest/mjwarp/index.html
Example of configuring camera parameters within an XML file for a render context.
```xml
```
--------------------------------
### Install mujoco-warp from PyPI
Source: https://mujoco.readthedocs.io/en/latest/_sources/mjwarp/index.rst.txt
Use this command to install the mujoco-warp package using pip.
```shell
pip install mujoco-warp
```
--------------------------------
### Install mujoco-warp via Pip
Source: https://mujoco.readthedocs.io/en/latest/mjwarp/index.html
Install the mujoco-warp package using pip. This is the recommended method for most users.
```bash
pip install mujoco-warp
```
--------------------------------
### Enable USD Support with Pre-built Library
Source: https://mujoco.readthedocs.io/en/latest/OpenUSD/building.html
Configure MuJoCo's build system to include USD support when using a pre-built USD library. You must also provide the path to your USD installation using the pxr_DIR flag.
```bash
cd ~/mujoco
cmake -Bbuild -S. -DMUJOCO_WITH_USD=True -Dpxr_DIR=/path/to/my_usd_install_dir
cmake --build build -j 64
```
--------------------------------
### Warm-starting Optimization
Source: https://mujoco.readthedocs.io/en/latest/_modules/mujoco/mjx/_src/solver.html
Implements warm-starting for optimization by comparing the cost of a warm-started solution with a newly smoothed solution. Uses JAX's `where` for conditional selection.
```python
# warmstart:
qacc = d.qacc_smooth
if not m.opt.disableflags & DisableBit.WARMSTART:
warm = Context.create(m, d.replace(qacc=d.qacc_warmstart), grad=False)
smth = Context.create(m, d.replace(qacc=d.qacc_smooth), grad=False)
qacc = jp.where(warm.cost < smth.cost, d.qacc_warmstart, d.qacc_smooth)
d = d.replace(qacc=qacc)
```
--------------------------------
### Verify MuJoCo Installation
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Verify that the MuJoCo Python bindings have been successfully installed by attempting to import the mujoco package in Python.
```python
import mujoco
```
--------------------------------
### Run MuJoCo with USD Support
Source: https://mujoco.readthedocs.io/en/latest/OpenUSD/building.html
After successfully building MuJoCo with USD support, you can run the `simulate` executable to enable drag-and-drop functionality for USD files.
```bash
simulate
```
--------------------------------
### Check if WARP is installed
Source: https://mujoco.readthedocs.io/en/latest/_modules/mujoco/mjx/_src/io.html
Raises a RuntimeError if the WARP language implementation is not installed, as it's required for the WARP backend of MJX.
```python
def _check_warp_installed():
if not mjxw.WARP_INSTALLED:
raise RuntimeError(
'warp-lang is not installed. Cannot use WARP implementation of MJX.'
)
```
--------------------------------
### Basic USD Exporter Usage
Source: https://mujoco.readthedocs.io/en/latest/python.html
Demonstrates initializing the USDExporter, stepping through a simulation, updating the scene with new frames, and saving the final USD file. Ensure optional dependencies are installed before use.
```python
import mujoco
from mujoco.usd import exporter
m = mujoco.MjModel.from_xml_path('/path/to/mjcf.xml')
d = mujoco.MjData(m)
# Create the USDExporter
exp = exporter.USDExporter(model=m)
duration = 5
framerate = 60
while d.time < duration:
# Step the physics
mujoco.mj_step(m, d)
if exp.frame_count < d.time * framerate:
# Update the USD with a new frame
exp.update_scene(data=d)
# Export the USD file
exp.save_scene(filetype="usd")
```
--------------------------------
### Initialize Default OpenGL Context
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Sets up an OpenGL rendering context with default properties.
```c
void mjr_defaultContext(mjrContext* con);
```
--------------------------------
### Save MjSpec to XML string example
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
An example of the XML output generated by the to_xml() method, showing a basic Mujoco model structure.
```xml
```
--------------------------------
### Launch interactive MuJoCo simulator
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/samples.rst.txt
The simulate code sample provides a fully-featured interactive simulator. It opens an OpenGL window using GLFW for rendering, includes built-in help, simulation statistics, a profiler, and sensor data plots. Models can be loaded via command-line argument or drag-and-drop.
```C++
#include
#include "mujoco/mujoco.h"
#include
#include
// MuJoCo data structures
mjModel *m = NULL;
mujoco::simulation::State *state = NULL;
// forward declarations
void load_model(const char* filename);
void close_mujoco();
int main(int argc, const char** argv) {
// activate software based on your system
mj_activate("mjkey.txt");
// load model
if (argc > 1) {
load_model(argv[1]);
} else {
// load default model if no argument provided
load_model("humanoid.xml");
}
// init GLFW
if (!glfwInit())
mjtError("Could not initialize GLFW");
// create window, make context current, set vsync
GLFWwindow* window = glfwCreateWindow(1000, 800, "MuJoCo", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// install GLFW mouse and keyboard callbacks
glfwSetMouseButtonCallback(window, mjv_default_mouse_button);
glfwSetCursorPosCallback(window, mjv_default_mouse_move);
glfwSetKeyCallback(window, mjv_default_keyboard);
// initialize visualization data structures
mjvScene scene;
mjvOption options;
mjvPerturb perturb;
mjvCamera cam;
mjv_default_scene(m, &scene);
mjv_default_option(&options);
mjv_default_camera(m, &cam);
mjv_default_perturb(&perturb);
// create visualization
mjv_make_scene(m, 1000, &options, &scene);
mjv_update_camera(m, &cam, &perturb, &scene);
// run while window is not closed
while (!glfwWindowShouldClose(window)) {
// advance simulation and re-render window
mjtNum simstart = mjtNum();
while (mjtNum() < simstart + 0.016) {
mj_step(m, state->data());
}
mjv_render_scene(window, m, state->data(), &options, &scene, &cam);
// poll for events
glfwPollEvents();
}
// free visualization data structures
mjv_free_scene(&scene);
// close MuJoCo
close_mujoco();
// terminate GLFW
glfwTerminate();
return 0;
}
void load_model(const char* filename) {
char error[1000] = {0};
char warning[1000] = {0};
// load model and assign it to the global variable m
m = mj_loadXML(filename, NULL, error, warning);
if (error[0])
mjtError("Could not load model | %s\n", error);
if (warning[0])
printf("Warning: %s\n", warning);
// allocate model data and assign it to the global variable state
state = new mujoco::simulation::State(m);
}
void close_mujoco() {
// free model data
delete state;
state = NULL;
// free model
mj_deleteModel(m);
m = NULL;
}
```
--------------------------------
### Get and Set Simulation State
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Manage the simulation state using provided methods. These methods allow for getting, setting, and handling flattened state representations.
```python
state = sim.get_state()
sim.set_state(state)
sim.set_state_from_flattened(state)
```
--------------------------------
### Build MuJoCo Documentation
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/index.rst.txt
Steps to build the MuJoCo documentation locally, including installing dependencies and generating HTML output.
```shell
pip install -r requirements.txt
```
```shell
make html
```
--------------------------------
### Convert Raw Data to Video with ffmpeg
Source: https://mujoco.readthedocs.io/en/latest/programming/samples.html
Demonstrates how to use ffmpeg to convert the raw RGB output file generated by the record sample into a playable MP4 video file. Ensure the video_size matches the offscreen rendering resolution specified in the MuJoCo model.
```bash
ffmpeg -f rawvideo -pixel_format rgb24 -video_size 2560x1440 \
-framerate 60 -i rgb.out -vf "vflip,format=yuv420p" video.mp4
```
--------------------------------
### MJCF Default Settings Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/modeling.rst.txt
Demonstrates the use of default classes and child classes to set rgba values for geoms. Note that this example is for illustrative purposes and may not compile directly.
```xml
```
--------------------------------
### Basic Interactive MuJoCo Simulator
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/samples.rst.txt
A minimal interactive simulator that takes a model file as a command-line argument. It opens an OpenGL window, renders the simulation at 60 fps, and advances the simulation in real-time. Use Backspace to reset. Mouse controls camera rotation, translation, and zoom.
```C
#include
#include
#include
char error[1024] = {
0
};
// model and data
mjModel *m = NULL;
pjData *d = NULL;
// user API for rendering
void render(void) {
// set camera
mjv_defaultCamera(m, d);
// add offscreen camera
mjvCamera cam;
mjv_defaultCamera(m, &cam);
cam.distance = 1.5;
// set camera
mjv_setCamera(m, d, &cam);
// set scene
mjvScene sc;
mjv_defaultScene(m, &sc);
mjv_addCamera(m, &sc, &cam);
// add geom
mjv_defaultOption(m, &sc.opt);
mjv_defaultLight(m, &sc.light);
// render scene
mjr_render(0, &sc, &m->vis, &m->opt, d, NULL, 0, 0, 0, 0);
}
// main
int main(int argc, const char **argv) {
// check command-line arguments
if (argc < 2) {
printf("Usage: basic modelfile\n");
return 0;
}
// init MuJoCo
mj_activate(NULL);
// load model
m = mj_loadXML(argv[1], NULL, error);
if (m == NULL) {
printf("Load model error: %s\n", error);
return 1;
}
// make data
d = mj_makeData(m);
// init GLFW
if (!glfwInit())
mjtNmError("Could not initialize GLFW");
// create window
GLFWwindow *window = glfwCreateWindow(1200, 800, "MuJoCo", NULL, NULL);
glfwMakeContextCurrent(window);
// init rendering
mjr_defaultContext();
// run main loop
while (!glfwWindowShouldClose(window)) {
// advance simulation
mj_step(m, d);
// render
render();
// swap buffers
glfwSwapBuffers(window);
// poll events
glfwPollEvents();
}
// terminate MuJoCo
mj_deleteData(d);
mj_deleteModel(m);
mj_deactivate();
// terminate GLFW
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
```
--------------------------------
### Record Sample Command Line
Source: https://mujoco.readthedocs.io/en/latest/programming/samples.html
Specifies the command-line arguments for the record sample. Required arguments include the model file path, duration, frames per second, and output RGB file path. An optional argument can enable depth image overlay.
```bash
record modelfile duration fps rgbfile [adddepth]
```
--------------------------------
### Initialize Plugin Library with GCC/MSVC
Source: https://mujoco.readthedocs.io/en/latest/programming/extension.html
Use the mjPLUGIN_LIB_INIT macro to ensure plugins are registered when a library is loaded. This macro adapts to GCC-compatible compilers and MSVC.
```c
#define mjPLUGIN_LIB_INIT \
__attribute__((constructor)) void mj_plugin_lib_init() { mjp_registerPlugin(&plugin); }
```
--------------------------------
### Basic MuJoCo Simulation in C
Source: https://mujoco.readthedocs.io/en/latest/index.html
Loads an MJCF model, simulates it for 10 seconds, and then cleans up resources. This demonstrates the core C API for running passive dynamics.
```c
#include "mujoco.h"
#include "stdio.h"
char error[1000];
mjModel* m;
mjData* d;
int main(void) {
// load model from file and check for errors
m = mj_loadXML("hello.xml", NULL, error, 1000);
if (!m) {
printf("%s\n", error);
return 1;
}
// make data corresponding to model
d = mj_makeData(m);
// run simulation for 10 seconds
while (d->time < 10)
mj_step(m, d);
// free model and data
mj_deleteData(d);
mj_deleteModel(m);
return 0;
}
```
--------------------------------
### Get Sensor Dimension
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Returns the dimension of a given sensor.
```c
int mjs_sensorDim(const mjsSensor* sensor);
```
--------------------------------
### Initialize Plugin Library
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIglobals.html
Use this macro to register a plugin before `main()` is called. It requires a unique identifier `n` to prevent naming conflicts between different plugin initialization functions.
```c
#define mjPLUGIN_LIB_INIT(n) \
static void _mj_init_##n(void) __attribute__((constructor)); \
static void _mj_init_##n(void)
```
--------------------------------
### USD Exporter Basic Usage
Source: https://mujoco.readthedocs.io/en/latest/_sources/python.rst.txt
Demonstrates the basic workflow of initializing the USDExporter, stepping through a simulation, updating the scene, and finally saving the USD file.
```APIDOC
## Basic Usage of USDExporter
### Description
This example shows how to initialize the `USDExporter`, simulate a model, update the USD scene with simulation data at each frame, and export the final USD file.
### Method
Python script
### Endpoint
N/A
### Parameters
N/A
### Request Example
```python
import mujoco
from mujoco.usd import exporter
m = mujoco.MjModel.from_xml_path('/path/to/mjcf.xml')
d = mujoco.MjData(m)
# Create the USDExporter
exp = exporter.USDExporter(model=m)
duration = 5
framerate = 60
while d.time < duration:
# Step the physics
mujoco.mj_step(m, d)
if exp.frame_count < d.time * framerate:
# Update the USD with a new frame
exp.update_scene(data=d)
# Export the USD file
exp.save_scene(filetype="usd")
```
### Response
N/A
### Response Example
N/A
```
--------------------------------
### Get Plugin Count
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Returns the number of globally registered plugins.
```c
int mjp_pluginCount(void);
```
--------------------------------
### Open Resource - C
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Opens a resource. If the name lacks a prefix matching a registered provider, the OS filesystem is used. Handles potential errors via the `error` buffer.
```c
mjResource* mju_openResource(const char* dir, const char* name,
const mjVFS* vfs, char* error, size_t nerror);
```
--------------------------------
### Get State
Source: https://mujoco.readthedocs.io/en/latest/_modules/mujoco/mjx/_src/io.html
Retrieves state components from mjx.Data, equivalent to mujoco.mj_getState.
```APIDOC
## get_state
### Description
Gets state from mjx.Data. This is equivalent to `mujoco.mj_getState`.
### Arguments
- **m** (types.Model) - model describing the simulation
- **d** (types.Data) - data for the simulation
- **spec** (Union[int, mujoco.mjtState]) - int bitmask or mjtState enum specifying which state components to include
### Returns
- jax.Array - a flat array of state values
```
--------------------------------
### Matrix Representation Example
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/simulation.rst.txt
Illustrates the row-major format for a 2x3 matrix in MuJoCo.
```Text
a0 a1 a2
a3 a4 a5
```
--------------------------------
### Get Plugin by Slot Number
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Looks up a plugin by its registered slot number.
```c
const mjpPlugin* mjp_getPluginAtSlot(int slot);
```
--------------------------------
### MuJoCo Application Structure with GLFW
Source: https://mujoco.readthedocs.io/en/latest/_sources/programming/visualization.rst.txt
Illustrates the basic structure of a MuJoCo application that combines simulation and rendering using GLFW. It covers initialization of MuJoCo data structures, GLFW window setup, visualization context creation, the main rendering loop, and cleanup.
```C
// MuJoCo data structures
mjModel* m = NULL; // MuJoCo model
mjData* d = NULL; // MuJoCo data
mjvCamera cam; // abstract camera
mjvOption opt; // visualization options
mjvScene scn; // abstract scene
mjrContext con; // custom GPU context
// ... load model and data
// init GLFW, create window, make OpenGL context current, request v-sync
glfwInit();
GLFWwindow* window = glfwCreateWindow(1200, 900, "Demo", NULL, NULL);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// initialize visualization data structures
mjv_defaultCamera(&cam);
mjv_defaultPerturb(&pert);
mjv_defaultOption(&opt);
mjr_defaultContext(&con);
// create scene and context
mjv_makeScene(m, &scn, 1000);
mjr_makeContext(m, &con, mjFONTSCALE_100);
// ... install GLFW keyboard and mouse callbacks
// run main loop, target real-time simulation and 60 fps rendering
while( !glfwWindowShouldClose(window) ) {
// advance interactive simulation for 1/60 sec
// Assuming MuJoCo can simulate faster than real-time, which it usually can,
// this loop will finish on time for the next frame to be rendered at 60 fps.
// Otherwise add a cpu timer and exit this loop when it is time to render.
mjtNum simstart = d->time;
while( d->time - simstart < 1.0/60.0 )
mj_step(m, d);
// get framebuffer viewport
mjrRect viewport = {0, 0, 0, 0};
glfwGetFramebufferSize(window, &viewport.width, &viewport.height);
// update scene and render
mjv_updateScene(m, d, &opt, NULL, &cam, mjCAT_ALL, &scn);
mjr_render(viewport, &scn, &con);
// swap OpenGL buffers (blocking call due to v-sync)
glfwSwapBuffers(window);
// process pending GUI events, call GLFW callbacks
glfwPollEvents();
}
// close GLFW, free visualization storage
glfwTerminate();
mjv_freeScene(&scn);
mjr_freeContext(&con);
// ... free MuJoCo model and data
```
--------------------------------
### Get Frame from Element
Source: https://mujoco.readthedocs.io/en/latest/APIreference/APIfunctions.html
Retrieves the frame associated with an element. Requires an mjElement pointer.
```c
mjsFrame* mjs_getFrame(mjsElement* element);
```