This tutorial shows how to use ERB to generate simulation world files. ERB is the commonly used templating language to generate structured text files with Ruby code. In this case, since most simulation world used in gazebo is defined with SDFormat, ERB works conveniently.
Why ERB
There are many use cases and advantages of using ERB in your SDF file. Some of them are listed below and demonstrated in this example ERB file:
- Embedding logic into the SDF, such as loops and conditionals
- Full access to Ruby's math library, for simple things like PI, to more elaborate ones like matrices and randomization
- Breaking the SDF into multiple smaller files for better organization
- Placing multiple instances of the same model into simulation world without manually copy-pasting every tag
Set up Ruby
Firstly, Ruby needs to be installed. If you have gone through Gazebo Sim's installation guide, it's most likely you already have Ruby installed. To check if Ruby is installed, use
If it is not found, run the following to install Ruby
Create an ERB template
To make a distinction between ERB templates and normal sdformat files, .erb
is commonly used as file suffix. ERB language is usually embedded in the SDF file. Below is a step-by-step tutorial to generate 1000 box shapes in a simulation world using ERB template. You can copy-and-paste the code block into an editor to try it out.
First is to create a world using SDFormat syntax. You need to specify both the xml
and sdf
versions you are using. And don't forget to give your simulation world a name.
To create 1000 instances of simple box shapes, you can use a for
loop in Ruby syntax in the ERB template. This code block can be inserted in between the <world>
tags. Note that the <model>
tags are wrapped in between the ERB template. <% end %>
is to mark the end of loops or if
statements. Each box model also has a different name and pose to ensure they show up as individuals in simulation.
Here is a complete shapes simulation world example.
Instead of simple shapes, you can also use a nested loop to generate 100 actors spaced out evenly in a simulation world.
Generate SDF from ERB template
Now that an ERB template file is ready and saved as my_first_erb.erb
, you can run the following terminal command to generate the corresponding SDF file.
Run simulation world
To test if the ERB template works, run the SDF file with the gz sim
command
If there are any errors or warnings from running the SDF file, you would need to go back to the ERB file and see if any coding mistakes were made.