Mujoco C++ example: List all bodies
This simple example shows how to load a MuJoCo model from an XML file and list all bodies in the model along with their IDs.
#include <mujoco/mujoco.h>
#include <cstdio>
int main(int argc, char** argv) {
// Check args
if (argc < 2) {
printf("Usage: %s model.xml\n", argv[0]);
return 1;
}
// Load model
char error[1000] = "Could not load binary model";
mjModel* m = mj_loadXML(argv[1], nullptr, error, 1000);
if (!m) {
printf("%s\n", error);
return 1;
}
// Create data
mjData* d = mj_makeData(m);
// Loop over all bodies
printf("Bodies in the model:\n");
for (int i = 0; i < m->nbody; i++) {
const char* name = mj_id2name(m, mjOBJ_BODY, i);
if (name)
printf(" id %d: %s\n", i, name);
else
printf(" id %d: (unnamed)\n", i);
}
// Free MuJoCo structures
mj_deleteData(d);
mj_deleteModel(m);
return 0;
}
How to compile
g++ -o list_bodies list_bodies.cpp -lmujoco -I/opt/mujoco/include -L/opt/mujoco/lib -Wl,-rpath,/opt/mujoco/lib
Usage example
./list_bodies ~/mujoco_menagerie/franka_fr3/fr3.xml
Bodies in the model:
id 0: world
id 1: base
id 2: fr3_link0
id 3: fr3_link1
id 4: fr3_link2
id 5: fr3_link3
id 6: fr3_link4
id 7: fr3_link5
id 8: fr3_link6
id 9: fr3_link7
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow