Webots 8.4.0 User Guide PDF
Webots 8.4.0 User Guide PDF
release 8.4.0
Copyright
c 2016 Cyberbotics Ltd.
[Link]
March 8, 2016
2
Permission to use, copy and distribute this documentation for any purpose and without fee is
hereby granted in perpetuity, provided that no modifications are performed on this documenta-
tion.
The copyright holder makes no warranty or condition, either expressed or implied, including
but not limited to any implied warranties of merchantability and fitness for a particular purpose,
regarding this manual and the associated software. This manual is provided on an as-is basis.
Neither the copyright holder nor any applicable licensor will be liable for any incidental or con-
sequential damages.
The Webots software was initially developed at the Laboratoire de Micro-Informatique (LAMI)
of the Swiss Federal Institute of Technology, Lausanne, Switzerland (EPFL). The EPFL makes
no warranties of any kind on this software. In no event shall the EPFL be liable for incidental or
consequential damages of any kind in connection with the use and exploitation of this software.
Trademark information
AiboTM is a registered trademark of SONY Corp.
RadeonTM is a registered trademark of ATI Technologies Inc.
GeForceTM is a registered trademark of nVidia, Corp.
JavaTM is a registered trademark of Sun MicroSystems, Inc.
KheperaTM and KoalaTM are registered trademarks of K-Team S.A.
LinuxTM is a registered trademark of Linus Torvalds.
Mac OS XTM is a registered trademark of Apple Inc.
MindstormsTM and LEGOTM are registered trademarks of the LEGO group.
IPRTM is a registered trademark of Neuronics AG.
UbuntuTM is a registered trademark of Canonical Ltd.
Visual C++TM , WindowsTM , Windows NTTM , Windows 2000TM , Windows XPTM , Windows
VistaTM , Windows 7TM and Windows 8TM are registered trademarks of Microsoft Corp.
UNIXTM is a registered trademark licensed exclusively by X/Open Company, Ltd.
Foreword
3
4
Thanks
Cyberbotics is grateful to all the people who contributed to the development of Webots, Webots
sample applications, the Webots User Guide, the Webots Reference Manual, and the Webots
web site, including Stefania Pedrazzi, David Mansolino, Yvan Bourquin, Fabien Rohrer, Jean-
Christophe Fillion-Robin, Jordi Porta, Emanuele Ornella, Yuri Lopez de Meneses, Sébastien
Hugues, Auke-Jan Ispeert, Jonas Buchli, Alessandro Crespi, Ludovic Righetti, Julien Gag-
net, Lukas Hohl, Pascal Cominoli, Stéphane Mojon, Jérôme Braure, Sergei Poskriakov, An-
thony Truchet, Alcherio Martinoli, Chris Cianci, Nikolaus Correll, Jim Pugh, Yizhen Zhang,
Anne-Elisabeth Tran Qui, Grégory Mermoud, Lucien Epinet, Jean-Christophe Zufferey, Laurent
Lessieux, Aude Billiard, Ricardo Tellez, Gerald Foliot, Allen Johnson, Michael Kertesz, Simon
Garnieri, Simon Blanchoud, Manuel João Ferreira, Rui Picas, José Afonso Pires, Cristina Santos,
Michal Pytasz and many others.
Moreover, many thanks are due to Cyberbotics’s Mentors: Prof. Jean-Daniel Nicoud (LAMI-
EPFL), Dr. Francesco Mondada (EPFL), Dr. Takashi Gomi (Applied AI, Inc.).
Finally, thanks to Skye Legon and Nathan Yawn, who proofread this guide.
5
6
Contents
1 Installing Webots 21
1.1 Webots licenses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.1 Webots PRO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.2 Webots EDU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
1.1.3 Webots MOD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.1.4 Webots licences overview . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.2 System requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.3 Verifying your graphics driver installation . . . . . . . . . . . . . . . . . . . . . 23
1.3.1 Supported graphics cards . . . . . . . . . . . . . . . . . . . . . . . . . . 23
1.3.2 Unsupported graphics cards . . . . . . . . . . . . . . . . . . . . . . . . 23
1.3.3 Upgrading your graphics driver . . . . . . . . . . . . . . . . . . . . . . 24
1.3.4 Hardware acceleration tips . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.4 Installation procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.4.1 Installation on linux . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.4.2 Installation on Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 28
1.4.3 installation on Mac OS X . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.5 Webots license system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
1.5.1 Firewall configuration (optional) . . . . . . . . . . . . . . . . . . . . . . 29
1.5.2 License agreement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.5.3 License setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.5.4 License administration . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.6 Classroom license setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
1.6.1 User account . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
7
8 CONTENTS
1.6.2 Classroom . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.6.3 Homework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
1.6.4 Using Webots without Internet connection . . . . . . . . . . . . . . . . . 33
1.7 Translating Webots to your own language . . . . . . . . . . . . . . . . . . . . . 34
3.2.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
3.2.2 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
3.2.3 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
3.2.4 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
3.2.5 distance [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
3.2.6 emitter [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
3.2.7 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
3.2.8 force [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
3.2.9 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
3.2.10 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
3.2.11 light [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
3.2.12 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
3.2.13 range [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
3.3 How To . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.3.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
3.3.2 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
3.3.3 force [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
3.3.4 inverted [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
3.3.5 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
3.3.6 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
3.3.7 texture [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
3.3.8 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
3.4 Geometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
3.5 Real Robots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.5.1 aibo ers210 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
3.5.2 aibo [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
3.5.3 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
3.5.4 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.5.5 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
3.5.6 e-puck [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
3.5.7 e-puck line [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
CONTENTS 11
7 Tutorials 193
7.1 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7.1.1 Install Webots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7.1.2 Create a directory for all your Webots files . . . . . . . . . . . . . . . . 194
7.1.3 Start Webots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
7.1.4 Create a new Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
7.1.5 The Webots Graphical User Interface (GUI) . . . . . . . . . . . . . . . . 195
7.2 Tutorial 1: Your first Simulation in Webots (20 minutes) . . . . . . . . . . . . . 195
7.2.1 Create a new World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
7.2.2 Add an e-puck Robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
7.2.3 Create a new Controller . . . . . . . . . . . . . . . . . . . . . . . . . . 201
7.2.4 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.3 Tutorial 2: Modification of the Environment (20 minutes) . . . . . . . . . . . . . 203
7.3.1 A new Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.3.2 Modification of the Floor . . . . . . . . . . . . . . . . . . . . . . . . . . 203
7.3.3 The Solid Node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
7.3.4 Create a Ball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
7.3.5 Geometries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
7.3.6 DEF-USE mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
7.3.7 Add Walls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
7.3.8 Efficiency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
7.3.9 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
7.4 Tutorial 3: Appearance (15 minutes) . . . . . . . . . . . . . . . . . . . . . . . . 210
7.4.1 New simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
7.4.2 Lights . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
7.4.3 Modify the Appearance of the Walls . . . . . . . . . . . . . . . . . . . . 211
7.4.4 Add a Texture to the Ball . . . . . . . . . . . . . . . . . . . . . . . . . . 211
7.4.5 Rendering Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
7.4.6 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
7.5 Tutorial 4: More about Controllers (20 minutes) . . . . . . . . . . . . . . . . . . 212
7.5.1 New World and new Controller . . . . . . . . . . . . . . . . . . . . . . 213
16 CONTENTS
8 Robots 235
8.1 Using the e-puck robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
8.1.1 Overview of the robot . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
8.1.2 Simulation model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
8.1.3 Control interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
8.2 Using the Nao robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
8.2.2 Using Webots with Choregraphe . . . . . . . . . . . . . . . . . . . . . . 246
8.2.3 Nao models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
8.2.4 Using motion boxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
8.2.5 Using the cameras . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
8.2.6 Using Several Nao robots . . . . . . . . . . . . . . . . . . . . . . . . . 247
8.2.7 Getting the right speed for realistic simulation . . . . . . . . . . . . . . . 248
8.2.8 Known Problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
8.3 Using the Thymio II robot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
8.3.1 Thymio II model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249
8.3.2 Connect Aseba to the Thymio II model . . . . . . . . . . . . . . . . . . 251
8.3.3 Thymio II Pen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
8.3.4 Thymio II Ball . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
8.4 Using the Pioneer 3-AT and Pioneer 3-DX robots . . . . . . . . . . . . . . . . . 253
8.4.1 Pioneer 3-AT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
8.4.2 Pioneer 3-DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Installing Webots
This chapter explains how to install Webots and configure your license rights.
The Webots licenses comes in three different flavors, including Webots PRO, Webots EDU and
Webots MOD. They differ by the features and price. These different versions are described in
this section. The features available in the different versions are summarized in table 1.1.
Webots PRO is the most powerful version of Webots. It is designed for research and development
projects. Webots PRO includes the possibility to create supervisor processes for controlling
robotics experiments, an extended physics programming capability and a fast simulation mode
(faster than real time). A 30 day trial version of Webots PRO is available from Cyberbotics web
site.
Webots EDU is tailored for classrooms. Students learn how to model robots, create their own
environments and program the behavior of the robots, using any of the supported programming
languages. To validate their models, they can optionally transfer their control programs to real
robots. A 30 day trial version of Webots EDU is available upon request.
21
22 CHAPTER 1. INSTALLING WEBOTS
• A fairly recent PC or Macintosh computer with at least a 2 GHz dual core CPU clock speed
and 2 GB of RAM is a minimum requirement. A quad-core CPU is however recommended.
• An nVidia or AMD (formerly ATI) OpenGL (minimum version 2.1) capable graphics
adapter with at least 512 MB of RAM is required. We do not recommend any other graph-
ics adapters, including Intel graphics adapters, as they often lack a good OpenGL support
which may cause 3D rendering problems and application crashes. Nevertheless, in some
cases, the installation of the latest Intel graphics driver can fix such problems and let you
1.3. VERIFYING YOUR GRAPHICS DRIVER INSTALLATION 23
use Webots. However, we don’t provide any guarantee on this. For Linux systems, we rec-
ommend only nVidia graphics cards. Webots works well on all the graphics cards included
in fairly recent Apple computers. It is strongly advised to try the 30 day trial version of
Webots on your computer systems to ensure they are compatible before you buy.
• Linux: Webots is ensured to run on the latest Ubuntu Long Term Support (LTS) release,
currently version 14.04. But it is also known to run on most recent major Linux distribu-
tions, including RedHat, Mandrake, Debian, Gentoo, SuSE, and Slackware. We recom-
mend using a recent version of Linux. Webots is provided for Linux 64 (x86-64) systems.
Since Webots 8.1.0, the Linux 32 (i386) version is no longer provided. Webots doesn’t run
on Ubuntu version eariler than 12.04.
• Windows: Webots runs on Windows 10 64-bit, Windows 8.1 64-bit, Windows 8 64-bit and
Windows 7 64-bit. It is not supported on 32-bit versions of Windows and on old versions
including Windows Vista, XP, NT4 or 2000.
• Macintosh: Webots runs on Mac OS X 10.11 ”El Captan” and 10.10 ”Yosemite”. Webots
may work but is not officially supported on earlier versions of Mac OS X. Since version
6.3.0, Webots is compiled exclusively for Intel Macs, it does not run on old PowerPC
Macs. To use Webots on a PowerPC Mac, you need Webots 6.2.4 (or earlier), these older
versions were compiled as Universal Binary.
Other versions of Webots for other UNIX systems (Solaris, Linux PPC, Irix) may be available
upon request.
users reported success with some Intel graphics cards after installing the latest version of the
driver. Graphics drivers from Intel may be obtained from the Intel download center web site1 .
Linux graphics drivers from Intel may be obtained from the Intel Linux Graphics web site2 .
If some graphical bugs subsist, changing the ”RTT prefered mode” from the Webots OpenGL
Preferences from ”Framebuffer Object” to ”Pixelbuffer Object” or ”Direct Copy” may fix the
problems. However, this may also impact the 3D performance.
If the output contains the string ”NVIDIA”, ”ATI”, or ”Intel”, this indicates that a hardware
driver is currently installed:
$ glxinfo | grep OpenGL
OpenGL vendor string: NVIDIA Corporation
OpenGL renderer string: GeForce 8500 GT/PCI/SSE2
OpenGL version string: 3.0.0 NVIDIA 180.44
...
If you read ”Mesa”, ”Software Rasterizer” or ”GDI Generic”, this indicates that the hardware
driver is currently not installed and that your computer is currently using a slow software emula-
tion of OpenGL:
$ glxinfo | grep OpenGL
OpenGL vendor string: Mesa project: [Link]
OpenGL renderer string: Mesa GLX Indirect
OpenGL version string: 1.4 (1.5 Mesa 6.5.2)
...
Then you can normally download the appropriate driver from the graphics hardware manufac-
turer’s website: [Link] for an nVidia card or [Link] for a ATI
graphics card. Please follow the manufacturer’s instructions for the installation.
1. Right-click on My Computer.
2. Select Properties.
4. Click on the plus sign to the left of Display adapters. The name of the driver ap-
pears. Make a note of it.
5. Go to the web site of your card manufacturer: [Link] for an nVidia card
or [Link] for a ATI graphics card.
Depending on the graphics hardware, there may be a huge performance drop of the rendering
system (up to 10x) when compiz desktop effects are on. Also these visual effects may cause some
display bug where the main window of Webots is not properly refreshed. Hence, on Ubuntu (or
other Linux) we recommend to deactivate the desktop effects. You can easily disable them using
some tools like Compiz Config Settings Manager or Unity Twerk Tool.
3
[Link]
4
[Link]
5
[Link]
6
[Link]
26 CHAPTER 1. INSTALLING WEBOTS
1. Uninstall completely any old version of Webots that may have been installed on your
computer previously.
After installation, the most important Webots features will be available, but
some third party tools (such as Java, Python, or MATLABTM ) may be neces-
sary for running or compiling specific projects. The chapter 4 covers the set
up of these tools.
Some of the following commands requires the root privileges. You can get
these privileges by preceding all the commands by the sudo command.
Webots will run much faster if you install an accelerated OpenGL drivers. If
you have a nVidia or ATI graphics card, it is highly recommended that you
install the Linux graphics drivers from these manufacturers to take the full
advantage of the OpenGL hardware acceleration with Webots. Please find
instructions here section 1.3.
Webots needs the avconv program to create MPEG-4 movies, that can be
installed with libav-tools and libavcodec-extra-54 packages.
7
[Link]
1.4. INSTALLATION PROCEDURE 27
The advantage of this solution is that Webots will be updated with the system updates. This
installation requires the root privileges.
First of all, you may want to configure your apt package manager by adding this line:
deb [Link] binary-i386/
or
deb [Link] binary-amd64/
in the /etc/apt/[Link] configuration file. Then update the APT packages by using
apt-get update
Optionally, Webots can be autentified thanks to the [Link] signature file which
can be downloaded here8 , using this command:
apt-key add /path/to/[Link]
This procedure can also be done using any APT front-end tool such as the
Synaptic Package Manager. But only a command line procedure is docu-
mented here.
This section explains how to install Webots from the tarball package (having the .tar.bz2
extension). This package can be installed without the root privileges. It can be uncompressed
anywhere using the tar xjf command line. Once uncompressed, it is recommended to set
the WEBOTS HOME environment variable to point to the webots directory obtained from the
uncompression of the tarball:
tar xjf [Link].bz2
or
tar xjf [Link].bz2
and
export WEBOTS_HOME=/home/username/webots
8
[Link]
28 CHAPTER 1. INSTALLING WEBOTS
The export line should however be included in a configuration script like /etc/profile, so
that it is set properly for every session.
Some additional libraries are needed in order to properly run Webots. In particular libjpeg62,
libav-tools, libpci and libavcodec-extra-54 have to be installed on the system.
This procedure explains how to install Webots from the DEB package (having the .deb exten-
sion).
On Ubuntu, double-click on the DEB package file to open it with the Ubuntu Software Center
and click on the Install button. If a previous version of Webots is already installed, then the text
on the button could be different, like Upgrade or Reinstall.
Alternatively, the DEB package can also be installed using dpkg or gdebi with the root
privileges. For 32-bit systems:
dpkg -i webots_8.4.0_i386.deb
apt-get -f install
or
gdebi webots_8.4.0_i386.deb
or
gdebi webots_8.4.0_amd64.deb
It is possible to install Webots silently from an administrator DOS console, by typing webots-8.
4.0_setup.exe/SILENT or webots-8.4.0_setup.exe/VERYSILENT
If you observe 3D rendering anomalies or Webots crashes, it is strongly recommend to upgrade
your graphics driver.
9
[Link]
1.5. WEBOTS LICENSE SYSTEM 29
2. Double click on this file. This will mount on the desktop a volume named Webots con-
taining the Webots folder.
3. Move this folder to your /Applications folder or wherever you would like to install
Webots.
If you are using a proxy to access the Internet, Webots will retrieve your
system proxy configuration automatically.
10
[Link]
30 CHAPTER 1. INSTALLING WEBOTS
Please read your license agreement carefully before using Webots. This license is provided
within the software package. By using the software and documentation, you agree to abide by
all the provisions of this license.
A Webots license is originally associated with an e-mail address which corresponds to a user
account on Cyberbotics’s web site.
When Webots is started for the first time, a login dialog invites you to register a user account on
Cyberbotics’s web site (if not already done) and to enter the corresponding license information
to log in your Webots session.
The Synchronization field of the Webots login dialog defines how frequently
Webots checks the license server. Setting this field to a small value will cause
more networking activity, but will allow you to release the license quickly
after a crash. This will allow you in turn to restart Webots quicker on another
machine. For example, if you select 5 minutes, you may have to wait for up
to 5 minutes if you crashed Webots on a machine and want to restart it on
another.
If you are the administrator of the license, you can log into your Webots account on Cyberbotics’
web site and go to the Administration page under the My Account tab. From there, you will be
able to monitor your licenses, to purchase more licenses, to create groups of users and to grant
customized user access to your licenses.
If you need further information about license issues, please send an e-mail to:
<license@[Link]>
Internet and in particular the license server of Cyberbotics11 . If it doesn’t work, you may need to
configure your local firewall to allow Webots to access this URL.
There are two methods to handle student access to Webots licenses: a single user account, or
multiple user accounts.
The single user account method is simpler to setup as you don’t need to know the e-mail ad-
dresses of the students. Nevertheless, you need to setup an e-mail address for a generic user for
which you can read the e-mails received. It could be your own personal e-mail address. Let’s
call this e-mail address webots@[Link]. A drawback to this method is that
it allows a single student to use simultaneously several instances of your 20 licenses, possibly all
of them, thus preventing other students to use them.
1. Log in to your Webots user account using your license administration credentials, e.g., the
user account which was used to activate your Webots licenses.
2. Create a new user pack from the administration page and call it ”Students”.
4. Set the concurrency value to 20 to allow the single user account to use all the licenses
simultaneously.
7. Create this account (if needed), log in and visit the Profile page of this account. Copy the
”Alternate password for Webots 8”. This password allows students to use Webots, but not
to log in this user account. It looks like J6ebgAGRgFtkf8QHiWoHXIUnI98=.
8. Give this e-mail address and alternate password to your students to allow them to log in
Webots using your licenses (but they won’t be able to log in the web page).
11
[Link]
12
[Link]
32 CHAPTER 1. INSTALLING WEBOTS
The multiple user accounts license requires that you have the list of e-mail addresses of the
students to whom you want to grant access to your Webots licenses. You will be able to limit
the number of simultaneous instances of Webots used per student to 1, so that a single student
cannot use multiple licenses simultaneously. Hence a single student cannot prevent the others
from using Webots.
1. Log in to your Webots user account using your license administration credentials, e.g., the
user account which was used to activate your Webots licenses.
2. Create a new user pack from the administration page and call it ”Students”.
4. Set the concurrency value to 1 to prevent a single user to use multiple instances of Webots
at the same time.
5. Type (or copy/paste) the list of student e-mail addresses in the ”users:” text area.
6. Press the apply button. The e-mail addresses which are not already registered on Cy-
berbotics’ web site will receive an invitation e-mail explaining how to register a Webots
account and use the newly granted Webots licenses. For existing accounts, no e-mail is
sent and it is your responsibility to inform the students about their modified license rights.
1.6.2 Classroom
Setup
You can install Webots on all the computers in a classroom, even if you have more computers
than licenses. In our example, if you have 20 licenses and 30 computers, then 20 students could
use the software simultaneously on any of the 30 computers. If a 21rst student comes in, he
won’t be able to start Webots until one of the 20 students stops using Webots.
It is possible to restrict the use of your licenses to a specific classroom, or more generally, to
a number of specific computers. This can be achieved from the ”Module pack” section of the
administration web page: click on the license you want to restrict and a new page entitled ”Edit
module pack” should be displayed. On this page, set an IP range value to limit the use of this
pack to machines with a specific IP address. For example: ”[Link], [Link],
[Link]” will limit the use of Webots to these 3 IP addresses. It is also possible to use an
IP mask (CIDR notation) to specify a range of IP addresses. For example, ”[Link]/24,
1.6. CLASSROOM LICENSE SETUP 33
[Link]” will limit the use of Webots to any machine whose IP address starts with
128.179.67 and also to the machine whose IP address is [Link]. Machines that do
not match the values provided in the IP range field won’t be able to access the licenses.
To save the students from having to type an e-mail address and password on the first run of We-
bots, you may want to do it for them before the class starts. If you do it from the user account
they are supposed to use, this information will be saved and the students won’t need to enter it
again. You may also automate this process by copying an already configured Webots preferences
to all the user accounts used by the students. On Windows, the Webots preferences are stored in
the registry under the HKEY_CURRENT_USER/SOFTWARE/Cyberbotics key (so you need
to use a tool that copies registry keys across user accounts). On Mac OS X, the Webots prefer-
ences are stored in a file under the user home directory at ˜/Library/Preferences/com.
[Link]. On Linux, the Webots preferences are stored in a
file under the user home directory at ˜/.config/Cyberbotics/[Link].
1.6.3 Homework
If no IP restriction is set (see above), then the students will be able to use Webots anytime,
from any computer, including their own personal computers. In such a case, it’s better to use
multiple user accounts rather than a single one, to avoid that a few students use all the licenses
permanently.
It is possible to use Webots without any Internet connection for a limited amount of time. Users
who anticipate they will be away from the Internet can download a license locally on their ma-
chine for a specified lease duration. During this period of time, the license is considered to be
in use and is not available to other users. The maximum lease duration can be defined by the
administrator of the licenses in the ”Edit module pack” administration web page. It can be set
to ”None” to prevent any off-line use of Webots. Otherwise, the maximum lease value can be
chosen between 1 hour and 7 days.
In order to download a license locally for off-line use, a user should go to the Tools menu of
Webots and open the License Manager... item. A new window should pop-up to display the
available licenses. The user can then choose which licenses to download on his local computer
as well as the duration of the lease for these licenses. Warning: this operation cannot be undone.
Once transferred locally, the licenses are not available to other computers for the duration of the
lease period.
34 CHAPTER 1. INSTALLING WEBOTS
• Mobile robot prototyping (academic research, the automotive industry, aeronautics, the
vacuum cleaner industry, the toy industry, hobbyists, etc.)
35
36 CHAPTER 2. GETTING STARTED WITH WEBOTS
You will need a minimal amount of technical knowledge to develop your own simulations:
• A basic knowledge of the C, C++, Java, Python or Matlab programming language is nec-
essary to program your own robot controllers. However, even if you don’t know these
languages, you can still program the e-puck and Hemisson robots using a simple graphical
programming language called BotStudio.
• If you don’t want to use existing robot models provided within Webots and would like to
create your own robot models, or add special objects in the simulated environments, you
will need a basic knowledge of 3D computer graphics and VRML97 description language.
That will allow you to create 3D models in Webots or import them from 3D modelling
software.
1. A Webots world file (.wbt) that defines one or several robots and their environment. The
.wbt file does sometimes depend on external PROTO files (.proto) and textures.
2. One or several controller programs for the above robots (in C/C++/Java/Python/Matlab).
3. An optional physics plugin that can be used to modify Webots regular physics behavior (in
C/C++).
1
[Link]
2
[Link]
2.1. INTRODUCTION TO WEBOTS 37
A controller is a computer program that controls a robot specified in a world file. Controllers
can be written in any of the programming languages supported by Webots: C, C++, Java, Python
or MATLABTM . When a simulation starts, Webots launches the specified controllers, each as a
separate process, and it associates the controller processes with the simulated robots. Note that
several robots can use the same controller code, however a distinct process will be launched for
each robot.
Some programming languages need to be compiled (C and C++) other languages need to be
interpreted (Python and MATLABTM ) and some need to be both compiled and interpreted (Java).
For example, C and C++ controllers are compiled to platform-dependent binary executables
(for example .exe under Windows). Python and MATLABTM controllers are interpreted by the
corresponding run-time systems (which must be installed). Java controller need to be compiled
to byte code (.class files or .jar) and then interpreted by a Java Virtual Machine.
The source files and binary files of each controller are stored together in a controller directory. A
controller directory is placed in the controllers subdirectory of each Webots project.
The Supervisor is a privileged type of Robot that can execute operations that can normally only
be carried out by a human operator and not by a real robot. The Supervisor is normally associated
with a controller program that can also be written in any of the above mentioned programming
languages. However in contrast with a regular Robot controller, the Supervisor controller will
have access to privileged operations. The privileged operations include simulation control, for
example, moving the robots to a random position, making a video capture of the simulation, etc.
38 CHAPTER 2. GETTING STARTED WITH WEBOTS
2.2.1 Linux
Open a terminal and type webots to launch Webots.
2.2.2 Mac OS X
Open the directory in which you installed the Webots package and double-click on the Webots
icon.
2.2.3 Windows
On Windows 10 and Windows 7, open the Start menu, go to the Program Files > Cyberbotics
menu and click on the Webots 8.4.0 menu item.
On Windows 8, open the Start screen, scroll to the screen’s right until spotting the Cyberbotics
section and click on the Webots icon.
The optional worldfile argument specifies the name of a .wbt file to open. If it is not speci-
fied, Webots attempts to open the most recently opened file.
The --minimize option is used to minimize (iconize) Webots window on startup. This also
skips the splash screen and the eventual Welcome Dialog. This option can be used to avoid
cluttering the screen with windows when automatically launching Webots from scripts. Note
that Webots PRO does automatically enable the Fast mode when --minimize is specified.
The --mode=<mode> option can be used to start Webots in the specified simulation mode.
The four possible simulation modes are: pause, realtime, run and fast; they correspond
to the simulation control buttons of Webots’ graphical user interface. This option overrides, but
does not modify, the startup mode saved in Webots’ preferences. For example, type webots
--mode=pause [Link] to start Webots in pause mode. Note that run and fast
modes are only available in Webots PRO.
The --sysinfo option displays misc information about the current system on the standard
40 CHAPTER 2. GETTING STARTED WITH WEBOTS
For example, the following command will start Webots with the streaming server enabled on the
TCP port ’1234’: webots --start-streaming-server="port:1234"
The File menu allows you to perform usual file operations: loading, saving, etc.
The New World menu item (and button) opens a new world in the simulation window containing
only an ElevationGrid, displayed as a chessboard of 10 x 10 squares on a surface of 1 m x
1 m.
2.3. THE USER INTERFACE 41
The Open World... menu item (and button) opens a file selection dialog that allows you to
choose a .wbt file to load.
The Open Recent World menu item gives the possibility of reopening a .wbt file that was opened
recently by choosing it from the list displayed in the submenu.
The Open Sample World menu item opens a dialog listing all the available sample worlds where
it is possible to search for a specific .wbt file to load by entering the file name or part of it in
the search field.
The Save World menu item (and button) saves the current world using the current filename
(the filename that appears at the top of the main window). On each Save the content of the .wbt
file is overwritten and no backup copies are created by Webots, therefore you should use this
button carefully and eventually do safety copies manually.
The Save World As... menu item (and button) saves the current world with a new filename entered
by the user. Note that a .wbt file should always be saved in a Webots project directory, and in
the worlds subdirectory, otherwise it will not be possible to reopen the file.
The Revert World menu item (and button) reloads the current world from the saved version
and restarts the simulation from the beginning.
42 CHAPTER 2. GETTING STARTED WITH WEBOTS
When opening (or reverting) a world, if the world takes more than 2 seconds
to load a window will pop up and show the progression. Using this window
it is possible to cancel the loading of the world, in that case, the empty world
will be opened instead.
The New Text File menu item (and button) opens an empty text file in the text editor.
The Open Text File... menu item (and button) opens a file selection dialog that allows you
to choose a text file (for example a .java file) to load.
The Save Text File menu item (and button) saves the current text file.
The Save Text File As... menu item (and button) saves the current text file with a new
filename entered by the user.
The Save All Text Files menu item saves all the opened and unsaved text files.
The Revert Text File menu item (and button) reloads the text file from the saved version.
The Print Preview... menu item opens a window allowing you to manage the page layout in order
to print files from the text editor.
The Print... menu item opens a window allowing you to print the current file of the text editor.
The Import VRML 2.0... menu item adds VRML97 objects at the end of the scene tree. These
objects come from a VRML97 file you must specify. This feature is useful for importing complex
shapes that were modeled in a 3D modelling program, then exported to VRML97 (or VRML 2.0).
Most 3D modelling software, like 3D Studio Max, Maya, AutoCAD, Pro Engineer, AC3D, or Art
Of Illusion, include the VRML97 (or VRML 2.0) export feature. Be aware that Webots cannot
import files in VRML 1.0 format. Once imported, these objects appear as Group, Transform
or Shape nodes at the bottom of the scene tree. You can then either turn these objects into
Webots nodes (like Solid, DifferentialWheels, etc.) or cut and paste them into the
children list of existing Webots nodes.
The Export VRML 2.0... item allows you to save the currently loaded world as a .wrl file,
conforming to the VRML97 standard. Such a file can, in turn, be opened with any VRML97
viewer and most 3D modeling software.
The Take Screenshot... item allows you to take a screenshot of the current view in Webots.
It opens a file dialog to save the current view as a PNG or JPG image.
2.3. THE USER INTERFACE 43
The Make Movie... item allows you to create MPEG movies (Linux and Mac OS X) or AVI
movies (Windows). Once the movie recording is started, this item is changed in Stop Movie....
During the recording, it is possible to the change the running mode and pause the simulation.
However, frames are only captured during Webots steps and not when the simulation is paused.
The Export HTML5 Model... item allows you to export the current world as an interactive 3D
.html file, using the X3DOM web standard, based on WebGL. This is especially useful for
publishing Webots-created worlds on the Web. X3DOM is supported in recent versions of Fire-
fox, Chrome, Internet Explorer and Safari on Mac OS X (see details on the X3DOM web site3 ).
The Make HTML5 Animation... item allows you to record a simulation as a 3D animation and
publish it on a HTML5 web page. The result is similar to a movie with playback controls, except
that you can change the viewpoint at any time. Several files are generated: an X3D file containing
the 3D scene, a JSON file containing the animation data and a HTML5 file displaying the result
using X3DOM and jQuery. Once the animation recording is started, this item is changed to Stop
HTML5 Animation... and can be used to stop the animation recording.
The Quit Webots terminates the current simulation and closes Webots.
The Edit menu provides usual text edition functions to manipulate files opened in the Text editor,
such as Copy, Paste, Cut, etc.
The View menu allows to control the viewing in the simulation window.
The Follow Object menu item allows to switch between a fixed (static) viewpoint and a viewpoint
that follows a mobile object (usually a robot). If you want the viewpoint to follow an object, first
you need to select the object with the mouse and then check the Follow Object menu item. Note
that the Follow Object state is saved in the .wbt file.
3
[Link]
44 CHAPTER 2. GETTING STARTED WITH WEBOTS
The Restore Viewpoint item restores the viewpoint’s position and orientation to their initial set-
tings when the file was loaded or reverted. This feature is handy when you get lost while navi-
gating in the scene, and want to return to the original viewpoint.
The Fullscreen item enables and disables displaying the 3D window on the entire screen.
The Projection radio button group allows to choose between the Perspective Projection (default)
and the Orthographic Projection mode for Webots simulation window. The perspective mode
corresponds to a natural projection: in which the farther an object is from the viewer, the smaller
it appears in the image. With the orthographic projection, the distance from the viewer does
not affect how large an object appears. Furthermore, with the orthographic mode, lines which
are parallel in the model are drawn parallel on the screen, therefore this projection is sometimes
useful during the modelling phase. No shadows are rendered in the orthographic mode.
The Rendering radio button group allows to choose between the Plain Rendering (default) and
the Wireframe modes for Webots simulation window. In plain rendering mode, the objects are
rendered with their geometrical faces, materials, colors and textures, in the same way they are
usually seen by an eye or a camera. In wireframe rendering mode, only the segments of the ren-
derable primitives are rendered. This mode can be useful to debug your meshes. If the wireframe
rendering mode and the View > Optional Rendering > Show All Bounding Objects toggle button
are both activated, then only bounding objects are drawn (not the renderable primitives). This
can be used to debug a problem with the collision detection.
Finally, the Optional Rendering submenu allows to display, or to hide, supplementary informa-
tion. These rendering are displayed only in the main rendering and hide in the robot camera.
They are used to understand better the behavior of the simulation.
The Show Coordinate System allows to display, or to hide, the global coordinate system at the
bottom right corner of the 3D window as red, green and blue arrows representing the x, y and z
axes respectively.
The Show All Bounding Objects allows to display, or to hide, all the bounding objects (defined in
the boundingObject fields of every Solid node). Bounding objects are represented by white lines.
These lines turn rose when a collision occurs and blue when the solid is idle, i.e., it comes to rest
and it doesn’t interact with any other active solid.
The Show Contact Points allows to display, or to hide, the contact points generated by the colli-
sion detection engine. Contact points that do not generate a corresponding contact force are not
shown. A contact force is generated only for objects simulated with physics (Physics node
required). A step is required for taking this operation into account.
The Show Connector axes allows to display, or to hide, the connector axes. The rotation align-
ments are depicted in black while the y and z axes respectively in green and blue.
The Show Joint axes allows to display, or to hide, the joint axes. The joint axes are represented
by black lines.
The Show RangeFinder frustums allows to display, or to hide, the OpenGL culling frustum and
the recorded image for every range-finder in the scene, using a yellow wire frame. The OpenGL
2.3. THE USER INTERFACE 45
culling frustum is a truncated pyramid corresponding to the field of view of a range-finder. The
recorded image is displayed on the plane described by the frustum at a distance corresponding
to the minimum range of the range-finder from the device center. More information about this
concept is available in the OpenGL documentation.
The Show Lidar Rays Paths allows to display, or to hide, the layers (the laser ray paths) for every
lidar in the scene, using a cyan wire frame.
The Show Lidar Point Cloud allows to display, or to hide, the point cloud for every lidar enabled
in point cloud mode in the scene. The point cloud is represented by the location of the points
themselves and by the rays from the lidar origin to the points using a gradient from blue (top
layer) to red (bottom layer). This optional rendering is computationally expensive and can there-
fore significantly slow-down the simulation speed. Note that if the point cloud contains more
than 2500 points, the rays from the lidar origin to the point are not displayed.
The Show Camera frustums allows to display, or to hide, the OpenGL culling frustum and the
recorded image for every camera in the scene, using a magenta wire frame. The OpenGL culling
frustum is a truncated pyramid corresponding to the field of view of a camera. The back of
the pyramid is not represented because the far plane is set to infinity. The recorded image is
displayed on the camera’s near plane. More information about this concept is available in the
OpenGL documentation.
The Show Distance Sensor rays allows to display, or to hide, the rays casted by the distance
sensor devices. These rays are drawn as red lines (which become green beyond collision points).
Their length corresponds to the maximum range of the device.
The Show Light Sensor rays allows to display, or to hide, the rays casted by the light sensor
devices. These rays are drawn as yellow lines.
The Show Lights allows to display, or to hide, the lights (including PointLights and SpotLights).
DirectionalLights aren’t represented. PointLights and SpotLights are represented by a colored
circle surrounded by a flare.
The Show Pen Painting Rays allows to display, or to hide, the rays in which the pen devices paint.
These rays are drawn as violet lines if painting is enabled, otherwise as gray lines.
The Show Center Of Mass and Support Polygon allows to display, or to hide, both the global
center of mass of a selected solid (with non NULL Physics node) and its support polygon. By
support polygon we mean the projection of the convex hull of the solid’s contact points on the
horizontal plane which contains the lowest one. In addition, the projection of the center of mass
in the latter plane is rendered in green if it lies inside the support polygon (static equilibrium),
red otherwise. This rendering option can be activated only for solids with no other solid at their
top.
If the Disable selection option is enabled, it prevents you from changing the selected solid node
when clicking on the 3D window. This is particularly useful during the modeling phase, when
you want to change the viewpoint without modifying the visible and selected fields in the scene
tree.
46 CHAPTER 2. GETTING STARTED WITH WEBOTS
The Step menu item (and button) executes one basic time step of simulation. The duration
of this step is defined in the basicTimeStep field of the WorldInfo node, and can be
adjusted in the scene tree window to suit your needs.
The Real-time menu item (and button) runs the simulation at real-time until it is interrupted
by Pause or Step. In run mode, the 3D display of the scene is refreshed every n basic time steps,
where n is defined in the displayRefresh field of the WorldInfo node.
The Run menu item (and button) is like Real-time, except that it runs as fast as possible
(Webots PRO only).
The Fast menu item (and button) is like Run, except that no graphical rendering is per-
formed (Webots PRO only). As the graphical rendering is disabled (black screen) this allows
for a faster simulation and therefore this is well suited for cpu-intensive simulations (genetic
algorithms, vision, learning, etc.).
The RangeFinder Devices submenu contains the list of all the range-finder devices of the selected
robot and lets the user show or hide single range-finder overlay images by checking or uncheck-
ing the corresponding item. Range-finder overlays differ from the camera overlays because of
their yellow border. Note that if the Hide All RangeFinder Overlays item is checked, then the
range-finder device overlays will not be visible in the 3D view independently from the status of
RangeFinder Devices menu items. A RangeFinder Devices menu item is disabled if the overlay’s
texture is shown in an external window by double-clicking on it.
The Display Devices submenu contains the list of all the display devices of the selected robot
and lets the user show or hide single display overlay images by checking or unchecking the
corresponding item. Display overlays differ from the camera overlays because of their cyan
border. Note that if the Hide All Display Overlays item is checked, then the display device overlays
will not be visible in the 3D view independently from the status of Display Devices menu items.
A Display Devices menu item is disabled if the overlay’s texture is shown in an external window
by double-clicking on it.
On the other hand the following items are always active and apply to all the robot in the world:
The Hide All Camera Overlays option hides all the camera devices overlays in the 3D view inde-
pendently from the specific robot’s device option set in Camera Devices submenu.
The Hide All RangeFinder Overlays option hides all the camera devices overlays in the 3D view
independently from the specific robot’s device option set in RangeFinder Devices submenu.
The Hide All Display Overlays option hides all the display devices overlays in the 3D view inde-
pendently from the specific robot’s device option set in Display Devices submenu.
The License Manager... item opens the Webots License Manager window that allows you to
see which licenses are in use and optionally to transfer some license to your local computer
for off-line use. Please note that the transfer of license may be limited by your local license
administrator: It may not be possible to transfer some license to your local computer or only for
a limited duration depending on the configuration defined by your local license administrator.
Please ask your local license administrator in case of problem.
The Preferences item pops up a window described in this section.
The Wizards menu makes it easier to create new projects and new controllers.
The New Project Directory... menu item first prompts you to choose a filesystem location and
then it creates a project directory. A project directory contains several subdirectories that are
used to store the files related to a particular Webots project, i.e. world files, controller files, data
files, plugins, etc. Webots remembers the current project directory and automatically opens and
saves any type of file from the corresponding subdirectory of the current project directory.
The New Robot Controller... menu item allows you to create a new controller program. You will
first be prompted to choose between a C, C++, Java, Python or MATLABTM controller. Then,
Webots will ask you to enter the name of your controller and finally it will create all the necessary
files (including a template source code file) in your current project directory.
The New Physics Plugin... menu item will let you create a new physics plugin for your project.
Webots asks you to choose a programming language (C or C++) and a name for the new physics
plugin. Then it creates a directory, a template source code file and a Makefile in your current
project.
In the Help menu, the About... item opens the About... window that displays the license
information.
The Webots Guided Tour... menu item starts a guided tour that demonstrates Webots capabilies
through a series of examples.
The OpenGL Information... menu item gives you information about your current OpenGL hard-
ware and driver. It can be used to diagnose rendering problems.
The remaining menu items bring up various information as indicated, in the form of HTML
pages, PDF documents, etc.
2.3. THE USER INTERFACE 49
Hide/Show Scene Tree: shows or hides the Scene Tree and resizes the 3D window conse-
quently.
Add: Adds a node or an object. For nodes, this triggers a dialog that will let you choose
a node type from a list. The new node is created with default values that can be modified af-
terwards. You can only insert a node suitable for the corresponding field. The dialog also gives
the possibility to load a previously exported node by clicking on the Import... button. Further
information about how to export a node are available here.
The basic time step for simulation can be set in the basicTimeStep field of the WorldInfo
node in the scene tree window. It is expressed in virtual time milliseconds. The value of this time
step defines the length of the time step executed during the Step mode. This step is multiplied
by the displayRefresh field of the same WorldInfo node to define how frequently the
display is refreshed.
A single mouse click allows to select a solid object. The bounding object of a selected solid is
represented by white lines. These lines turn rose if the solid is colliding with another one and
blue when the solid is idle, i.e., it comes to rest and it doesn’t interact with any other active solid.
Selecting a robot enables the Show Robot Window item in the Tools menu. Double-clicking on a
solid object opens the Robot Window and if it was closed, the Scene Tree.
If an object has a solid subpart, then it is also possible to select only this subpart by clicking on
it once the whole object is already selected, or by clicking on it while holding down the Alt key.
Linux users should also hold down the Control key (Ctrl) together with the Alt key.
Dragging the mouse while pressing a mouse button moves the camera of the 3D window.
• Camera rotation: In the 3D window, press the left button and drag the mouse to select an
object and rotate the viewpoint about it. If no object is selected, the camera rotates about
the origin of the world coordinate system.
• Camera translation: In the 3D window, press the right button and drag the mouse to trans-
late the camera with the mouse motion.
2.4. THE 3D WINDOW 51
• Zooming / Camera rotation: In the 3D window, press both left and right mouse buttons
simultaneously (or just the middle button) and drag the mouse vertically, to zoom in and
out. Dragging the mouse horizontally will rotate the camera about the viewing axis. Alter-
natively, the mouse wheel alone can also be used for zooming.
If you are a Mac user with a single button mouse, hold the Alt key and press
the mouse button to translate the camera according to the mouse motion.
Hold the control key (Ctrl) down and press the mouse button to zoom / rotate
the camera with the mouse motion.
Currently Webots provides two different ways to move solid objects: axis-aligned handles and
keyboard shortcuts.
Axis-aligned handles
When a solid object is selected, some arrow-shaped handles appear in the 3D window (see figure
2.3). These handles can be used to translate and rotate the object along the corresponding axis.
For moving the object you can simply click on the handle and drag it to the desired position.
A label will show the currect relative translation or rotation during the movement, as shown in
figure 2.4.
If the Control key (Ctrl), the handles for resizing the solid object will be displayed instead of
translation and rotation handles. These resize handles can also be enabled from the Field Editor.
52 CHAPTER 2. GETTING STARTED WITH WEBOTS
Figure 2.4: Labels displaying relative translation and rotation when moving objects with handles
• Translation: To move an object parallel to the ground: hold down the shift key, press the
left mouse button and drag.
• Lift: To raise or lower and object: hold down the Shift key, press both left and right mouse
buttons (or the middle button) and drag. Alternatively, the mouse wheel combined with
the Shift key can also be used.
If you are a Mac user with a single button mouse, hold the Shift key and the
Control key (Ctrl) down and press the mouse button to rotate the selected
object according to mouse motion. Hold the Shift key and the Command key
(key with Apple symbol) down and press the mouse button to lift the selected
object according to mouse motion.
the intensity of the applied torque being directly proportional to the product of the mass by the
length of the 3D-vector.
In pause mode, you can simultaneously add a force and a torque to the same
selected solid. Camera rotation can be useful when checking wether your
force / torque vector has the desired direction.
image is created and the overlay in the 3D window is disabled. It is possible to restore the 3D
window overlay simply by closing the window.
This section describes the user interface of the Scene Tree, gives an overview of the VRML97
nodes and Webots nodes.
Nodes can be expanded with a double-click. When a field is selected, its value can be edited at
the bottom of the Scene Tree. All changes will be immediately reflected in the 3D window. The
following buttons are available int the field editor section:
We recommend to use the Scene Tree to write Webots world files. However,
because the nodes and fields are stored in a human readable form, it is also
possible to edit world files with a regular text editor. Some search and replace
operations may actually be easier that way. Please refer to Webots Reference
Manual for more info on the available nodes and the world file format.
2.6 Preferences
The Webots preferences can be modified by a dialog box which can be open from the Webots
> Preferences menu item on Mac, and from the Tools > Preferences menu item on the other
2.6. PREFERENCES 57
operating systems.
The dialog box is separated into tabs. Each of the following subsection corresponds to one of
this tab.
2.6.1 General
• The Language option allows you to choose the language of Webots user interface (restart
needed).
• The Startup mode allows you to choose the state of the simulation when Webots is started
(pause, realtime, run, fast; see the Simulation menu).
• The Editor font defines the font to be used in Webots text editor and in the Console. It is
recommended to select a fixed width font for better source code display. The default value
of this preference is ”Consolas,10” on Windows, ”Courier,14” on Mac and ”Monospace”
on linux.
• The Number of threads defines how many threads can be created by Webots at maximum.
The recommended value matches with the number of logical cores of the computer pro-
cessor. It may be interesting to reduce this value in some specific cases, for example when
another process requires intensively other cores. For now this value affects only the phys-
ical engine speed, and the controller compilation speed. Note that this is the maximum
number of threads allowed, but the actual number of threads used is the one defined in the
optimalThreadCount field of the WorldInfo node.
2.6.2 OpenGL
The OpenGL tab contains preferences about setting the 3D rendering abilities. The initial param-
eters of these settings may vary from one computer to another depending on the GPU OpenGL
abilities.
• The RTT preferred mode option allows you to modify the method used to create the Camera
device images. The methods are sorted from the most efficient one to the less efficient one.
• The Disable shadows option allows you to disable completely the shadows in the 3D view
and in the Camera rendering, whatever the values of the [Link] fields.
The global performances can be improved by disabling this feature, but on the other hand
the rendering is more difficult to understand, and less pretty.
58 CHAPTER 2. GETTING STARTED WITH WEBOTS
• The Disable shader option allows you to use the regular OpenGL shading model, instead
of a custom shading. This custom shading model computes the light effects on the 3D
objects per pixel instead of per vertex, resulting in a much smoother rendering. It may be
interesting to disbale this feature on old GPU if the shaders are not well supported.
• The Disable camera anti-aliasing option allows you to bypass all the [Link]
fields and to disable this feature. We observed that some hardware doesn’t support the
OpenGL feature about anti-aliasing when rendering into a texture (RTT).
If you write a scientific paper or describe your project involving Webots on a web page, we will
greatly appreciate if you can add a reference to Webots. For example by explicitly mentioning
Cyberbotics’ web site or by referencing a journal paper that describes Webots. To make this
simpler, we provide here some citation examples, including BibTex entries that you can use in
your own documents.
This project uses Webots4 , a commercial mobile robot simulation software developed by Cyber-
botics Ltd.
This project uses Webots ([Link] a commercial mobile robot simulation
software developed by Cyberbotics Ltd.
The BibTex reference entry may look odd, as it is very different from a standard paper citation
and we want the specified fields to appear in the normal plain citation mode of LaTeX.
@MISC{Webots,
AUTHOR = {Webots},
TITLE = {[Link]
NOTE = {Commercial Mobile Robot Simulation Software},
EDITOR = {Cyberbotics Ltd.},
URL = {[Link]
}
@ARTICLE{Webots04,
AUTHOR = {Michel, O.},
TITLE = {Webots: Professional Mobile Robot Simulation},
JOURNAL = {Journal of Advanced Robotics Systems},
YEAR = {2004},
VOLUME = {1},
NUMBER = {1},
PAGES = {39--42},
URL = {[Link]
Advanced-Robotic-Systems/Volume-1/[Link]}
}
60 CHAPTER 2. GETTING STARTED WITH WEBOTS
Chapter 3
This chapter gives an overview of sample worlds provided with the Webots package. The ex-
amples world can be tried easily; the .wbt files are located in various worlds directories
of the WEBOTS_HOME/projects directory and can be directly opened from Webots using
the Open Sample World item in File menu. The controller code is located in the corresponding
controllers directory. This chapter provides each example a with short abstract only. More
detailed explanations can be found in the source code.
3.1 Samples
This section provides a list of interesting worlds that broadly illustrate Webots capabilities. Sev-
eral of these examples have stemmed from research or teaching projects. You will find the corre-
sponding .wbt files in the WEBOTS_HOME/projects/samples/demos/worlds direc-
tory, and their controller source code in the WEBOTS_HOME/projects/samples/demos/
controllers directory. For each demo, the world file and its corresponding controller have
the same name.
61
62 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.1.2 [Link]
Keywords: Gantry robot, gripper, Hanoi towers, linear motors, recursive algorithm
In this example, a gantry robot plays ”Towers of Hanoi” by stacking three colored boxes. The
gantry robot is modeled using a combination of LinearMotor and RotationalMotor de-
vices. A recursive algorithm is used to solve the Hanoi Towers problem.
64 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.1.3 [Link]
Keywords: Legged robot, alternating tripod gait, linear motor
In this example, an insect-shaped robot is made of a combination of LinearMotor and Ro-
tationalMotor devices. The robot moves using an alternating tripod gait.
3.1. SAMPLES 65
3.1.4 [Link]
Keywords: Humanoid, QRIO robot
In this example, a humanoid robot performs endless gymnastic movements.
66 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.1.5 [Link]
Keywords: DifferentialWheels, Koala, keyboard, texture
In this example, two Koala robots (K-Team) circle on a moon-like surface. You can modify
their trajectories with the arrow keys on your keyboard. The moon-like scenery is made of
IndexedFaceSet nodes. Both robots use the same controller code.
3.1. SAMPLES 67
3.1.6 [Link]
Keywords: Quadruped, legged robot, dog robot, passive joint, spring and damper
This example shows a galloping quadruped robot made of active hip joints and passive knee
joints (using spring and dampers). The keyboard can be used to control the robot’s direction and
to change the amplitude of the galloping motion. Each knee is built of two embedded HingeJoint
nodes, one active and one passive, sharing the same rotation axis. The passive HingeJoint simu-
lates the spring and damping. The active HingeJoint is not actuated in this demo but it could be
used for controlling the knee joints.
68 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.1.7 [Link]
Keywords: Salamander robot, swimming robot, amphibious robot, legged robot, physics plugin,
buoyancy
A salamander-shaped robot walks down a slope and reaches a pool where it starts to swim. The
controller uses two different types of locomotion: it walks on the ground and swims in the water.
This demo simulates propulsive forces caused by the undulations of the body and the resistance
caused by the robot’s shape. In addition, the buoyancy of the robot’s body is also simulated using
Archimedes’ principle.
3.1. SAMPLES 69
3.1.8 [Link]
Keywords: Soccer, Supervisor, DifferentialWheels, label
In this example, two teams of simple DifferentialWheels robots play soccer. A Super-
visor is used as the referee; it counts the goals and displays the current score and the remaining
time in the 3D view. This example shows how a Supervisor can be used to read and change
the position of objects.
70 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.1.9 [Link]
Keywords: Sojourner, Passive joint, planetary exploration robot, keyboard, IndexedFaceSet
This is a realistic model of the ”Sojourner” Mars exploration robot (NASA). A large obstacle is
placed in front of the robot so that it is possible to observe how the robot manages to climb over
it. The keyboard can be used to control the robot’s motion.
3.1. SAMPLES 71
3.1.10 [Link]
Keywords: Connector, modular robots, self-reconfiguring robot
In this example, eight ”Yamor” robot modules attach and detach to and from each other us-
ing Connector devices. Connector devices are used to simulate the mechanical connections
of docking systems. In this example, the robot modules go through a sequence of loops and
worm-like configurations while changing their mode of locomotion. All modules use the same
controller code, but their actual module behaviour is chosen according to the name of the module.
72 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.2.1 [Link]
Keywords: Battery, Charger, DifferentialWheels
In this example, a robot moves in a closed arena. The energy consumed by the wheel motors
slowly discharges the robot’s battery. When the battery level reaches zero, the robot is powered
off. In order to remain powered, the robot must recharge its battery at energy chargers. Chargers
are represented by the semi-transparent colored cylinders in the four corners of the arena. Only
a full charger can recharge the robot’s battery. The color of a charger changes with its energy
level: it is red when completely empty and green when completely full.
74 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.2.2 [Link]
Keywords: TouchSensor, bumper, DifferentialWheels
In this example, a robot moves in a closed arena filled with obstacles. Its ”bumper” Touch-
Sensor is used to detect collisions. Each time a collision is detected, the robot moves back and
turns a bit.
3.2. WEBOTS DEVICES 75
3.2.3 [Link]
Keywords: Camera, image processing, DifferentialWheels
In this example, a robot uses a camera to detect colored objects. The robot analyses the RGB
color level of each pixel of the camera images. It turns and stops for a few seconds when it has
detected something. It also prints a message in the Console explaining the type of object it has
detected. You can move the robot to different parts of the arena (using the mouse) to see what it
is able to detect.
76 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.2.4 [Link]
Keywords: Connector, RotationalMotor, IndexedLineSet, USE, DEF, DifferentialWheels
In this example, a light robot (light blue) is lifted over two heavier robots (dark blue). All three
robots are equipped with a Connector placed at the tip of a moveable handle (HingeJoint).
An IndexedLineSet is added to every Connector in order to show the axes. When the
simulation starts, the light robot approaches the first heavy robot and their connectors dock to
each other. Then both robots rotate their handles simultaneously, and hence the light robot gets
passed over the heavy one. Then the light robot gets passed over another time the second heavy
robot and so on ... All the robots in this simulation use the same controller; the different behaviors
are selected according to the robot’s name.
3.2. WEBOTS DEVICES 77
3.2.7 [Link]
Keywords: DifferentialWheels, encoders
This example demonstrates the usage of the wheel encoders of DifferentialWheels robots.
The controller randomly chooses target encoder positions, then it rotates its wheels until the en-
coder values reach the chosen target position. Then the encoders are reset and the controller
chooses new random values. The robot does not pay any attention to obstacles.
80 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.2.9 [Link]
Keywords: GPS, Supervisor, DifferentialWheels, keyboard
This example shows two different techniques for finding out the current position of a robot. The
first technique consists in using an on-board GPS device. The second method uses a Supervi-
sor controller that reads and transmits the position info to the robot. Note that a Supervisor
can read (or change) the position of any object in the simulation at any time. This example im-
plements both techniques, and you can choose either one or the other with the keyboard. The ’G’
key prints the robot’s GPS device position. The ’S’ key prints the position read by the Supervisor.
82 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.2.10 [Link]
Keywords: LED, DifferentialWheels
In this example, a robot moves while randomly changing the color of three LEDs on the top of
its body. The color choice is printed in the Console.
3.2. WEBOTS DEVICES 83
3.2.12 [Link]
Keywords: Pen, keyboard
In this example, a robot uses a Pen device to draw on the floor. The controller randomly chooses
the ink color. The ink on the floor fades slowly. Use the ’Y’ and ’X’ keys to switch the Pen on
and off.
3.2. WEBOTS DEVICES 85
3.3 How To
This section gives various examples of complexe behaviours and/or functionalities. The world
files are located in the WEBOTS_HOME/projects/samples/howto/world directory, and
their controllers in the WEBOTS_HOME/projects/samples/howto/controllers di-
rectory. For each, the world file and its corresponding controller are named according to the
behaviour they exemplify.
3.3.1 [Link]
Keywords: Stereovision, Stereoscopy, Camera
This example simply shows how to equip a robot with two Cameras for stereovision. The
example does not actually perform stereovision or any form of computer vision.
3.3. HOW TO 87
3.3.2 [Link]
Keywords: Humanoid robot, biped robot, power off, passive joint
In this example, a biped robot stands up while his head rotates. After a few seconds, all the
motors are turned off and the robot collapses. This example illustrates how to build a simple
articulated robot and also how to turn off motor power.
88 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.3.5 [Link]
Keywords: Physics plugin, OpenGL drawing, flying robot, Emitter, Receiver
In this example, a robot flies using a physics plugin. This plugins is an example of:
3.3.6 [Link]
Keywords: Supervisor, DifferentialWheels, soccer, label, import node, restart simulation, screen-
shot, change controller
This shows a simple soccer game with six robots and a referee. The Supervisor code demon-
strates the usage of several Supervisor functions. For example, the Supervisor inserts
a second ball to the simulation, changes its color, takes a picture of the 3D view, restarts the
simulation, etc. In addition the Supervisor also plays the role of a soccer referee: it displays
the current score, places the players to their initial position when a goal is scored, etc.
92 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.3.8 [Link]
Keywords: Transform, USE, DEF
This example shows a complex city model built with various Transform nodes. The model
makes a intensive use of the DEF and USE VRML keywords.
94 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.4 Geometries
This section shows the geometric primitives available in Webots. The world files for these exam-
ples are located in the sample/geometries/worlds directory.
In this directory, you will find the following world files :
• [Link]
• [Link]
• convex [Link]
• [Link]
• physics [Link]
• [Link]
• [Link]
• textured [Link]
• webots [Link]
3.5. REAL ROBOTS 95
3.5.3 [Link]
Keywords: Alice, Braitenberg, DistanceSensor
In this example, you can see an Alice robot moving inside an arena while avoiding the walls.
Its world file is in the others/worlds directory. Like many others, this example uses the
braitenberg controller.
98 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.4 [Link]
Keywords: BoeBot, DistanceSensor, LED
In this example, BoeBot moves inside an arena while avoiding the walls. When the robot detects
an obstacle with one of its DistanceSensors, it turns the corresponding LED on.
3.5. REAL ROBOTS 99
3.5.5 [Link]
Keywords: DifferentialWheels, texture, Braitenberg, Accelerometer, Odometry, E-puck
In this example, you can see the e-puck robot avoiding obstacles inside an arena by using
the Braitenberg technique. The odometry of the e-puck is computed at each simulation steps.
The accelerometer values and an estimation the coverage distance and the orientation of the e-
puck are displayed. The source code for this controller is in the WEBOTS_HOME/projects/
default/controllers/braitenberg directory.
100 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.15 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, texture, Khepera
In this example, you can see a Khepera robot from K-Team moving inside an arena while
avoiding the walls. Like many other examples, this one uses the braitenberg controller.
The source code for this controller is located in the WEBOTS_HOME/projects/default/
controllers/braitenberg directory.
110 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.16 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, texture, Khepera II
In this example, you can see a Khepera II robot from K-Team moving inside an arena while
avoiding the walls. Like many other examples, this one uses the braitenberg controller. The
source code for this controller is in the WEBOTS_HOME/projects/default/controllers/
braitenberg directory.
3.5. REAL ROBOTS 111
3.5.17 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, texture, Khepera III
In this example, you can see a Khepera III robot from K-Team moving inside an arena while
avoiding the walls. Like many other examples, this one uses the braitenberg controller. The
source code for this controller is in the WEBOTS_HOME/projects/default/controllers/
braitenberg directory.
112 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
As this example is based on standard UNIX pipes, it does not work under
Windows.
3.5. REAL ROBOTS 117
3.5.24 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, Koala
In this example, you can see a Koala robot from K-Team moving inside an arena while avoiding
the walls. Like many other examples, this one uses the braitenberg controller. The source
code for this controller is located in the WEBOTS_HOME/projects/default/controllers/
braitenberg directory.
3.5. REAL ROBOTS 119
3.5.25 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, Magellan
In this example, you can see a Magellan robot moving inside an arena while avoiding the
walls. As this robot is no longer produced, its world file is in the others/worlds direc-
tory. Like many other examples, this one uses the braitenberg controller. The source code
for this controller is located in the WEBOTS_HOME/projects/default/controllers/
braitenberg directory.
120 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.26 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, Pioneer 2
In this example, you can see a Pioneer 2 robot from ActivMedia Robotics moving inside an arena
while avoiding the walls. Like many other examples, this one uses the braitenberg con-
troller. The source code for this controller is in the WEBOTS_HOME/projects/default/
controllers/braitenberg directory.
3.5. REAL ROBOTS 121
3.5.27 [Link]
Keywords: DifferentialWheels, bumper, TouchSensor, line following, Rover, Java
In this example you can see the Mindstorms Rover robot from LEGO following a black line
drawn on the ground. In the middle of this line there is an obstacle which the robot navigates
around after detecting a collision with it. The robot will then recover its path. As this robot is
a Mindstorms robot, its world file and its controller are in the mindstorms directory. This
example is written both in Java and C, as a reference for translating Webots code from one
language to another. The source code for this controller is in the Rover directory.
122 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.28 [Link]
Keywords: DifferentialWheels, DistanceSensor, Braitenberg, Scout 2
In this example, a Scout 2 robot moves inside an arena while avoiding the walls. Its world
file is in the others/worlds directory. Like many other examples, this one uses the brait-
enberg controller. The source code for this controller is in the WEBOTS_HOME/projects/
default/controllers/braitenberg directory.
3.5. REAL ROBOTS 123
3.5.29 [Link]
Keywords: Robot node, custom ODE plugin, keyboard, passive joint, uneven ground sponginess,
Shrimp, LinearMotor
This example contains a model of the Shrimp robot, which is a mobile platform for rough terrain
from Bluebotics1 . It has 6 wheels and a passive structure which allows it to adapt to the terrain
profile and climb obstacles. It can also turn on the spot. In this example the robot will first move
on its own to the center of the world; then you may drive it yourself using the keyboard. To find
out which keys will allow you to perform these operations, please read the explanation message
printed at the beginning of the simulation in the Console window.
Because of its particular structure, this model is also an example of custom ODE plugins for:
1
[Link]
124 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
3.5.30 [Link]
Keywords: Robot node, legged robot, RotationalMotor, Bioloid, Camera, DistanceSensor, key-
board, modular robots, walking
In this example, the four-legged robot model (figure 3.62 (a)) corresponds to a real Bioloid2 robot
(figure 3.62 (b)) developed by and commercially available from Tribotix3 . This dog-robot model
was build from the Bioloid Comprehensive Kit.
Both the visual aspect and the physical properties of the real robot have been modeled. The
physical dimensions, friction coefficients and mass distribution have been estimated after various
measurements on the components of the real robot.
The source code for the controller of the robot, as well as the model of the robot are located under
the Webots installation directory, in the WEBOTS_HOME/projects/robots/bioloid sub
folder:
Using the keyboard, the user can control the quadruped robot by setting the walking direction
(forward or backwards) and also the heading direction (right or left). Keyboard actions include:
• B: Walk backwards
• F: Walk forward
The walking gait used in the controller relies on an inverse kinematics model. Further details
are available from BIRG web site4 . The included controller illustrates a trotting gait showing
the best performance so far. The turning capabilities of the robot are based on the stride length
modulation. When the robot is asked to turn right, the stride length of the right side and left side
are respectively decreased and increased. During the walk, the extremity of each leg is describing
an ellipsoid, the diameters of these ellipsoids are updated according to the stride length to allow
the robot to turn either right or left.
Other keyboard actions are also provided to fine-tune the frequency and the stride length factor:
• Q: Increase frequency
• W: Decrease frequency
4
[Link]
126 CHAPTER 3. SAMPLE WEBOTS APPLICATIONS
Chapter 4
Language Setup
Webots controllers can be written in C/C++, Java, Python or MATLABTM . This chapter explains
how to install the software development kits for the programming language of your choice.
4.1 Introduction
Webots can execute controllers written in compiled (C/C++, Java) or interpreted (Python, MATLABTM )
languages. The compilation or interpretation process requires extra software that must usually
be installed separately. Only when using C/C++ on the Windows platform it is not necessary
to install a separate C/C++ compiler; on this platform Webots comes with a pre-installed and
preconfigured copy of the MinGW C/C++ compiler. For any other language or platform the soft-
ware development tools must be installed separately. Note that Webots uses very standard tools
that may already be present in a standard installation. Otherwise the instructions in this chapter
will advise you about the installation of your software development tools.
127
128 CHAPTER 4. LANGUAGE SETUP
The first file that is found will be executed by Webots using the required language interpreter
(java, python, matlab). So the priority is defined by the file extension, e.g. it won’t be possible to
execute xyz_controller.m if a file named xyz_controller.py is also present in the
same controller directory. In the case that none of the above filenames exist or if the required
language interpreter is not found, an error message will be issued and Webots will start the void
controller instead.
language: Java
In the Java case there are two options. The controller can be placed in a
.class file or in a .jar file. If a .class file is used, it must be named
xyz_controller.class. If a .jar file is used it must be named xyz_
[Link] and it must contain a class named xyz_controller
that Webots will attempts to start.
4.3 Using C
4.3.1 Introduction
The C API (Application Programming Interface) is composed of a set of about 200 C functions
that can be used in C or C++ controller code. This is the low level interface with the Webots
simulator; all other APIs are built over the C API. A majority of Webots controller examples are
written in C, therefore the C API is Webots de facto standard API. Although less represented in
the controller examples, the other APIs offer exactly the same functionality as the C API.
4.4. USING C++ 129
Windows Instructions
The Windows version of Webots comes with a pre-installed copy of the MinGW C/C++ compiler,
so there is usually no need to install a separate compiler. The MinGW compiler is a port of the
GNU Compiler Collection (gcc) on the Windows platform. The advantage of using the MinGW
compiler will be the better portability of your controller code. If you develop your code with
MinGW it will be straightforward to recompile it on the other Webots supported platforms: Mac
OS X and Linux. However, if you prefer using the Visual C++ compiler you will find instructions
there.
Mac OS X Instructions
In order to compile C/C++ controllers on the Mac, you will need to install Apple Xcode. Xcode
is a suite of tools, developed by Apple, for developing software for Mac OS X. Xcode is free
and can be downloaded from the Apple App Store. Webots will need principally the gcc (GNU
C Compiler) and make commands of Xcode. To install these commands, start Xcode and go to
Xcode menu, Preferences, Downloads, Components and click Install for ”Command Line Tools”.
Linux Instructions
For compiling C controllers, Webots will need the GNU C Compiler and GNU Make utility.
On Linux, these tools are often pre-installed, otherwise you will need to install them separately
(gcc and make packages). For C++ you will also need the GNU C++ Compiler (g++ package).
Optionally you can also install the GNU Debugger (gdb package).
4.4.1 Introduction
The C++ API is a wrapper of the C API described in the previous section. The major part of
the C functions has been wrapped in a function of a specific class. It is currently composed of a
set of about 25 classes having about 200 public functions. The classes are either representations
of a node of the scene tree (such as Robot, LED, etc.) or either utility classes (such as Motion,
ImageRef, etc.). A complete description of these functions can be found in the reference guide
while the instructions about the common way to program a C++ controller can be found in the
chapter 6.
130 CHAPTER 4. LANGUAGE SETUP
The source code of the C++ API is available in the Webots release. You may be interested in
looking through the directory containing the header files (include/controllers/cpp) in
order to get the precise definition of every classes and functions although the reference guide
offers a clean description of the public functions. This directory is automatically included when
the C++ controller is compiled.
For users who want to use a third-party development environment, it is useful to know that the
shared library ([Link],[Link], or libCppController.
dylib) is located in the lib subdirectory of your Webots directory. This directory is automat-
ically included when the C++ controller is linked.
For advanced users who want to modify the C++ API, the C++ sources and the Makefile are
located in the resources/languages/cpp directory.
4.5.1 Introduction
The Java API has been generated from the C++ API by using SWIG. That implies that their
class hierarchy, their class names and their function names are almost identical. The Java API
is currently composed of a set of about 25 classes having about 200 public functions located in
the package called [Link]. The classes are either representations of
a node of the scene tree (such as Robot, LED, etc.) or either utility classes (such as Motion,
ImageRef, etc.). A complete description of these functions can be found in the reference guide
while the instructions about the common way to program a Java controller can be found in the
chapter 6.
In order to develop and run Java controllers for Webots it is necessary to have the Java Develop-
ment Kit (JDK) version 1.7.
4.5. USING JAVA 131
Installation Instructions
The Java Development Kit (JDK) can be downloaded for free from the Sun Developer Network1 .
Make sure you choose the most recent release and the Standard Edition (SE) of the JDK 7. For
Windows, make also sure you have selected the 64 bit version since webots is incompatible with
the 32 bit version. Then follow the installation instructions attending the package.
The java command is the Java Virtual Machine (JVM); it is used for executing Java controllers
in Webots. The javac command is the Java compiler; it is used for compiling Java controllers
in Webots text editor.
These commands should be accessible from a terminal. If it is not the case, this can be done by
modifying your PATH environment variable.
On Mac the JDK installer should do this automatically.
On Linux, you can set the PATH by adding this line to your ˜/.bashrc or equivalent file.
$ export PATH=/usr/lib/jvm/java-XXXXXX/bin:$PATH
Where java-XXXXXX should correspond to the actual name of the installed JDK package.
On Windows, the PATH variable must be set using the Environment Variables dialog.
On Windows 7 and 8, this dialog can be opened like this: Choose Start, Settings, Control Panel,
System and Security, System and open Advanced system settings. Select the Advanced tab and
click on the Environment Variables button.
In the dialog, in the User variables for ... section, look for a variable named PATH. Add the bin
path of the installed SDK to the right end of PATH variables. If the PATH variable does not exist
you should create it. A typical value for PATH is:
C:\Program Files\Java\jdk-XXXXXXX\bin
Where jdk-XXXXXX stands for the actual name of the installed JDK package.
Then, you need to restart Webots so that the change is taken into account.
Note that the PATH can also be set globally for all users. On Linux this can be achieved by
adding it in the /etc/profile file. On Windows this can be achieved by adding it to the Path
variable in the System variables part of the Environment Variables dialog.
In alternative to Oracle JDK, on most popular Linux distribution is also possible to directly install
the open-source JDK from the system package manager. Detailed information can be found on
the OpenJDK website2 .
1
[Link]
2
[Link]
132 CHAPTER 4. LANGUAGE SETUP
If a Java controller fails to execute or compile, check that the java, respectively the javac
commands are reachable. You can verify this easily by opening a Terminal (Linux and Mac OS
X) or a Command Prompt (Windows) and typing java or javac. If these commands are not
reachable from the Terminal (or Command Prompt) they will not be reachable by Webots. In this
case check that the JDK is installed and that your PATH variable is defined correctly as explained
above.
If you run into an error message that looks approximately like this:
Native code library failed to load. See the chapter on Dynamic Linking
Problems in the SWIG Java documentation for help.
[Link]: [Link]: no suitable
image found.
this is due to a 32-bit/64-bit incompatibility between Java Virtual Machine (JVM) and Webots.
On Mac OS X this problem should disappear after you upgrade to a recent version of Webots
(6.3.0 or newer). On Windows, Webots is only compatible with 64-bit versions of Java. On
Linux (and Mac OS X) you should be able to solve this problem by replacing the default ”java”
command string by ”java -d32” or ”java -d64” in the dialog Tools > Preferences > General >
Java command.
For users who want to use a third-party development environment, it can be useful to know that
the package of the Java API ([Link]) is located in the lib directory.
Advanced users may want to modify the Java API. They will need to modify the SWIG script
(controller.i), the java sources and the Makefile located in the resources/languages/
java directory.
4.6.1 Introduction
The Python API has been generated from the C++ API by using SWIG. That implies that their
class hierarchy, their class names and their function names are almost identical. The Python API
is currently composed of a set of about 25 classes having about 200 public functions located in
the module called controller. The classes are either representations of a node of the scene tree
(such as Robot, LED, etc.) or either utility classes (such as Motion, ImageRef, etc.). A complete
description of these functions can be found in the reference guide while the instructions about
the common way to program a Python controller can be found in chapter 6.
The Python API of Webots is built with Python 2.7. Python 2.7 or earlier versions are there-
fore recommended although more recent versions can work without guarantee. Python 3 is not
supported.
Most of the Linux distribution have Python 2.7 already installed. Mac OS X also has Python
installed by default. To check the current version of Python installed on your system, you can
type in a terminal:
$ python --version
Webots will start Python using the python2.7 command line. To check if this command line
is installed on your computer, you can type in a terminal:
$ python2.7 --version
Windows Instructions
Webots comes with Python 2.7 64-bit pre-installed in the msys64 folder.
lib/matlab directory of Webots distribution. These are readable source files; please report
any problem, or possible improvement about these files.
On Linux, the MATLABTM installer does normally suggest to add a symlink to the matlab
startup script in the /usr/local/bin directory. This is a good option to make matlab glob-
ally accessible. Otherwise you can create the link at anytime afterwards with this shell command
(please change according to your actual MATLABTM installation directory and version):
$ sudo ln -s /usr/local/MATLAB/R2014a/bin/matlab /usr/local/bin/matlab
Similarly, on Mac OS X, if Webots is unable to find the matlab startup script then you should
add a symlink in /usr/bin:
$ sudo ln -s /Applications/MATLAB_R2014a.app/bin/matlab /usr/bin/
matlab
ROS is released under the terms of the BSD license, and is open source software. It is free for
commercial and research use. The ros-pkg contributed packages are licensed under a variety of
open source licenses.
Standard Controller
This controller uses the libCppController library and proposes the available Webots func-
tionalities on the ROS network according to the robot’s configuration. Using the roscpp library,
it provides these Webots functions mostly as ROS services and uses standard messages type to
avoid dependencies on third-party packages.
During simulation there can be multiple instances of robots or devices and other Webots appli-
cations connected to the ROS network. Therefore the controller uses a specific syntax to declare
its services or topics on the network:
[robot_unique_name]/[device_name]/[service/topic_name]
[robot_unique_name]: in order to avoid any misunderstanding between different instances
of the same robot, the name of the robot is followed by the ID of the process and the IP address
of the computer.
[device_name]: since the same function can refer to different devices, this field show you
which device it refers to.
[service/topic_name]: this field is equal or really close to the Webots function it corre-
sponds. For topics, it is followed by the sampling period. For services, it is also the name of the
corresponding srv file.
The controller is pre-compiled and you shouldn’t edit it. All you have to do is to load it on
your robot; you will find it in the default list of controller. In order to use it, you will have to
build a ROS node that will communicates with the robot using the different services available.
Good examples of such ROS node can be found inside Webots at WEBOTS_HOME/projects/
languages/ros/webots_ros. In this folder you will find useful instructions to help you.
138 CHAPTER 4. LANGUAGE SETUP
If you want to access the controller from another machine and the roscore
isn’t running on the same machine as Webots, you will need to edit the ROS -
MASTER URI variable. This can be done by editing your environment vari-
ables, setting ’–ROS MASTER URI=address’ in the controller arguments or
with a [Link] file in the controller directory. You must also be able to
connect to each of the computer in ssh in both ways. As ROS uses the host-
name to find other computers on the network, you must add other computers’
hostname and the associated IP address to the known hosts of each computer.
You can find this list in a file named *hosts*. On Linux distribution, you can
find it directly at /etc/hosts; on Mac OS X, it is located at /private/etc/hosts;
on Windows, it is located at C:\Windows\System32\drivers\etc\hosts. On
Windows and Mac OS X, this a hidden path and you will need to search di-
rectly for this path. The hosts file is usually protected and you will need
administrator or root privileges to edit it.
If you want to have a predefined [robot unique name] you can do it by adding
’–name=predefined name’ in the controller arguments. Note that you are
then responsible for avoiding any name clashes between the different robot
controllers.
By default the ROS controller is not blocking the simulation even if no ROS
node is connected to it. In order to synchronize the simulation with the ROS
node, the ’–synchronize’ argument can be used, so that the simulation will
not run as long as the robot time step service is not called.
Furthermode, adding the ’–clock’ argument will make the ROS controller
publish Webots time using the clock topic (which you may use as the ROS
time if the ROS parameter use sim time is set to true).
Custom Controller
The standard controller has been developed in order to work on every robot and for general
purpose. Sometimes, you may not be able to do what you want with this controller or it would
be too complicated. In this case, you can build your own custom controller and ROS node.
It is possible to implement such a ROS node in C++ using the roscpp library. However, in
this case, you need to setup a build configuration to handle both the catkin_make from ROS
and the Makefile from Webots to have the resulting binary linked both against the Webots
libController and the roscpp library. An example of such an implementation is included
in the Webots distribution (see below).
This controller can also be implemented in Python by importing both ROS libraries (roslib,
rospy) and Webots libraries (controller) in a Webots robot or supervisor controller.
4.9. INTERFACING WEBOTS TO THIRD PARTY SOFTWARE WITH TCP/IP 139
A sample C++ ROS node running as a Webots controller is provided in the Webots distri-
bution for Linux. It is located in the Webots WEBOTS_HOME/projects/languages/
ros/custom folder and contains a world file named [Link] and a controller named
joystick which allows the user to drive a simulated robot using a joystick through the ROS
joy node. This controller is a very simple example of a ROS node running as a Webots controller.
It could be used as a starting point to develop more complex interfaces between Webots and ROS.
The controller directory includes all the Makefile machinery to call the build tools used by
ROS and Webots to produce the controller binary. The ros folder also includes a [Link]
file with detailed installation and usage instructions.
4.9.1 Overview
Webots offers programming APIs for following languages: C/C++, Java, Python and MATLABTM .
It is also possible to interface Webots with other programming languages of software packages,
such as LispTM , LabViewTM , etc. Such an interface can be implemented through a TCP/IP
protocol that you can define yourself. Webots comes with an example of interfacing a simu-
lated Khepera robot via TCP/IP to any third party program able to read from and write to a
TCP/IP connection. This example world is called khepera_tcpip.wbt, and can be found
in the WEBOTS_HOME/projects/robots/khepera/khepera1/worlds directory of
Webots. The simulated Khepera robot is controlled by the tcpip controller which is in the
controllers directory of the same project. This small C controller comes with full source
code in tcpip.c, so that you can modify it to suit your needs. A client example is provided
in client.c. This client may be used as a model to write a similar client using the program-
ming language of your third party software. This has already been implemented in LispTM and
MATLABTM by some Webots users.
several TCP/IP connections. To allow the tcpip process to open a different port depending on
the controlled robot, you should give a different name to each robot and use the robot get -
name() in the tcpip controller to retrieve this name and decide which port to open for each
robot.
The second advantage is that you can also control a real robot from your third party software
by simply implementing your library based on the given remote control library. Switching to
the remote control mode will redirect the input/output to the real robot through the Inter-Process
Communication (IPC). An example of remote control is implemented for the e-puck robot in
the file WEBOTS_HOME/projects/robots/e-puck/worlds/[Link] directory
of Webots.
The third advantage is that you can spread your controller programs over a network of com-
puters. This is especially useful if the controller programs perform computationally expensive
algorithms such as genetic algorithms or other learning techniques.
Finally, you should set the controlled robot to synchronous or asynchronous mode depending
on whether or not you want the Webots simulator to wait for commands from your controllers.
In synchronous mode (with the synchronization field of the robot equal to TRUE), the
simulator will wait for commands from your controllers. The controller step defined by the
robot step parameter of the tcpip controller will be respected. In asynchronous mode
(with the synchronization field of the robot set to FALSE), the simulator will run as fast
as possible, without waiting for commands from your controllers. In the latter case, you may
want to run the simulation in real time mode so that robots will behave like real robots controlled
through an asynchronous connection.
4.9.3 Limitations
The main drawback of TCP/IP interfacing is that if your robot has a camera device, the protocol
must send the images to the controller via TCP/IP, which might be network intensive. Hence
it is recommended to have a high speed network, or use small resolution camera images, or
compress the image data before sending it to the controller. This overhead is negligible if you use
a low resolution camera such as the Khepera K213 (see example WEBOTS_HOME/projects/
robots/khepera/khepera1/worlds/khepera_k213.wbt).
Chapter 5
Development Environments
This chapter indicates how to use the built-in development environment or third-party environ-
ments for developing Webots controllers.
The Source Code Editor can be used to compile C/C++ or Java source files into binary executable
or bytecode (Java) files that can be executed in a simulation. The compilation output is printed
to Webots console; errors and warnings appear in red. If you double-click an error message,
Webots will highlight the corresponding source line in the editor.
Note that, for compiling source code it is necessary to have the appropriate development tools
installed. You will find information on the development tools here.
In the following, the possible compilation actions are listed. Some of them are only accessible in
the Build menu, whereas Build and Clean actions have a shortcut in the Text Editor toolbar.
Builds the whole project by invoking make in the selected file’s directory. With C/C++,
the Build button compiles and links the whole project into an executable file. C/C++ source file
dependencies are automatically generated and updated when necessary. With Java, the Build
button compiles the whole project into bytecode (.class files).
141
142 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
The Clean button invokes make clean to delete the intermediate compilation files in the
current file’s directory. The source files remain untouched.
The Make JAR file menu item rebuilds the whole project and packs all the .class in a .jar. This
is a convenience function that can be used to pack a complete controller prior to uploading it to
one of our online contest website.
The Cross-compile menu item allows to cross-compile the current text editor’s file. Note that a
specific Makefile is required in the controller’s directory for performing this operation. For an
e-puck robot, this Makefile must be named Makefile.e-puck.
The Cross-compilation clean menu item allows you to clean the cross-compilation files. Note
that a specific Makefile is required in the controller’s directory for performing this operation. For
an e-puck robot, this Makefile must be named Makefile.e-puck.
• controllers: this directory contains the controllers available in each world files of the
current project. The link between the world files and this directory is done through the
controller field of the Robot node (explained in the reference manual). More information
about this directory in the following subsections.
• protos: this directory contains the PROTO files available for all the world files of the
current project.
• plugins: this directory contains the plugins available in the current project. The link
between the world files and this directory is done through the physics field of the WordInfo
node (explained in the reference manual).
• worlds: this directory contains the world files, the project files (see below) and the tex-
tures (typically in a subdirectory called textures).
Note that the directories can be created by using the wizard New Project
Directory described in chapter 2.
144 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
The project files contain information about the GUI (such as the perspective). These files are
hidden. Each world file can have one project file. If the world file is named myWorldFile.
wbt, its project file is named .[Link]. This file is written by Webots when
a world is correctly closed. Removing it allows you to retrieve the default perspective.
controllers/
controllers/simple_controller/
controllers/simple_controller/Makefile
controllers/simple_controller/simple_controller.c
controllers/simple_controller/simple_controller[.exe]
You can create all the files needed by a new controller using the wizard New
Robot Controller described in chapter 2.
$ export WEBOTS_HOME=/usr/local/webots
5.3.2 Windows
On Windows you must use the MSYS terminal to compile the controllers. MSYS is a UNIX-like
terminal that can be used to invoke MinGW commands. It can be downloaded from [Link] .
You will also need to add the bin directory of MinGW to your PATH environment variable.
MinGW is located in the mingw subdirectory of Webots distribution. When set correctly, the
environment variable should be like this:
WEBOTS_HOME=C:\Program Files\Webots
PATH=C:\program Files\Webots\mingw\bin;C:\...
Once MSYS is installed and the environment variables are defined, you should be able to compile
controllers by invoking mingw32-make in the MSYS terminal, e.g.:
$ mingw32-make
$ mingw32-make clean
$ mingw32-make my_robot.class
$ mingw32-make my_robot.o
The compilation of Webots C/C++ and Java controllers can be configured in the provided Make-
files. A controller’s Makefile is a configuration file used by the make utility and that optionally
1
[Link]
146 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
specifies a list of source files and how they will be compiled and linked to create the executable
program.
Note that Python and MATLABTM are interpreted languages and therefore they don’t need Make-
files. So if you are using any of these programming languages or Visual C++ then you can ignore
this section.
When using C/C++ or Java, the presence of a Makefile in the controller directory is neces-
sary. If the Makefile is missing Webots will automatically propose to create one. This Makefile
can be modified with a text editor; its purpose is to define project specific variables and to in-
clude the global [Link] file. The global [Link] file is stored
in WEBOTS_HOME/resources/ directory; it contains the effective build rules and may vary
with the Webots version. Note that Webots Makefiles are platform and language independent.
If a controller requires several C/C++ source files they need to be specified in the Makefile. The
name of each source file must be listed, using one of these variables:
Variable Usage
C SOURCES Specifies a list of .c sources files
CXX SOURCES Specifies a list of .cpp, *.cc or *.c++ source files
Table 5.1: Webots Makefile Sources Variables
Every source file specified using these variables, will be added to the controller build. In addition
dependency files will be automatically generated by the make command in order to minimize
the build. Note that these variables should not be used in any language other than C or C++.
For example, if a controller has several .c source files, then this can be specified like this in the
controller’s Makefile:
C_SOURCES = my_controller.c my_second_file.c my_third_file.c
If a project has several .cpp source files, then this can be specified like this:
CXX_SOURCES = my_controller.cpp my_second_file.cpp my_third_file.cc
Important: the build rules require that one of the source files in the list must correspond to
the controller name (i.e. controller directory name), e.g. if the controller directory is my_
controller then the list must contain either my_controller.c,my_controller.
cpp or my_controller.cc accordingly.
5.4. USING WEBOTS MAKEFILES 147
Variable Usage
CFLAGS Specifies a list of flags that will be passed to the gcc/g++ compiler
INCLUDE Specifies a list of flags that will be passed to the gcc/g++ compiler
LIBRARIES Specifies a list of flags that will be passed to the linker
Table 5.2: Webots Makefile Compiler Variables
Webots C/C++ controllers are regular binary executable files that can easily be compiled and
linked with external libraries. To add an external library it is only necessary to specify the path
to the header files, and the path and name of the library in the controller’s Makefile. For example
the -Idir flag can be used to add a directory to search for include files. The LIBRARIES variable
can be used to pass flags to the linker. For example the -Ldir flag can be used to add a directory
to search for static or dynamic libraries, and the -l flag can be used to specify the name of a
library that needs to be linked with the controller.
For example, let’s assume that you would like to add an external library called XYZLib. And let’s
assume that the library’s header files and .dll file are located like this (Windows):
C:\Users\YourName\XYZLib\include\XYZLib.h
C:\Users\YourName\XYZLib\lib\[Link]
Then here is how this should be specified in the Makefile:
INCLUDE = -I"C:\Users\YourName\XYZLib\include"
LIBRARIES = -L"C:\Users\YourName\XYZLib\lib" -lXYZLib
The first line tells gcc where to look for the #include<XYZLib.h> file. The second line tells gcc
to link the executable controller with the [Link] and where that .dll can be found. Note
that this would be similar on Linux and Mac OS X, you would just need to use UNIX-compatible
paths instead. If more external libraries are required, it is always possible to use additional -I,
-L and -l flags. For more information on these flags, please refer to the gcc man page.
Normally, C++ controllers use Webots C++ API. The C++ API is a set of C++ classes provided
by C++ header files, e.g. #include <webots/[Link]>. If you prefer, C++ control-
lers can use Webots C API instead. The C API is a set of C functions starting with the wb prefix
and provided by C header files, e.g. #include <webots/robot.h>. To use the C API in
a C++ controller you need to add this line in your controller Makefile:
USE_C_API = true
148 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
If you need to debug your controller, you need to recompile it with the debug target from a
terminal:
make debug
This will instruct gcc to add debugging information so that the executable can be debugged using
gcc.
On Mac OS X, use rather ps -x and on Windows use the Task Manager for this. If one of
your robot controllers is missing in the list (or appearing as <defunct>) this confirms that it
has crashed and therefore blocked the simulation. In this example the soccer_supervisor
has crashed. Note that the crash of a controller is almost certainly caused by an error in the
controller code, because an error in Webots would have caused Webots to crash. Fortunately, the
GNU debugger (gdb) can usually help finding the reason of the crash. The following example
assumes that there is a problem with the soccer_supervisor controller and indicates how
to proceed with the debugging.
5.5. DEBUGGING C/C++ CONTROLLERS 149
Then you must recompile the controller, either by using the Clean and Build buttons of the Webots
text editor or directly in a terminal:
$ make clean
$ make
...
Note that, the -g flag should now appear in the compilation line. Once you have recompiled
the controller, hit the Pause and Revert buttons. This pauses the simulation and reloads the
freshly compiled versions of the controller. Now find the process ID (PID) of the soccer_
supervisor process, using ps -e (Linux) or ps -x (Mac OS X), or using the Task Manager
(Windows). The PID is in the left-most column of output of ps as shown above. Then open a
terminal and start the debugger by typing:
$ gdb
...
(gdb) attach PID
...
(gdb) cont
Continuing.
Where PID stands for the PID of the soccer_supervisor process. The attach command
will attach the debugger to the soccer_supervisor process and interrupt its execution.
Then the cont command will instruct the debugger to resume the execution of the process. (On
Windows you will need to install the [Link] file separately and use an MSYS console to
achieve this.)
Then hit the Run button to start the simulation and let it run until the controller crashes again.
The controller’s execution can be interrupted at any time (Ctrl-C), in order to query variables, set
up break points, etc. When the crash occurs, gdb prints a diagnostic message similar to this:
Program received signal SIGSEGV, Segmentation fault.
[Switching to Thread -1208314144 (LWP 16448)]
0x00cd6dd5 in _IO_str_overflow_internal () from /lib/tls/[Link].6
This indicates the location of the problem. You can examine the call stack more precisely by
using the where command of gdb. For example type:
(gdb) where
#0 0x00cd6dd5 in _IO_str_overflow_internal() from /lib/tls/[Link].6
#1 0x00cd596f in _IO_default_xsputn_internal() from /lib/tls/[Link].6
150 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
By examining carefully the call stack you can locate the source of the error. In this example we
will assume that the sprintf() function is OK, because it is in a system library. Therefore it
seems that the problem is caused by an illegal use of the sprintf() function in the run()
function. The line 106 of the source file soccer_supervisor.c must be examined closely.
While the controller is still in memory you can query the values of some variables in order to
understand what happened. For example, you can use the frame and print commands:
(gdb) frame 6
#6 0x08048953 in run (ms=0) at soccer_supervisor.c:106
106 sprintf(time_string, "%02d:%02d", (int) (time / 60),
(int) time % 60);
(gdb) print time_string
$1 = 0x0
The frame command instructs the debugger to select the specified stack frame, and the print
command prints the current value of an expression. In this simple example we clearly see that the
problem is caused by a NULL (0x0) time string argument passed to the sprintf() function.
The next steps are to: fix the problem, recompile the controller and revert the simulation to give
it another try. Once it works correctly you can remove the -g flag from the Makefile.
5.6.1 Introduction
Microsoft Visual C++ is an integrated development environment (IDE) for C/C++ available on
the Windows platform. On Windows, Visual C++ is a possible alternative to using Webots built-
in gcc (MinGW) compiler. Visual C++ can be used to develop controllers using Webots C or
C++ API. The developer must choose one of these two APIs as they cannot be used together in
controller code. The C API is composed of .h files that contains flat C functions that can be
used in C or C++ controllers. The C++ API is composed of .hpp files that contain C++ classes
and methods that can be used in C++ controllers only.
Two Visual C++ projects examples are included in Webots distribution: WEBOTS_HOME\projects\
robots\khr-2hv\controllers\khr2\[Link] and WEBOTS_HOME\projects\
robots\khr-2hv\plugins\physics\khr2\[Link]. However in princi-
ple any C or C++ controller from Webots distribution can be turned into a Visual C++ project.
5.6. USING VISUAL C++ WITH WEBOTS 151
5.6.2 Configuration
When creating a Webots controller with Visual C++, it is necessary to specify the path to Webots
.h and/or .hpp files. It is also necessary to configure the linker to use the [Link]
import library from Webots distribution. The [Link] files is needed to link with
the [Link] file that must be used by the controller in order to communicate with
Webots.
The following procedure (Visual C++ 2008 Express) explains how to create a Visual C++ con-
troller for Webots. Note that the resulting .exe file must be launched by Webots; it cannot be
run from Visual C++.
1. Copy a Webots project from Webots distribution to your Documents folder, or create an
empty project directory using Webots menu: Wizard > New Project Directory... Either way,
the project directory must contain the controllers and worlds subdirectories.
2. Start Visual C++ and select: File > New > Project... Then choose these settings:
Project type: General
Template: Empty Project
Name: MyController (for example)
Location: C:\Users\MyName\Documents\MyProject\controllers (for
example)
Where ”MyController” is the name of a new or already existing controller directory, and
where ”Location” must indicate the controllers subdirectory of your Webots project
directory.
3. Then you can add a C or C++ source file to your project: Choose either: Project > Add
Existing Item or Project > Add New Item > C++ File (.cpp). In the second case you can copy
the content of one of the C/C++ examples of Webots distribution.
Note that if you copied C code from Webots examples to Visual C++, it is highly recom-
mended to change the source file extension from .c to .cpp. The reason is that Webots
examples are written for the gcc compiler which uses a more modern version of the C
language than Visual C++. By changing the file extension to .cpp you will instruct Visual
C++ to compile the file in C++ mode (/TP) which is more tolerant with gcc code. If you
don’t do it, you may run into error messages like these:
MyController.c(24): error C2275: ’WbDeviceTag’ : illegal use of
this type as an expression
MyController.c(24): error C2146: syntax error : missing ’;’
before
identifier ’ir0’
...
152 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
4. Now we can set up the project configuration for Webots. Select the Project > Properties
menu. In the Property Pages, in the Configuration Properties, enter following configura-
tion:
C/C++ > General > Additional Include Directories:
C:\Program Files\Webots\include\controller\c
This will tell Visual C++ where to find Webots C API (.h files).
By default Visual C++ places the .exe file in a Debug or Release subdirectory. How-
ever order to be executed by Webots, the .exe file must be placed directly at the root of the
MyController directory. So in this example the .exe should be there: MyProject\
controllers\MyController\[Link]. Consequently the linker out-
put file should be configured like this:
Linker > General > Output File: $(ProjectName).exe
Now we need to tell Visual C++ to use the [Link] import library:
Linker > Input > Additional Dependencies:
[Link]
Linker > General > Additional Library Directories:
C:\Program Files\Webots\msys64\mingw64\lib\
5. If you want to use the C API, you should skip step 5 and go directly to step 6. If you want
to use the C++ API follow these instructions:
In Property Pages, in the Configuration Properties, add the path to Webots .hpp files:
C/C++ > General > Additional Include Directories:
C:\Program Files\Webots\include\controller\c
C:\Program Files\Webots\include\controller\cpp
Now you should have the path to both the .h and the .hpp files.
Then you need to add Webots C++ wrappers to your project. The C++ wrappers are .cpp
files that implement the interface between the C++ API and the C API. You can proceed
like this:
In Visual C++, in the Solution Explorer: right-mouse-click on the Sources Files folder,
then select Add > New Filter. This should create a NewFilter1 subfolder in your Sources
Files folder. Then select the NewFilter1 and with the right-mouse-button: choose the Add
> Existing Item... menu. In the file dialog, go to the C:\ProgramFiles\Webots\
resources\languages\cpp directory, then select all the .cpp files (but no other file)
in that directory and hit the Add button. This should add the [Link],
[Link],[Link], etc. source files to your project.
6. Now you should be able to build your controller with the Build > Build MyController
menu item (or the F7 key). This should generate the MyProject\controllers\
MyController\[Link] file.
5.7. STARTING WEBOTS REMOTELY (SSH) 153
7. Now we can switch to Webots in order to test the .exe controller. Start Webots and ver-
ify that your robot is associated with the correct controller: In the Scene tree, expand the
robot node and check the controller field. It should be: controller "MyCon-
troller". Otherwise you should change it: hit the ... (ellipsis) button, this opens a
selection dialog. In the selection dialog choose ”MyController”. Then hit the Save button
in Webots main window. Finally you can hit the Run button to start the simulation. At this
point the simulation should be using your Visual C++ controller.
8. If you want to debug your controller with Visual C++ you can attach the debugger to
the running controller process. Proceed like this: In Webots, hit the Pause button then
the Revert button. Then, in Visual C++, use the Debug > Attach to Process... menu. In
the dialog choose the [Link] webots process. Still in Visual C++, you can now
add breakpoints and watches in the controller code. Then, in Webots, hit the Run button
to resume the simulation. Now the controller should pause when it reaches one of your
breakpoints.
The first line logs onto computer B. The 2nd line sets the DISPLAY variable to the display 0 (and
screen 0) of computer B. This will indicate to all X11 applications (including Webots) that they
needs to connect to the X-server running on the local computer: computer B in this case. This
step is necessary because the DISPLAY variable is usually not set in an ssh session.
The last line starts Webots: the –mode=fast option enables the Fast simulation mode, which
is available only with Webots PRO. The –mode=fast option makes the simulation run as fast as
possible, without graphical rendering, which is fine because the graphical output won’t be visible
anyway from computer A. Options –stdout and –stderr are used to redirect Webots’ output to
the standard streams instead of Webots console, otherwise the output would not be visible on
computer A.
At this point, Webots will start only if a X-server with proper authorizations is running on com-
puter B. To ensure that this is the case, the simplest solution is to have an open login session on
154 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
computer B, i.e., to have logged in using the login screen of computer B, and not having logged
out. Unless configured differently, the ssh login and the screen login session must belong to the
same user, otherwise the X-server will reject the connection. Note that the xhost + command
can be used to grant access to the X-server to another user. For security reasons, the screen of
the open session on computer B can be locked (e.g. with a screen-saver): this won’t affect the
running X-server.
A little problem with the above approach is that closing the ssh session will kill the remote jobs,
including Webots. Fortunately it is easy to overcome this problem by starting the Webots as a
background job and redirecting its output to a file:
$ ssh myname@[Link]
$ export DISPLAY=:0.0
$ webots --mode=fast --stdout --stderr [Link] &> [Link] &
$ exit
The &> sign redirects into a text file the output that would otherwise appear in the ssh terminal.
The & sign starts Webots as a background job: so the user can safely exit the ssh session, while
Webots keeps running.
In this case the decision to terminate the job is usually made in the Supervisor code according
to simulation specific criteria. The wb supervisor simulation quit() function can be
used to automatically terminate Webots when the job is over.
In mobile robot simulation, it is often useful to transfer the results onto real mobile robots.
Webots was designed with this transfer capability in mind. The simulation is as realistic as
possible, and the programming interface can be ported or interfaced to existing, real robots.
Webots already comprises transfer systems for a number of existing robots including e-puckTM ,
DARwIn-OPTM , KheperaTM and HemissonTM . This section explains how to develop your own
transfer system to your own mobile robot.
Since the simulation is only an approximation of the physics of the real robot, some tuning is
always necessary when developing a transfer mechanism for a real robot. This tuning will affect
the simulated model so that it better matches the behavior of the real robot.
5.8. TRANSFER TO YOUR OWN ROBOT 155
Often, the easiest way to transfer your control program to a real robot is to develop a remote
control system. In this case, your control program runs on the computer, but instead of sending
commands to and reading sensor data from the simulated robot, it sends commands to and reads
sensor data from the real robot. Developing such a remote control system can be achieved in a
very simple way by writing your own implementation of the Webots API functions as a small
library. For example, you will probably have to implement the wb differential wheels -
set speed() function to send a specific command to the real robot with the wheel speeds as
an argument. This command can be sent to the real robot via the serial port of the PC, or any
other PC-robot interface you have. You will probably need to make some unit conversions, since
your robot may not use the same units of measurement as the ones used in Webots. The same
applies for reading sensor values from the real robot.
Webots already provides some facilities to implement a remote control library and in particular
it is possible to develop it as a controller plugin. Once set in the corresponding field of the Robot
node, this remote control plugin will be executed automatically when running the controller.
Implementation details are described in subsection 6.6.5.
Special functions
The wb robot init() function must be the first called function. It performs the controller
library’s initialization.
The wb robot step() function should be called repeatedly (typically in an infinite loop). It
requests that the simulator performs a simulation step of ms milliseconds; that is, to advance the
simulation by this amount of time.
The wb robot cleanup() function should be called at the end of a program in order to leave
the controller cleanly.
Once linked with your own remote control plugin, you can control your real robot by running
the simulation in Webots. It might be useful to also add a robot window plugin (see subsection
6.6.2) to graphically display specific sensor values, motor commands or a stop button.
Such a remote control system is designed to be implemented in C/C++ as explained in section
6.6; however, it can also be implemented other programming languages creating a wrapper.
156 CHAPTER 5. DEVELOPMENT ENVIRONMENTS
5.8.2 Cross-compilation
Cross-compilation overview
Developing a cross-compilation system will allow you to recompile your Webots controller for
the embedded processor of your own real robot. Hence, the source code you wrote for the Webots
simulation will be executed on the real robot itself, and there is no need to have a permanent PC
connection with the robot as with the remote control system. This is only possible if the processor
on your robot can be programmed respectively in C, C++, Java or Python. It is not possible for
a processor that can be programmed only in assembler or another specific language. Webots
includes the source code of such a cross-compilation system for the e-puck and the Hemisson
robot. Samples are located in the WEBOTS_HOME/projects/robots directory.
Unlike the remote control system, the cross-compilation system requires that the source code
of your Webots controller be recompiled using the cross-compilation tools specific to your own
robot. You will also need to rewrite the Webots include files to be specific to your own robot.
In simple cases, you can just rewrite the Webots include files you need, as in the hemisson
example. In more complex cases, you will also need to write some C source files to be used as
a replacement for the Webots Controller library, but running on the real robot. You should
then recompile your Webots controller with your robot cross-compilation system and link it with
your robot library. The resulting file should be uploaded onto the real robot for local execution.
Examples
Webots support cross-compilation for several existing commercial robots. For the e-puckTM robot,
this system is fully integrated in Webots and needs no modification in the code. For the HemissonTM robot,
this system needs a few include files to replace the Webots API include files. For the KheperaTM robot,
a specific C library is used in addition to specific include files.
Programming Fundamentals
This chapter introduces the basic concepts of programming with Webots. Webots controllers can
be written in C/C++, Java, Python or MATLABTM . Besides their syntactic differences all these
languages share the same low-level implementation. As long as the sequence of function/method
calls does not vary, every programming language will yield exactly the same simulation results.
Hence the concepts explained here with C examples also apply to C++/Java/Python/Matlab.
157
158 CHAPTER 6. PROGRAMMING FUNDAMENTALS
This code repeatedly prints "Hello World!" to the standard output stream which is redi-
rected to Webots console. The standard output and error streams are automatically redirected to
Webots console for all Webots supported languages.
Webots C API (Application Programming Interface) is provided by regular C header files. These
header files must be included using statements like #include <webots/xyz.h> where
xyz represents the name of a Webots node in lowercase. Like with any regular C code it is
also possible to include the standard C headers, e.g. #include <stdio.h>. A call to the
initialization function wb robot init() is required before any other C API function call.
This function initializes the communication between the controller and Webots. Note that wb -
robot init() exists only in the C API, it does not have any equivalent in the other supported
programming languages.
Usually the highest level control code is placed inside a for or a while loop. Within that loop
there is a call to the wb robot step() function. This function synchronizes the controller’s
data with the simulator. The function wb robot step() needs to be present in every controller
and it must be called at regular intervals, therefore it is usually placed in the main loop as in the
above example. The value 32 specifies the duration of the control steps, i.e. the function wb -
robot step() shall compute 32 milliseconds of simulation and then return. This duration
specifies an amount of simulated time, not real (wall clock) time, so it may actually take 1
millisecond or one minute of CPU time, depending on the complexity of the simulated world.
Note that in this ”Hello World!” example the while loop has no exit condition, hence the return
statement is never reached. It is usual to have an infinite loop like this in the controller code: the
result is that the controller runs as long as the simulation runs.
Now that we have seen how to print a message to the console, we shall see how to read the
sensors of a robot. The next example does continuously update and print the value returned by a
DistanceSensor:
1 #include <webots/robot.h>
2 #include <webots/distance_sensor.h>
3 #include <stdio.h>
4
5 #define TIME_STEP 32
6
7 int main() {
8 wb_robot_init();
9
10 WbDeviceTag ds = wb_robot_get_device("my_distance_sensor");
11 wb_distance_sensor_enable(ds, TIME_STEP);
12
13 while (1) {
6.1. CONTROLLER PROGRAMMING 159
14 wb_robot_step(TIME_STEP);
15 double dist = wb_distance_sensor_get_value(ds);
16 printf("sensor value is %f\n", dist);
17 }
18
19 return 0;
20 }
As you can notice, prior to using a device, it is necessary to get the corresponding device tag
(WbDeviceTag); this is done using the wb robot get device() function. The WbDe-
viceTag is an opaque type that is used to identify a device in the controller code. Note that
the string passed to this function, ”my distance sensor” in this example, refers to a device name
specified in the robot description (.wbt or .proto file). If the robot has no device with the
specified name, this function returns 0.
Each sensor must be enabled before it can be used. If a sensor is not enabled it returns undefined
values. Enabling a sensor is achieved using the corresponding wb * enable() function, where
the star (*) stands for the sensor type. Every wb * enable() function allows to specify an
update delay in milliseconds. The update delay specifies the desired interval between two updates
of the sensor’s data.
In the usual case, the update delay is chosen to be similar to the control step (TIME STEP)
and hence the sensor will be updated at every wb robot step(). If, for example, the update
delay is chosen to be twice the control step then the sensor data will be updated every two wb -
robot step(): this can be used to simulate a slow device. Note that a larger update delay
can also speed up the simulation, especially for CPU intensive devices like the Camera. On the
contrary, it would be pointless to choose an update delay smaller than the control step, because it
will not be possible for the controller to process the device’s data at a higher frequency than that
imposed by the control step. It is possible to disable a device at any time using the corresponding
wb * disable() function. This may increase the simulation speed.
The sensor value is updated during the call to wb robot step(). The call to wb dis-
tance sensor get value() retrieves the latest value.
Note that some device return vector values instead of scalar values, for example these functions:
1 const double *wb_gps_get_values(WbDeviceTag tag);
2 const double *wb_accelerometer_get_values(WbDeviceTag tag);
3 const double *wb_gyro_get_values(WbDeviceTag tag);
Each function returns a pointer to three double values. The pointer is the address of an array
allocated by the function internally. These arrays should never be explicitly deleted by the con-
troller code. They will be automatically deleted when necessary. The array contains exactly three
double values. Hence accessing the array beyond index 2 is illegal and may crash the controller.
Finally, note that the array elements should not be modified, for this reason the pointer is declared
as const. Here are correct examples of code using these functions:
160 CHAPTER 6. PROGRAMMING FUNDAMENTALS
The example below shows how to make a rotational motor oscillate with a 2 Hz sine signal.
Just like sensors, each Webots actuator must be identified by a WbDeviceTag returned by
the wb robot get device() function. However, unlike sensors, actuators don’t need to be
expressly enabled; they actually don’t have wb * enable() functions.
To control a motion, it is generally useful to decompose that motion in discrete steps that cor-
respond to the control step. As before, an infinite loop is used here: at each iteration a new
target position is computed according to a sine equation. The wb motor set position()
function stores a new position request for the corresponding rotational motor. Note that wb -
motor set position() stores the new position, but it does not immediately actuate the
motor. The effective actuation starts on the next line, in the call to wb robot step(). The
wb robot step() function sends the actuation command to the RotationalMotor but
6.1. CONTROLLER PROGRAMMING 161
it does not wait for the RotationalMotor to complete the motion (i.e. reach the specified
target position); it just simulates the motor’s motion for the specified number of milliseconds.
1 #include <webots/robot.h>
2 #include <webots/motor.h>
3 #include <math.h>
4
5 #define TIME_STEP 32
6
7 int main() {
8 wb_robot_init();
9
10 WbDeviceTag motor = wb_robot_get_device("my_motor");
11
12 double F = 2.0; // frequency 2 Hz
13 double t = 0.0; // elapsed simulation time
14
15 while (1) {
16 double pos = sin(t * 2.0 * M_PI * F);
17 wb_motor_set_position(motor, pos);
18 wb_robot_step(TIME_STEP);
19 t += (double)TIME_STEP / 1000.0;
20 }
21
22 return 0;
23 }
When wb robot step() returns, the motor has moved by a certain (linear or rotational)
amount which depends on the target position, the duration of the control step (specified with
wb robot step()), the velocity, acceleration, force, and other parameters specified in the
.wbt description of the Motor. For example, if a very small control step or a low motor veloc-
ity is specified, the motor will not have moved much when wb robot step() returns. In this
case several control steps are required for the RotationalMotor to reach the target position.
If a longer duration or a higher velocity is specified, then the motor may have fully completed
the motion when wb robot step() returns.
Note that wb motor set position() only specifies the desired target position. Just like
with real robots, it is possible (in physics-based simulations only), that the RotationalMotro
is not able to reach this position, because it is blocked by obstacles or because the motor’s torque
(maxForce) is insufficient to oppose to the gravity, etc.
If you want to control the motion of several RotationalMotors simultaneously, then you
need to specify the desired position for each RotationalMotor separately, using wb mo-
tor set position(). Then you need to call wb robot step() once to actuate all the
RotationalMotors simultaneously.
162 CHAPTER 6. PROGRAMMING FUNDAMENTALS
The control step is the duration of an iteration of the control loop. It corresponds to the parameter
passed to the wb robot step() function. The wb robot step() function advances the
controller time of the specified duration. It also synchronizes the sensor and actuator data with
the simulator according to the controller time.
Every controller needs to call wb robot step() at regular intervals. If a controller does
not call wb robot step() the sensors and actuators won’t be updated and the simulator will
block (in synchronous mode only). Because it needs to be called regularly, wb robot step()
is usually placed in the main loop of the controller.
The simulation step is the value specified in [Link] (in milliseconds).
It indicates the duration of one step of simulation, i.e. the time interval between two computations
of the position, speed, collisions, etc. of every simulated object. If the simulation uses physics
(vs. kinematics), then the simulation step also specifies the interval between two computations
of the forces and torques that need to be applied to the simulated rigid bodies.
The execution of a simulation step is an atomic operation: it cannot be interrupted. Hence a
sensor measurement or a motor actuation can only take place between two simulation steps. For
that reason the control step specified with each wb robot step() must be a multiple of the
simulation step. So for example, if the simulation step is 16 ms, then the control step argument
passed to wb robot step() can be 16, 32, 64, 128, etc.
Webots and each robot controller are executed in separate processes. For example, if a simulation
involves two robots, there will be three processes in total: one for Webots and two for the two
robots. Each controller process exchanges sensors and actuators data with the Webots process
during the calls to wb robot step(). So for example, wb motor set position() does
not immediately send the data to Webots. Instead it stores the data locally and the data are
effectively sent when wb robot step() is called.
For that reason the following code snippet is a bad example. Clearly, the value specified with the
first call to wb motor set position() will be overwritten by the second call:
1 wb_motor_set_position(my_leg, 0.34); // BAD: ignored
2 wb_motor_set_position(my_leg, 0.56);
3 wb_robot_step(40);
6.1. CONTROLLER PROGRAMMING 163
since there was no call to wb robot step() between the two sensor readings, the values
returned by the sensor cannot have changed in the meantime. A working version would look like
this:
1 while (1) {
2 double d1 = wb_distance_sensor_get_value(ds1);
3 wb_robot_step(40);
4 double d2 = wb_distance_sensor_get_value(ds1);
5 if (d2 < d1)
6 avoidCollision();
7 wb_robot_step(40);
8 }
However the generally recommended approach is to have a single wb robot step() call in
the main control loop, and to use it to update all the sensors and actuators simultaneously, like
this:
1 while (1) {
2 readSensors();
3 actuateMotors();
4 wb_robot_step(TIME_STEP);
5 }
Note that it may also be judicious to move wb robot step() to the beginning of the loop, in
order to make sure that the sensors already have valid values prior to entering the readSen-
sors() function. Otherwise the sensors will have undefined values during the first iteration of
the loop, hence:
1 while (1) {
2 wb_robot_step(TIME_STEP);
3 readSensors();
4 actuateMotors();
5 }
Here is a complete example of using sensors and actuators together. The robot used here is
a DifferentialWheels using differential steering. It uses two proximity sensors (Dis-
tanceSensor) to detect obstacles.
164 CHAPTER 6. PROGRAMMING FUNDAMENTALS
1 #include <webots/robot.h>
2 #include <webots/differential_wheels.h>
3 #include <webots/distance_sensor.h>
4
5 #define TIME_STEP 32
6
7 int main() {
8 wb_robot_init();
9
10 WbDeviceTag left_sensor = wb_robot_get_device("left_sensor");
11 WbDeviceTag right_sensor = wb_robot_get_device("right_sensor"
);
12 wb_distance_sensor_enable(left_sensor, TIME_STEP);
13 wb_distance_sensor_enable(right_sensor, TIME_STEP);
14
15 while (1) {
16 wb_robot_step(TIME_STEP);
17
18 // read sensors
19 double left_dist = wb_distance_sensor_get_value(left_sensor
);
20 double right_dist = wb_distance_sensor_get_value(
right_sensor);
21
22 // compute behavior
23 double left = compute_left_speed(left_dist, right_dist);
24 double right = compute_right_speed(left_dist, right_dist);
25
26 // actuate wheel motors
27 wb_differential_wheels_set_speed(left, right);
28 }
29
30 return 0;
31 }
In the .wbt file, it is possible to specify arguments that are passed to a controller when it starts.
They are specified in the controllerArgs field of the Robot, Supervisor or Dif-
ferentialWheels node, and they are passed as parameters of the main() function. For
example, this can be used to specify parameters that vary for each robot’s controller.
For example if we have:
6.1. CONTROLLER PROGRAMMING 165
Robot {
...
controllerArgs "one two three"
...
}
and if the controller name is ”demo”, then this sample controller code:
1 #include <webots/robot.h>
2 #include <stdio.h>
3
4 int main(int argc, const char *argv[]) {
5 wb_robot_init();
6
7 int i;
8 for (i = 0; i < argc; i++)
9 printf("argv[%i]=%s\n", i, argv[i]);
10
11 return 0;
12 }
will print:
argv[0]=demo
argv[1]=one
argv[2]=two
argv[3]=three
10 WbDeviceTag ds = wb_robot_get_device("my_distance_sensor");
11 wb_distance_sensor_enable(ds, TIME_STEP);
12
13 while (wb_robot_step(TIME_STEP) != -1) {
14 double dist = wb_distance_sensor_get_value();
15 printf("sensor value is %f\n", dist);
16 }
17
18 // Webots triggered termination detected!
19
20 saveExperimentData();
21
22 wb_robot_cleanup();
23
24 return 0;
25 }
In some cases, it is up to the controller to make the decision of terminating the simulation. For
example in the case of search and optimization algorithms: the search may terminate when a
solution is found or after a fixed number of iterations (or generations).
In this case the controller should just save the experiment results and quit by returning from the
main() function or by calling the exit() function. This will terminate the controller process
and freeze the simulation at the current simulation step. The physics simulation and every robot
involved in the simulation will stop.
1 // freeze the whole simulation
2 if (finished) {
3 saveExperimentData();
4 exit(0);
5 }
If only one robot controller needs to terminate but the simulation should continue with the other
robots, then the terminating robot should call wb robot cleanup() right before quitting:
1 // terminate only this robot controller
2 if (finished) {
3 saveExperimentsData();
4 wb_robot_cleanup();
5 exit(0);
6 }
Note that the exit status as well as the value returned by the main() function are ignored by
Webots.
6.1. CONTROLLER PROGRAMMING 167
Creating shared libraries can be very useful to share code between controllers and/or plugins.
There are several ways to do so, but we recommend to place them into a subdirectory of the
libraries directory of your project. Indeed the environment variables of the controllers
are modified to include these paths into your [[DY]LD LIBRARY ]PATH environment variable
(depending on the OS). Moreover the main Makefile (WEBOTS HOME/resources/Make-
[Link]) used to compile Webots controllers is able to create shared libraries and to
link easily with the Controller libraries, ODE or the Qt framework.
A good example of this is the Qt utility library located there: WEBOTS HOME/resources/pro-
jects/libraries/qt utils
If for some reason shared libraries cannot be in the libraries directory, the WEBOTS LI-
BRARY PATH environment variable will be very helpful. The paths it contains will be added
at the beginning of the library search path([[DY]LD LIBRARY ]PATH) when starting the con-
troller.
For some projects it will be necessary to define or change variables defined in your environment.
They can be changed in the settings of the computer but it may last only for the current session
or create conflict with other applications or projects. Webots offers an elegant solution to this.
A configuration file named [Link] can be added to the controller directory. Any envi-
ronment variable defined in this file will be loaded to the environment each time the controller
starts.
This configuration file uses the standard INI template that is really simple and easy to write and
read. It contains pairs of key and value that can be inside [sections]. Comments can be written
on a line after using a semicolon ’;’ character.
Environment variables in this file can contain references to other environment variables using
this syntax : $(MY VARIABLE NAME). They will be automatically replaced by the actual value
already existing in the environment. The Webots [Link] supports 7 sections:
• [environment variables]
168 CHAPTER 6. PROGRAMMING FUNDAMENTALS
Environment variables defined in this section will also be added to the environment on
every platform but they will be written directly with no syntax change. It’s a good place
for variables that don’t contain any path.
The [Link] file may also contain language specific sections, named [java], [python]
and [matlab]. Each of this section may include two keys, namely COMMAND and OPTIONS.
The COMMAND key allows you to define a specific version of the language interpreter whereas
the OPTIONS key allows you to specific options that will be passed immediately to the language
interpreter. For example:
1 ; [Link] for a Python controller on Mac OS X
2
3 [python]
4 COMMAND = /opt/local/bin/python2.7
5 OPTIONS = -m [Link]
In the above example, the resulting command issued by Webots will be: /opt/local/bin/python2.7
-m [Link] my [Link] possibly followed by the value of the
controllerArgs field of the corresponding Robot node.
1 ; [Link] for a Java controller on Windows
2
3 [environment variables with relative paths]
4 CLASSPATH = ../lib/[Link]
5
6 [java]
7 COMMAND = [Link]
8 OPTIONS = -Xms6144k
The programming examples provided here are in C, but same concepts apply to C++/Java/Python/Matlab.
170 CHAPTER 6. PROGRAMMING FUNDAMENTALS
6.2.1 Introduction
The Supervisor is a special kind of Robot. In object-oriented jargon we would say that
the Supervisor class inherits from the Robot class or that the Supervisor class extends
the Robot class. The important point is that the Supervisor node offers the wb supervi-
sor *() functions in addition to the regular wb robot *() functions. These extra functions
can only be invoked from a controller program associated with a Supervisor node, not with
a Robot or a DifferentialWheels node. Note that Webots PRO is required to create
Supervisor nodes or use the wb supervisor *() functions.
In the Scene Tree, a Supervisor node can be used in the same context where a Robot node
is used, hence it can be used as a basis node to model a robot. But in addition, the wb super-
visor *() functions can also be used to control the simulation process and modify the Scene
Tree. For example the Supervisor can replace human actions such as measuring the distance
travelled by a robot or moving it back to its initial position, etc. The Supervisor can also take
a screen shot or a video of the simulation, restart or terminate the simulation, etc. It can read or
modify the value of every fields in the Scene Tree, e.g. read or change the position of robots, the
color of objects, or switch on or off the light sources, and do many other useful things.
One important thing to keep in mind is that the Supervisor functions correspond to function-
alities that are usually not available on real robots; they rather correspond to a human intervention
on the experimental setup. Hence, the Robot vs. Supervisor distinction is intentional and
aims at reminding the user that Supervisor code may not be easily transposed to real robots.
Now let’s examine a few examples of Supervisor code.
The Supervisor is frequently used to record robots trajectories. Of course, a robot can find
its position using a GPS, but when it is necessary to keep track of several robots simultaneously
and in a centralized way, it is much simpler to use a Supervisor.
The following Supervisor code shows how to keep track of a single robot, but this can easily
be transposed to an arbitrary number of robots. This example code finds a WbNodeRef that
corresponds to the robot node and then a WbFieldRef that corresponds to the robot’s trans-
lation field. At each iteration it reads and prints the field’s values.
1 #include <webots/robot.h>
2 #include <webots/supervisor.h>
3 #include <stdio.h>
4
5 int main() {
6 wb_robot_init();
7
8 // do this once only
6.2. SUPERVISOR PROGRAMMING 171
Note that a Supervisor controller must include the supervisor.h header file in addition to
the robot.h header file. Otherwise the Supervisor works like a regular Robot controller
and everything that was explained in the ”Controller Programming” section does also apply to
”Supervisor Programming”.
As illustrated by the example, it is better to get the WbNodeRefs and WbFieldRefs only
once, at the beginning of the simulation (keeping the invariants out of the loop). The call to
wb supervisor node get from def() searches for an object named ”MY ROBOT” in
the Scene Tree. Note that the name in question is the DEF name of the object, not the name
field which is used to identify devices. The function returns a WbNodeRef which is an opaque
and unique reference to the corresponding Scene Tree node. Then the call to wb supervi-
sor node get field() finds a WbFieldRef in the specified node. The ”translation” field
represents the robot’s position in the global (world) coordinate system.
In the while loop, the call to wb supervisor field get sf vec3f() is used to read
the latest values of the specified field. Note that, unlike sensor or actuator functions, the wb su-
pervisor field *() functions are executed immediately: their execution is not postponed
to the next wb robot step() call.
measured and logged. Then the robot is moved (translation) back to its initial position (0, 0.5,
0) for the next evaluation. To move the robot we need the wb supervisor *() functions and
hence the base node of this robot in the Scene Tree must be a Supervisor and not a Robot.
1 #include <webots/robot.h>
2 #include <webots/supervisor.h>
3 #include <stdio.h>
4 #include <math.h>
5
6 #define TIME_STEP 32
7
8 int main() {
9 wb_robot_init();
10
11 // get handle to robot’s translation field
12 WbNodeRef robot_node = wb_supervisor_node_get_from_def("
MY_ROBOT");
13 WbFieldRef trans_field = wb_supervisor_node_get_field(
robot_node, "translation");
14
15 double a, b, t;
16 for (a = 0.0; a < 5.0; a += 0.2) {
17 for (b = 0.0; b < 10.0; b += 0.3) {
18 // evaluate robot during 60 seconds (simulation time)
19 for (t = 0.0; t < 60.0; t += TIME_STEP / 1000.0) {
20 actuateMotors(a, b, t);
21 wb_robot_step(TIME_STEP);
22 }
23
24 // compute travelled distance
25 const double *pos = wb_supervisor_field_get_sf_vec3f(
trans_field);
26 double dist = sqrt(pos[0] * pos[0] + pos[2] * pos[2]);
27 printf("a=%g, b=%g -> dist=%g\n", a, b, dist);
28
29 // reset robot position
30 const double INITIAL[3] = { 0, 0.5, 0 };
31 wb_supervisor_field_set_sf_vec3f(trans_field, INITIAL);
32 }
33 }
34
35 return 0;
36 }
As in the previous example, the trans field variable is a WbFieldRef that identifies the
translation field of the robot. In this example the trans field is used both for getting
6.3. USING NUMERICAL OPTIMIZATION METHODS 173
(wb supervisor field get sf vec3f()) and for setting (wb supervisor field -
set sf vec3f) the field’s value.
Please note that the program structure is composed of three nested for loops. The two outer
loops change the values of the a and b parameters. The innermost loop makes the robot walk
during 60 seconds. One important point here is that the call to wb robot step() is placed in
the innermost loop. This allows the motor positions to be updated at each iteration of the loop.
If wb robot step() was placed anywhere else, this would not work.
There are several approaches to using optimization algorithms in Webots. Most approaches need
a Supervisor and hence Webots PRO is usually required.
A numerical optimization can usually be decomposed in two separate tasks:
1. Running the optimization algorithm: Systematical Search, Random Search, Genetic Algo-
rithms (GA), Particle Swarm Optimization (PSO), Simulated Annealing, etc.
2. Running the robot behavior with a set of parameters specified by the optimization algo-
rithm.
One of the important things that needs to be decided is whether the implementation of these two
distinct tasks should go into the same controller or in two separate controllers. Let’s discuss both
approaches:
If your simulation needs to evaluate only one robot at a time, e.g. you are optimizing the lo-
comotion gait of a humanoid or the behavior of a single robot, then it is possible to have both
tasks implemented in the same controller; this results in a somewhat simpler code. Here is a
pseudo-code example for the systematical optimization of two parameters a and b using only
one controller:
1 #include <webots/robot.h>
2 #include <webots/supervisor.h>
3
4 #define TIME_STEP 5
5
6 int main() {
7 wb_robot_init();
174 CHAPTER 6. PROGRAMMING FUNDAMENTALS
8 double a, b, time;
9 for (a = 0.5; a < 10.0; a += 0.1) {
10 for (b = 0.1; b < 5.0; b += 0.5) {
11 resetRobot(); // move robot to initial position
12
13 // run robot simulation for 30 seconds
14 for (time = 0.0; time < 30.0; time += TIME_STEP / 1000.0)
{
15 actuateMotors(a, b, time);
16 wb_robot_step(TIME_STEP);
17 }
18
19 // compute and print fitness
20 double fitness = computeFitness();
21 printf("with parameters: %g %g, fitness was: %g\n", a, b,
fitness);
22 }
23 }
24
25 wb_robot_cleanup();
26 return 0;
27 }
In this example the robot runs for 30 simulated seconds and then the fitness is evaluated and
the robot is moved back to it initial position. Note that this controller needs to be executed
in a Supervisor in order to access the wb supervisor field *() functions that are
necessary to read and reset the robot’s position. So when using this approach, the robot must
be based on a Supervisor node in the Scene Tree. Note that this approach is not suitable to
optimize a DifferentialWheels robot, because due to the class hierarchy, a robot cannot
be a DifferentialWheels and a Supervisor at the same time.
If, on the contrary, your simulation requires the simultaneous execution of several robots, e.g.
swarm robotics, or if your robot is a DifferentialWheels, then it is advised to use two
distinct types of controller: one for the optimization algorithm and one for the robot’s behavior.
The optimization algorithm should go in a Supervisor controller while the robots’ behavior
can go in a regular (non-Supervisor) controller.
Because these controllers will run in separate system processes, they will not be able to access
each other’s variables. Though, they will have to communicate by some other means in order to
specify the sets of parameters that need to be evaluated. It is possible, and recommended, to use
Webots Emitters and Receivers to exchange information between the Supervisor and
the other controllers. For example, in a typical scenario, the Supervisor will send evaluation
6.3. USING NUMERICAL OPTIMIZATION METHODS 175
parameters (e.g., genotype) to the robot controllers. The robot controllers listen to their Re-
ceivers, waiting for a new set of parameters. Upon receipt, a robot controller starts executing
the behavior specified by the set of parameters. In this scenario, the Supervisor needs an
Emitter and each individual robot needs a Receiver.
Depending on the algorithms needs, the fitness could be evaluated either in the Supervisor or
in the individual robot controllers. In the case it is evaluated in the robot controller then the fitness
result needs to be sent back to the Supervisor. This bidirectional type of communication
requires the usage of additional Emitters and Receivers.
When using optimization algorithm, you will probably need to reset the robot after or before
each fitness evaluation. There are several approaches to resetting the robot:
Using the wb supervisor field set *() and wb supervisor simulation reset physics() func-
tions
You can easily reset the position, orientation and physics of the robot using the wb supervi-
sor field set...() and wb supervisor simulation reset physics() functions,
here is an example:
1 // get handles to the robot’s translation and rotation fields
2 WbNodeRef robot_node = wb_supervisor_node_get_from_def("
MY_ROBOT");
3 WbFieldRef trans_field = wb_supervisor_node_get_field(
robot_node, "translation");
4 WbFieldRef rot_field = wb_supervisor_node_get_field(robot_node,
"rotation");
5
6 // reset the robot
7 const double INITIAL_TRANS[3] = { 0, 0.5, 0 };
8 const double INITIAL_ROT[4] = { 0, 1, 0, 1.5708 };
9 wb_supervisor_field_set_sf_vec3f(trans_field, INITIAL_TRANS);
10 wb_supervisor_field_set_sf_rotation(rot_field, INITIAL_ROT);
11 wb_supervisor_simulation_reset_physics();
The drawback with the above method is that it only resets the robot’s main position and orien-
tation. This may be fine for some types of optimization, but insufficient for others. Although it
is possible to add more parameters to the set of data to be reset, it is sometimes difficult to reset
everything. Neither motor positions, nor the robot controller(s) are reset this way. The motor po-
sitions should be reset using the wb motor set position() and the robot controller should
be reset by sending a message from the supervisor process to the robot controller process (using
176 CHAPTER 6. PROGRAMMING FUNDAMENTALS
Webots Emitter / Receiver communication system). The robot controller program should
be able to handle such a message and reset its state accordingly.
This function restarts the physics simulation and all controllers from the very beginning. With
this method, everything is reset, including the physics and the motor positions and the controllers.
But this function does also restart the controller that called wb supervisor simulation -
revert(), this is usually the controller that runs the optimization algorithm, and as a conse-
quence the optimization state is lost. Hence for using this technique, it is necessary to develop
functions that can save and restore the complete state of the optimization algorithm. The op-
timization state should be saved before calling wb supervisor simulation revert()
and reloaded when the Supervisor controller restarts. Here is a pseudo-code example:
1 #include <webots/robot.h>
2 #include <webots/supervisor.h>
3
4 void run_robot(const double params[]) {
5 read_sensors(params);
6 compute_behavior(params):
7 actuate_motors(params);
8 }
9
10 void evaluate_next_robot() {
11 const double *params = optimizer_get_next_parameters();
12 ...
13 // run robot for 30 seconds
14 double time;
15 for (time = 0.0; time < 30.0; time += TIME_STEP / 1000.0) {
16 run_robot(params);
17 wb_robot_step(TIME_STEP);
18 }
19 ...
20 // compute and store fitness
21 double fitness = compute_fitness();
22 optimizer_set_fitness(fitness);
23 ...
24 // save complete optimization state to a file
25 optimizer_save_state("my_state_file.txt");
26 ...
27 // start next evaluation
28 wb_supervisor_simulation_revert();
29 wb_robot_step(TIME_STEP);
30 exit(0);
31 }
6.3. USING NUMERICAL OPTIMIZATION METHODS 177
32
33 int main() {
34 wb_robot_init();
35 ...
36 // reload complete optimization state
37 optimizer_load_state("my_state_file.txt");
38 ...
39 if (optimizer_has_more_parameters())
40 evaluate_next_robot();
41 ...
42 wb_robot_cleanup();
43 return 0;
44 }
If this technique is used with Genetic Algorithms for example, then the function optimizer -
save state() should save at least all the genotypes and fitness results of the current GA
population. If this technique is used with Particle Swarm Optimization, then the optimizer -
save state() function should at least save the position, velocity and fitness of all particles
currently in the swarm.
Finally, the last method is to start and quit the Webots program for each parameter evaluation.
This may sound like an overhead, but in fact Webots startup time is usually very short compared
to the time necessary to evaluate a controller, so this approach makes perfectly sense.
For example, Webots can be called from a shell script or from any type of program suitable for
running the optimization algorithm. Starting Webots each time does clearly revert the simulation
completely, so each robot will start from the same initial state. The drawback of this method is
that the optimization algorithm has to be programmed outside of Webots. This external program
can be written in any programming language, e.g. shell script, C, PHP, perl, etc., provided that
there is a way to call webots and wait for its termination, e.g. like the C standard system()
does. On the contrary, the parameter evaluation must be implemented in a Webots controller.
With this approach, the optimization algorithm and the robot controller(s) run in separate system
processes, but they must communicate with each other in order to exchange parameter sets and
fitness results. One simple way is to make them communicate by using text files. For example,
the optimization algorithm can write the genotypes values into a text file then call Webots. When
Webots starts, the robot controller reads the genotype file and carries out the parameter evalu-
ation. When the robot controller finishes the evaluation, it writes the fitness result into another
text file and then it calls the wb supervisor simulation quit() function to terminate
Webots. Then the control flow returns to the optimization program that can read the resulting
fitness, associate it with the current genotype and proceed with the next genotype.
Here is a possible (pseudo-code) implementation for the robot evaluation controller:
178 CHAPTER 6. PROGRAMMING FUNDAMENTALS
1 #include <webots/robot.h>
2 #include <webots/supervisor.h>
3
4 #define TIME_STEP 10
5
6 double genotype[GENOME_SIZE];
7
8 int main() {
9 wb_robot_init();
10 ...
11 genotype_read("[Link]", genotype);
12 ...
13 // run evaluation for 30 seconds
14 for (double time = 0.0; time < 30.0; time += TIME_STEP /
1000.0) {
15 read_sensors(genotype);
16 actuate_motors(time, genotype);
17 wb_robot_step(TIME_STEP);
18 }
19 ...
20 double fitness = compute_fitness();
21 fitness_save(fitness, "[Link]");
22 ...
23 wb_supervisor_simulation_quit();
24 wb_robot_step(TIME_STEP);
25 return 0;
26 }
You will find complete examples of simulations using optimization techniques in Webots dis-
tribution: look for the worlds called advanced_particle_swarm_optimization.wbt
and advanced_genetic_algorithm.wbt located in the WEBOTS_HOME/projects/
samples/curriculum/worlds directory. These examples are described in the Advanced
Programming Exercises of Cyberbotics’ Robot Curriculum1 .
6.4 C++/Java/Python
This section explains the main differences between the C API and the C++/Java/Python APIs.
1
[Link]
6.4. C++/JAVA/PYTHON 179
C++, Java and Python are object-oriented programming languages and therefore the correspond-
ing Webots APIs are organized in classes. The class hierarchy is built on top of the C API and
currently contains about 25 classes and 200 methods (functions).
The Java and Python APIs are automatically generated from the C++ API using SWIG. Therefore
the class and method names, as well as the number of parameters and their types, are very similar
in these three languages.
The naming convention of the C++/Java/Python classes and methods directly matches the C API
function names. For example, for this C function: double wb distance sensor get -
value(WbDeviceTag tag) there will be a matching C++/Java/Python method called get-
Value() located in a class called DistanceSensor. Usually the C++/Java/Python methods
have the same parameters as their C API counterparts, but without the WbDeviceTag parame-
ter.
class must extend the DifferentialWheels class. If in the Scene Tree a robot is of type
Supervisor, then the C++/Java/Python controller class must be derived from the Supervi-
sor class, etc.
As you can see in figure 6.2, both DifferentialWheels and Supervisor are subclasses
of the Robot class. Hence it is possible to call the Robot’s methods, such as, e.g., step()
or getLED(), from the DifferentialWheels and Supervisor controllers. But it is not
possible to call the Supervisor methods from a DifferentialWheels controller, and
vice versa. For example it won’t be possible to call simulationRevert() from a Differ-
entialWheels controller.
Generally, the user-defined controller class should have a run() function that implements the
main controller loop. That loop should contains a call to the Robot’s step() method. Then
the only responsibility of the controller’s main() function is to create an instance of the user-
defined controller class, call its run() method and finally delete (C++ only) the instance: see
examples below. Note that the controller should never create more than one instance of a derived
class, otherwise the results are undefined.
Note that unlike the C API, the C++/Java/Python APIs don’t have (and don’t need) functions like
wb robot init() and wb robot cleanup(). The necessary initialization and cleanup
routines are automatically invoked from the constructor and destructor of the base class.
In C++/Java/Python, each Webots device is implemented as a separate class, there is a Dis-
tanceSensor class, a TouchSensor class, a RotationalMotor class, etc. The various
6.4. C++/JAVA/PYTHON 181
devices instances can be obtained with dedicated methods of the Robot class, like getDis-
tanceSensor(), getTouchSensor(), etc. There is no WbDeviceTag in C++/Java/Python.
1 #include <webots/[Link]>
2 #include <webots/[Link]>
3 #include <webots/[Link]>
4
5 using namespace webots;
6
7 #define TIME_STEP 32
8
9 class MyRobot : public Robot {
10 private:
11 LED *led;
12 DistanceSensor *distanceSensor;
13
14 public:
15 MyRobot() : Robot() {
16 led = getLED("ledName");
17 distanceSensor = getDistanceSensor("distanceSensorName");
18 distanceSensor->enable(TIME_STEP);
19 }
20
21 virtual ˜MyRobot() {
22 // Enter here exit cleanup code
23 }
24
25 void run() {
26 // Main control loop
27 while (step(TIME_STEP) != -1) {
28 // Read the sensors
29 double val = distanceSensor->getValue();
30
31 // Process sensor data here
32
33 // Enter here functions to send actuator commands
34 led->set(1);
35 }
36 }
37 };
38
39 int main(int argc, char **argv) {
182 CHAPTER 6. PROGRAMMING FUNDAMENTALS
1 import [Link].*;
2
3 public class MyRobot extends Robot {
4 private LED led;
5 private DistanceSensor distanceSensor;
6 private static final int TIME_STEP = 32; // milliseconds
7
8 public MyRobot() {
9 super();
10 led = getLED("my_led");
11 distanceSensor = getDistanceSensor("my_distance_sensor");
12 [Link](TIME_STEP);
13 }
14
15 public void run() {
16 // main control loop
17 while (step(TIME_STEP) != -1) {
18 // Read the sensors, like:
19 double val = [Link]();
20
21 // Process sensor data here
22
23 // Enter here functions to send actuator commands, like:
24 [Link](1);
25 }
26
27 // Enter here exit cleanup code
28 }
29
30 public static void main(String[] args) {
31 MyRobot robot = new MyRobot();
32 [Link]();
33 }
34 }
6.5. MATLAB 183
6.5 Matlab
The MATLABTM API for Webots is very similar to the C API. The functions names are identical,
only the type and number of parameters differs slightly in some cases. The MATLABTM functions
and prototypes are described in Webots Reference Manual. Note that unlike with the C API, there
are no wb robot init() and wb robot cleanup() functions in the MATLABTM API.
The necessary initialization and cleanup are automatically carried out respectively before enter-
ing and after leaving the controller code.
If the MATLABTM code uses graphics, it is necessary to call the drawnow command somewhere
in the control loop in order to flush the graphics.
Here is a simple MATLABTM controller example:
1 % uncomment the next two lines to use the desktop
2 %desktop;
3 %keyboard;
4
5 TIME_STEP = 32;
184 CHAPTER 6. PROGRAMMING FUNDAMENTALS
6
7 my_led = wb_robot_get_device(’my_led’);
8 my_sensor = wb_robot_get_device(’my_sensor’);
9
10 wb_distance_sensor_enable(my_sensor, TIME_STEP);
11
12 while wb_robot_step(TIME_STEP) ˜= -1
13 % read the sensors
14 val = wb_distance_sensor_get_value(my_sensor);
15
16 % Process sensor data here
17
18 % send actuator commands
19 wb_led_set(my_led, 1);
20
21 % uncomment the next line if there’s graphics to flush
22 % drawnow;
23 end
The desktop command brings up the MATLABTM desktop. The keyboard stops the execu-
tion of the controller and gives control to the keyboard (K>> prompt). Then MATLABTM opens
your controller m-file in its editor and indicates that the execution is stopped at the keyboard
command. After that, the controller m-file can be debugged interactively, i.e., it is possible to
continue the execution step-by-step, set break points, watch variable, etc. While debugging, the
current values of the controller variables are shown in the MATLABTM workspace. It is possible
to continue the execution of the controller by typing return at the K>> prompt. Finally the
execution of the controller can be terminated with Ctrl-C key combination.
Once the controller is terminated, the connection with Webots remains active. Therefore it be-
comes possible to issue Webots commands directly at the MATLABTM prompt, for example you
can interactively issue commands to query the sensors, etc.:
>> wb_differential_wheels_set_speed(600, 600);
>> wb_robot_step(1000);
6.6. CONTROLLER PLUGIN 185
>> wb_gps_get_values(gps)
ans =
6.6.1 Fundamentals
Whatever its language, a controller executable is linked with the Webots controller library (lib-
Controller) at startup. A controller plugin is a shared library loaded dynamically (at runtime) by
libController after a specific event depending on its type.
The figure 6.3 shows an overview of the controller plugin system. In this figure, the dashed
arrows shows how the shared libraries are loaded, and the large dash lines represents an Inter-
Process Communication (IPC). The IPC between libController and Webots is a pipe (On Win-
dows this is a named pipe, and otherwise a local domain socket). The IPC between libRemote-
Control and the real robot is defined by the user (TCP/IP, Serial, etc.).
The system has been designed as follow. Every entities (the controller, the remote control library
and the robot window library) should only call the libController interface (Webots API) func-
tions. The controller should not be aware of its robot window and its real robot for modularity
reasons. The only exception is about the robot window library which can be aware of the re-
mote control library to initialise and monitor it. This can be done trough the libController API
186 CHAPTER 6. PROGRAMMING FUNDAMENTALS
through the wb robot get mode(), wb robot set mode() and the wb remote con-
trol custom function() functions. Of course these rules can be easily broken because
every entities runs into the same process. However we recommend to respect them to get a good
design.
The controller plugins have been designed to be written in C/C++, because the result should be a
dynamic library. However it’s certainly possible to write them in other languages using a C/C++
wrapper inbetween.
After its loading, some controller plugin functions (entry points) are called by libController. A
set of entry points have to be defined to let the controller plugin work smoothly. Some of these
entry points are required and some are optional.
The Robot node defines the location of the controller plugin through its robotWindow and its
remoteControl fields (cf. reference manual)
The controller plugin run in the main thread of the process (also known as GUI thread): the
same as the controller executable. This implies that if an entry point of a plugin is blocking, the
controller will also be blocked. And if the plugin crashes, the controller is also crashed.
The search algorithm to convert the robotWindow and the remoteControl to an existing path is
explained in the reference manual.
Each distributed shared library is built thanks to the main Makefile (the same as the one used to
build the controllers): WEBOTS HOME/resources/[Link]
The robotWindow field of the Robot node specifies a robot window (cf. documentation in the
reference manual).
6.6. CONTROLLER PLUGIN 187
The internal behavior of the wb robot step() call is the key point to understand how the
different entry points of the robot window plugin are called (pseudo-code):
188 CHAPTER 6. PROGRAMMING FUNDAMENTALS
1 wb_robot_step() {
2 wbw_write_actuators()
3 wbw_pre_update_gui()
4 write_request_to_webots_pipe()
5 wbw_update_gui() // returns when something on the pipe
6 read_request_to_webots_pipe()
7 wbw_read_sensors()
8 }
As the Qt libraries are included in Webots (used by the Webots GUI), and all our samples are
based on it, we recommend to choose also this framework to create your GUI. The Make-
[Link] mentioned above allows you to efficiently link with the Qt framework embed-
ded in Webots.
The Webots pipe handle (integer id) is available in the WEBOTS PIPE IN environment variable.
The Qt utility library helps you to initialize Qt correctly (pipe, window visibility, ...). Refer to
the next section for more information related with this library.
If the robot window cannot be loaded (bad path, bad initialization, etc.), a generic robot win-
dow is opened instead. This generic robot window displays several sensors and actuators. The
source code of this robot window is a good demonstrator of the robot window plugin abilities.
All the source code is located there: WEBOTS HOME/resources/projects/plugin-
s/robot windows/generic window
Other samples can be found:
WEBOTS HOME/projects/robots/e-puck/plugins/robot windows/botstudio
WEBOTS HOME/projects/robots/e-puck/plugins/robot windows/e-puck win-
dow
In order to facilitate the creation of robot window plugins using the Qt framework, Webots has a
utility library allowing to hide the complexity of the management of the robot windows.
This library contains various classes including a subclass of QMainApplication managing the
pipe events, a subclass of QMainWindow dealing with the close events, a class to handle Webots
standard paths, and a collection of widgets to display the Webots devices. The source code of
the generic robot window is a good example illustrating how to use this library.
The location of the qt utility library is WEBOTS HOME/resources/projects/libraries/qt -
utils
6.6. CONTROLLER PLUGIN 189
The motion is stored in a motion file in a user-readable format. The controller API allows to
play easily the motion files on your robot. You can get the complete motion API in the reference
manual.
The motion editor (cf. the figure 6.4) is a GUI helping to create motions which can be played
by a robot. It is implemented in the Qt utils library, and is embedded inside the generic robot
window plugin. This implies that the motion editor is accessible only if the robot is linked (cf.
the Robot::robotWindow field) with either the generic window, or on a window using the Qt utils
library’s corresponding widget.
In the motion editor different fonts and colors are used to identify the status of poses and motor
states: modified items are displayed using bold font, disabled states are written in gray, and items
with values outside the valid motor position range are written in red.
190 CHAPTER 6. PROGRAMMING FUNDAMENTALS
A remote-control plugin allow to simply and efficiently create an interface using the Webots API
to communicate with a real robot. The main purpose of a remote-control library is to wrap all
the Webots API functions used by the robot with a protocol communicating to the real robot.
Generally, a program (client) runs on the real robot, and decodes the communication protocol to
dialog with the real robot devices.
The remote-control library is initialized when an entity calls the wb robot set mode() lib-
Controller function. This entity is typically libRobotWindow, because it’s quite convenient to
use the GUI to initialize the communication (i.e. entering the IP address of the robot, etc.)
There are two entry points to the remote-control library:
The WbrInterface structure has several functions (mandatory) which have to be mapped to
let the remote-control library run smoothly. Here they are:
As said above, all the Webots API functionalities that should work with the real robot have to be
wrapped into the remote-control library. To achieve this:
• The internal state of the libController has to be setup to match with the current state of the
robot.
Typically, when the value of a sensor is known the corresponding wbr sensor set -
value() has to be called.
The complete definition of the remote control API and of the WbrInterface structure is
contained in WEBOTS HOME/include/controller/c/webots/remote control.h
For example, if you want to be able to use the distance sensor of the real robot, you have to wrap
the wbr set refresh rate() function (to set the internal state of the remote control library
to read this distance sensor only when required), and to call wbr distance sensor set -
value() into the remote-control library when the distance sensor is refreshed (typically into
the wbr robot step() function).
A complete sample (communicating with the e-puck robot using bluetooth) can be found in this
directory:
WEBOTS HOME/projects/robots/e-puck/plugins/remote controls/e-puck -
bluetooth
Tutorials
The aim of this chapter is to explain the fundamental concepts of Webots required to create your
own simulations. Learning is focused on the modeling of robots and of their environment, as well
as on the programming of robot controllers. You will also learn where to find the documentation
to go further.
This chapter is suitable for absolute beginners in Webots. A background in programming is nev-
ertheless required. The examples are written in C language. If you are not familiar with the C
language, you should be able to understand this chapter anyway, because the C programs below
are very simple. Except for programming, you don’t need any particular knowledge to go through
the tutorials included in this chapter. However a basic background knowledge in robotics, mathe-
matics, modeling and tree representation might turn out to be helpful. Experienced Webots users
may skip the first tutorials. However, we would recommend them to read at least the introduction
and conclusion of these tutorials.
Each section of this chapter (except the first one and the last one) is a tutorial. Each tutorial
has a precise educational objective explained in the first paragraph. The acquired concepts are
then summarized in the conclusion subsection. A tutorial is designed as a sequence of interactive
steps. The knowledge acquired in a tutorial is often required to continue with the next tutorial.
Therefore we strongly recommend you to respect their natural order. Moreover we recommend
you to ensure you understood all the concepts of a tutorial before proceeding further.
A Webots PRO license or a 30-days trial license is required to follow all the tutorials. However,
an EDU license is sufficient to follow about 95% of this chapter, as it won’t allow you to program
supervisor processes and physics plugins.
The last section will provide you with some hints to address problems that are not covered in this
chapter.
The solutions of the tutorials are located into the WEBOTS_HOME/projects/samples/
tutorials subdirectory of the Webots installation directory.
We hope you will enjoy your first steps with Webots. Meanwhile, we would really appreciate to
receive your feedback regarding this chapter.
193
194 CHAPTER 7. TUTORIALS
7.1 Prerequisites
In this section, you will learn how to setup your Webots environment. It is obviously a necessary
step to get started with the tutorials.
The first step is to create a directory which will contain all your files related to Webots.
From your operating system interface, choose a location on your hard disk
where you have the writing rights (for example, your [My]Documents di-
rectory). Create there a directory that will contain all your Webots projects,
and name it my_webots_projects.
As mentioned earlier in this chapter, the solutions of the tutorials are included
in the WEBOTS_HOME/projects/samples/tutorials subdirectory
of Webots. Don’t look at it now! Hopefully, your own tutorials directory
should be pretty similar to that one at the end.
In Webots, open the wizard by selecting the Wizards > New Project Directory...
menu item. From this wizard, follow the instructions to create a new project
named tutorials in the my_webots_projects directory created be-
fore.
From your desktop, open the project directory and observe its subdirectories.
We will soon explain the purpose of each directory.
Figure 7.1: The Webots main window splits into four dockable subwindows: the scene tree view
on the left hand side (including a panel at the bottom for editing fields values), the 3D view in
the center, the text editor on the right hand side, and the console at bottom of the window. Note
that some of these subwindows have a toolbar with buttons. The main menus appear on the top
of the main window. The virtual time counter and the speedometer are displayed in the right part
of the 3D view toolbar. The status text is displayed in the bottom left of the main window.
Figure 7.2: What you should see at the end of the tutorial.
7.2. TUTORIAL 1: YOUR FIRST SIMULATION IN WEBOTS (20 MINUTES) 197
In this subsection, we will create a new simulation. The content of a simulation is stored in a
world file. This world file contains all the information related to your simulation, i.e. where are
the objects, how do they look like, how do they interact with each other, what is the color of the
sky, where is the gravity vector, etc.
Pause the current simulation by clicking on the Pause button of the 3D view.
The simulation is paused if the virtual time counter on the 3D view toolbar is
stable.
Create a new world by selecting the File > New World menu item.
A new world is now open. For now, the 3D window displays a black screen. This is normal
because the scene tree contains only the following fundamental nodes: WorldInfo (contain-
ing misc global parameters), Viewpoint (defining the main camera parameters) and Back-
ground (defining the background color). As no light and no 3D object are defined, the entire
scene is empty and unlit, and so black.
The first step is about to modify the background color.
Modify the background color, by setting up the skyColor field of the Back-
ground node. Choose a blue color (e.g. red = 0.4, green = 0.7 and blue =
1.0) using the color picker at the bottom of the scene tree. The background of
the 3D view should be modified accordingly.
Select the last node of the scene tree view (Background). Click on the Add
button at the top of the scene tree view. In the open dialog box, and choose
New node > DirectionalLight. The new node has been added but
as there is no 3D object in the scene, the result of this operation is not visible
yet.
Now we would like to add some environment (a floor and some walls). A predefined high-level
node called RectangleArena is designed to do this task quickly.
Select the last node of the scene tree view (DirectionalLight). Click
on the Add button. In the open dialog box, choose PROTO (Webots) >
objects > floors > RectangleArena. The new node has been
added and is appearing far away. Use the left click and the wheel of the
mouse in the 3D view to choose a better viewpoint.
In the scene tree, the fields are displayed in blue if they differ from their default
values.
Now your environment should look like the one depicted in the figure 7.1.
Save the new world into your project by selecting the File > Save
World As... menu item. Using the dialog box save the world
into the my_webots_projects/tutorials/worlds/my_first_
[Link] file location.
Revert the simulation by selecting the File > Revert World menu item.
You can change the viewpoint of the 3D view by using the mouse buttons (left
button, right button and the wheel).
7.2. TUTORIAL 1: YOUR FIRST SIMULATION IN WEBOTS (20 MINUTES) 199
Webots nodes stored in world files are organized in a tree structure called
the scene tree. The scene tree can be viewed in two subwindows of the main
window: the 3D view (at the center of the main window) is the 3D represen-
tation of the scene tree and the scene tree view (on the left) is the hierarchical
representation of the scene tree. The scene tree view is where the nodes and
the fields can be modified.
In the 3D view, click on the floor to selected it. When it is selected the floor is
surrounded by white lines and the corresponding node is selected in the scene
tree view. Now click on the blue sky to unselect the floor.
The e-puck is a small robot having differential wheels, 10 LEDs, and several sensors including 8
distance sensors and a camera. In this tutorial we are only interested in using its wheels. We will
learn how to use some other e-puck features in the other tutorials.
Now we are going to add an e-puck model to the world. Make sure that the simulation is paused
and that the virtual time elapsed is 0.
When a Webots world is modified with the intention of being saved, it is funda-
mental that the simulation is first paused and reverted to its initial state, i.e.
the virtual time counter on the 3D view toolbar should show [Link].
Otherwise at each save, the position of each 3D objects can accumulate er-
rors. Therefore, any modification of the world should be performed in that
order: pause, revert, modify and save the simulation.
As we don’t need to create the e-puck robot from scratch, we will just have to import a special E-
puck node (in fact: a PROTO node as the RectangleArena we introduced before). A PROTO
is an abstract assemblage of several nodes. PROTO nodes are defined in separate .proto, but
this will be explained in more details later. For now consider the E-puck node as a black box that
contains all the necessary nodes to define a e-puck robot.
Select the last node of the scene tree view (called RectangleArena). In
order to add the E-puck node, click on the Add button at the top of the
scene tree view. In the open dialog box, and choose PROTO (Webots) >
robots > e-puck > E-puck (DifferentialWheels). Then
save the simulation.
200 CHAPTER 7. TUTORIALS
Now if you run the simulation, the robot moves: that’s because the robot uses
a default controller with that behavior. Please pause and revert the simulation
before going on.
You can change the robot’s position in the 3D view using the translation and
rotation handles (see subsubsection 2.4.3).
Alternatively, the following keyboard shortcuts are available:
SHIFT + left-clicking + drag to move the robot parallel to the floor;
SHIFT + mouse-wheel to move the robot up or down.
Finally, it is possible to add a force to the robot: CTRL + ALT + left-clicking
+ drag.
Starting the simulation by pressing the Run button will make Webots running
the simulation as fast as possible. In order to obtain a real-time simulation
speed, the Real-Time button has to be pressed.
Now we are going to modify the world and decrease the step of the physics simulation: this will
increase the accuracy of the simulation.
In the scene tree view, expand the WorldInfo node (the first node). Set its
basicTimeStep field to 16. Then save the simulation.
Just after you added the E-puck node, a black window appeared in the upper left corner of the 3D
view. It shows the content of Camera nodes, but it will stay black until not explicitly used during
a simulation. In order to hide it, you simply have to set the pixelSize equal to 0. Then, if you
want to re-enable them, you have to set this field value to a positive number. Detailed definitions
can be found in chapter 3 of the Reference Manual1 .
In this tutorial we will not use the Camera devices of the E-puck. So we can
hide the window by expanding the E-puck node and setting the fields cam-
era pixelSize to 0. Don’t forget to revert the simulation before changing
the values and to save it after the modifications.
1
[Link]
7.2. TUTORIAL 1: YOUR FIRST SIMULATION IN WEBOTS (20 MINUTES) 201
Other languages than C are available but may require a setup. Please refer
to the language chapter to setup the other languages (see chapter 4).
Create a new C controller called e-puck go forward using the Wizards > New
Robot Controller... menu. This will create a new e-puck_go_forward
directory in my_webots_projects/tutorials/controllers. Se-
lect the option asking you to open the source file in the text editor.
The new C source file is displayed in Webots text editor window. This C file can be compiled
without any modification, however the code has no real effect. We will now link the E-puck node
with the new controller before modifying it.
Link the E-puck node with the e-puck go forward controller. This can be
done in the scene tree view by selecting the controller field of the E-puck
node, then use the field editor at the bottom of the scene tree view: push
the Select... button and then select e-puck go forward in the list. Once the
controller is linked, save the world.
202 CHAPTER 7. TUTORIALS
Save the modified source code (File > Save Text File), and compile it (Build
> Build). Fix any compilation error if necessary. When Webots proposes to
revert the simulation, choose Yes.
7.2.4 Conclusion
We hope you enjoyed creating your first simulation. You have been able to set up your environ-
ment, to add a robot and to program it. The important thing is that you learnt the fundamental
concepts summarized below:
A Webots world is made of nodes organized in a VRML-like tree structure. A world is saved
in a .wbt file stored in a Webots project. The project also contains the robot controllers which
are the programs that define the robots behavior. Robot controllers can be written in C (or other
languages). C controllers have to be compiled before they can be executed. Controllers are linked
to robots via the controller fields of the robot nodes.
In order to define an object as static, its physics node has not to be set
(NULL).
204 CHAPTER 7. TUTORIALS
Other pre-built floors are available in the Webots objects library. We will now delete the default
arena and add a simple floor that we will manually surround the walls later in this this tutorial.
To remove the RectangleArena, select it in the scene tree view and press
the Delete button located in the toolbar.
The newly added Floor PROTO has a default size of 10mx10m, but it is possible to adjust its
size, its position and texture by changing the corresponding fields.
In the scene tree view select and expand the Floor. Modify the size fields
and set it to {1, 1} to resize it to 1mx1m.
This subsection introduces the most important node in Webots: the Solid node. But let’s start
with a definition.
The physics engine of Webots is designed for simulating rigid bodies. An important steps, when
designing a simulation, is to break up the various entities into undividable rigid bodies.
In Webots there is a direct matching between a rigid body and a Solid node. A
Solid node (or a node which inherits the Solid node) will be created for each
rigid body.
7.3. TUTORIAL 2: MODIFICATION OF THE ENVIRONMENT (20 MINUTES) 205
Figure 7.3: The simplest model of a rigid body in Webots having a graphical representation
(Shape), a physical bound (boundingObject) and being in the dynamical environment (Physics).
To define a rigid body, you will have to create a Solid node. Inside this node you will find differ-
ent subnodes corresponding to the characteristics of the rigid body. The figure 7.3 depicts a rigid
body and its subnodes. The graphical representation of the Solid is defined by the Shape nodes
populating its children list. The collision bounds are defined by its boundingObject
field. The graphical representation and the collision shape are often but not necessarily identical.
Finally the physics field defines if the object belongs to the dynamical or to the statical envi-
ronment. All these subnodes are optional, but the physics field needs the boundingObject
to be defined.
The Geometry box (in figure 7.3) stands for any kind of geometrical primitive. In fact it can be
substituted by a Sphere, a Box, a Cylinder, etc.
We will now add a ball to the simulation. That ball will be modeled as a rigid body as shown in
the figure 7.3. As Geometry nodes we will use Spheres.
In the scene tree view, select the last node and add a Solid node using the
Add button. Similarly select the children field of the Solid node, and add
a Shape node to it. Add a Sphere node as the geometry field of the just
created Shape node. Add another Sphere node to the boundingObject
field of the Solid. Finally add a Physics node to the physics field of the
Solid. By modifying the translation field of the Solid node, place the
ball in front of the robot (at {0, 0.1, -0.2} for example). Save the simulation.
The result is depicted in figure 7.4.
206 CHAPTER 7. TUTORIALS
When the simulation is started, the ball hits the floor. You can move the ball
by adding a force to it (CTRL + ALT + left-click + drag). The contact points
between the ball and the floor can be displayed as cyan lines by enabling the
View > Optional Rendering > Show Contact Points menu item.
7.3.5 Geometries
To define the ball, we used the Sphere node in two different contexts: for the graphical repre-
sentation (children) and to define the physical bounds (boundingObject). All Geometry
node (such as the Sphere node) can be used in a graphical context. However, only a subset
of them can be used in a physical context. Take a look at the schema of the chapter 2 of the
Reference Manual to now which primitive you can use.
We want now to reduce the size of the Sphere and to increase its graphical quality by increasing
the number of triangles used to represent it.
For each Sphere node defining the ball, set its radius field to 0.05 and its
subdivision field to 2. Refer to the Reference Manual to understand what
the subdivision field stands for.
The DEF-USE mechanism allows to define a node in one place and to reuse
that definition elsewhere in the Scene Tree. This avoids the duplication of
identical nodes and this allows to modify several nodes at the same time.
Here is how this works: first a node is labeled with a DEF string, and then
copies of this node are reused elsewhere with the USE keyword. Only the
fields of the DEF node can be edited, the fields of the USE nodes assume
similar values. This mechanism is dependent on the apparition order of the
nodes in the world file, because the DEF node should appear first.
The two Sphere definitions that we have used earlier to define the ball, are redundant. We will
now merge these two Spheres into only once using the DEF-USE mechanism.
Select the first Sphere node (the child of the Shape) in the scene tree view.
The field editor of the scene tree view allows you to enter the DEF string.
Enter ”BALL GEOMETRY”. Select the boundingObject field (containing
the second Sphere node), and delete it by using the Reset to default button.
Then click on the Add button, and select the USE > BALL GEOMETRY in
the dialog box. The result is shown in figure 7.5.
Now, changing the radius field of the first Sphere node does also modify
the boundingObject.
For convenience, the boundingObject field accepts also the Shape node
(rather than the Sphere node directly). It would be also possible to use the
same DEF-USE mechanism at the Shape level as shown in figure 7.6. For now
the best advantage is to use this Shape also directly for graphical purposes.
Later this will turn out to be very useful for some sensors.
In order to verify your progression, implement by yourself four walls to surround the environ-
ment. The walls have to be defined statically to the environment, and use as much as possible
the DEF-USE mechanism at the Shape level rather than at the Geometry level. Indeed it’s more
convenient to add an intermediate Shape node in the boundingObject field of the Solid node.
The best Geometry primitive to implement the walls is the Box node. Only one Shape has to be
defined for all the walls. The expected result is shown in figure 7.7.
208 CHAPTER 7. TUTORIALS
Figure 7.5: DEF-USE mechanism on the Sphere node called ”BALL GEOMETRY”.
Figure 7.7: The simulation state at the end of this second tutorial.
Add four walls without physics and using only one definition of the Shape
node.
7.3.8 Efficiency
7.3.9 Conclusion
At the end of this tutorial, you are able to create simple environments based on rigid bodies.
You are able to add nodes from the scene tree view and to modify their fields. You have a more
precise idea of what are the Solid, the Physics, the Shape, the Sphere and the Box nodes. You
saw also the DEF-USE mechanism that allows to reduce node redundancy of the scene tree.
210 CHAPTER 7. TUTORIALS
From the results of the previous tutorial, create a new simulation called
[Link] by using the File > Save World As... menu.
7.4.2 Lights
The lighting of a world is determined by light nodes. There are three types of
light nodes: the DirectionalLight, the PointLight and the SpotLight. A Direc-
tionalLight simulates a light which is infinitely far (ex: the sun), a PointLight
simulates light emitted from a single point (ex: a light bulb), and a Spot-
Light simulates a conical light (ex: a flashlight). Each type of light node can
cast shadows. You can find their complete documentation in the Reference
Manual.
Your simulation is currently lighted by a PointLight node at the top of the scene. We want to
replace this light node by a DirectionalLight node casting shadows.
Remove the PointLight node, and add a new DirectionalLight node instead.
Set its ambientIntensity field to 0.5, its castShadows field to TRUE,
and its direction field to {1, -2, 1}.
7.4. TUTORIAL 3: APPEARANCE (15 MINUTES) 211
The Appearance node of the Shape node determines the graphical appear-
ance of the object. Among other things, this node is responsible for the color
and texture of objects.
In the Shape node representing graphically the first wall, add an Appearance
node to the appearance field. Then add a Material node to the material
field of the freshly created Appearance node. Set its diffuseColor field
to blue using the color selector. If the DEF-USE mechanism of the previous
tutorial has been correctly implemented, all the walls should turn blue.
The texture URLs must be defined either relative to the worlds direc-
tory of your project directory or relative to the default project directory
WEBOTS_HOME/projects/default/worlds. In the default project
directory you will find textures that are available for every world.
Open the [Link] texture in an image viewer while you observe how it
is mapped onto the Sphere node in Webots.
Figure 7.8: Simulation after having setup the Light and the Appearance nodes.
View the simulation in wireframe mode by using the View > Wireframe Ren-
dering menu item. Then restore the plain rendering mode: View > Plain Ren-
dering.
7.4.6 Conclusion
In this tutorial, you have learnt how to set up a good looking environment using the Appearance
node and the light nodes.
You can go further on this topic by reading the detailed description of these nodes in the Refer-
ence Manual. The subsection 9.3.7 will give you a method to efficiently setup these nodes.
devices, how to get the sensor values, how to command the actuators, and how to program a
simple feedback loop.
This chapter only addresses the correct usage of Webots functions. The study of robotics algo-
rithms is beyond the goals of this tutorial and so this won’t be addressed here. Some rudimentary
programming knowledge is required to tackle this chapter (any C tutorial should be a sufficient
introduction). At the end of the chapter, links to further robotics algorithmics are given.
Controller programming requires some information related to the e-puck model. For doing the
collision avoidance algorithm, we need to read the values of its 8 infra-red distance sensors
located around its turret, and we need to actuate its two wheels. The way that the distance
sensors are distributed around the turret and the e-puck direction are depicted in figure 7.9.
The distance sensors are modeled by 8 DistanceSensor nodes in the hierarchy of the robot. These
nodes are referenced by their name fields (from ”ps0” to ”ps7”). We will explain later how these
nodes are defined. For now, simply note that a DistanceSensor node can be accessed through the
related module of the Webots API (through the webots/distance_sensor.h include file).
The values returned by the distance sensors are scaled between 0 and 4096 (piecewise linearly to
the distance), while 4096 means that a big amount of light is measured (an obstacle is close) and
0 means that no light is measured (no obstacle).
In the same way, the e-puck root node is a DifferentialWheel node and can be access by the
webots/differential_wheel.h include file. The speed is given in a number of tick-
s/seconds where 1000 ticks correspond to a complete rotation of the wheel. The values are
clamped between -1000 and 1000.
214 CHAPTER 7. TUTORIALS
Figure 7.9: Top view of the e-puck model. The green arrow indicates the front of the robot. The
red lines represent the directions of the infrared distance sensors. The string labels corresponds
to the distance sensor names.
The controller API is the programming interface that gives you access to
the simulated sensors and actuators of the robot. For example, including the
webots/distance_sensor.h file allows to use the wb distance -
sensor *() functions and with these functions you can query the values of
the DistanceSensor nodes. The documentation on the API functions can be
found in Chapter 3 of the Reference Manual together with the description of
each node.
We would like to program a very simple collision avoidance behavior. You will program the
robot to go forwards until an obstacle is detected by the front distance sensors, and then to turn
towards the obstacle-free direction. For doing that, we will use the simple feedback loop depicted
in the UML state machine in figure 7.10.
At the beginning of the controller file, add the include directives correspond-
ing to the Robot, the DifferentialWheels and the DistanceSensor nodes in
order to be able to use the corresponding API (documented in chapter 3 of
the Reference Manual):
1 #include <webots/robot.h>
2 #include <webots/differential_wheels.h>
3 #include <webots/distance_sensor.h>
Just after the include statements add a macro that defines the duration of
each physics step. This macro will be used as argument to the wb robot -
step() function, and it will also be used to enable the devices. This dura-
tion is specified in milliseconds and it must be a multiple of the value in the
basicTimeStep field of the WorldInfo node.
1 #define TIME_STEP 64
The function called main() is where the controller program starts execu-
tion. The arguments passed to main() are given by the controllerArgs
field of the Robot node. The Webots API has to be initialized using the wb -
robot init() function and it has to be cleaned up using the wb robot -
cleanup() function.
216 CHAPTER 7. TUTORIALS
Just after the comment ”// initialize devices”, get and enable the distance
sensors as follows:
1 // initialize devices
2 int i;
3 WbDeviceTag ps[8];
4 char ps_names[8][4] = {
5 "ps0", "ps1", "ps2", "ps3",
6 "ps4", "ps5", "ps6", "ps7"
7 };
8
9 for (i=0; i<8; i++) {
10 ps[i] = wb_robot_get_device(ps_names[i]);
11 wb_distance_sensor_enable(ps[i], TIME_STEP);
12 }
In the main loop, just after the comment ”// read sensors outputs”, read the
distance sensor values as follows:
1 // read sensors outputs
2 double ps_values[8];
3 for (i=0; i<8 ; i++)
4 ps_values[i] = wb_distance_sensor_get_value(ps[
i]);
In the main loop, just after the comment ”// process behavior”, detect if a
collision occurs (i.e. the value returned by a distance sensor is bigger than a
threshold) as follows:
1 // detect obstacles
2 bool left_obstacle =
3 ps_values[0] > 100.0 ||
4 ps_values[1] > 100.0 ||
5 ps_values[2] > 100.0;
6 bool right_obstacle =
7 ps_values[5] > 100.0 ||
8 ps_values[6] > 100.0 ||
9 ps_values[7] > 100.0;
218 CHAPTER 7. TUTORIALS
Finally, use the information about the obstacle to actuate the wheels as fol-
lows:
1 // init speeds
2 double left_speed = 500;
3 double right_speed = 500;
4 // modify speeds according to obstacles
5 if (left_obstacle) {
6 // turn right
7 left_speed -= 500;
8 right_speed += 500;
9 }
10 else if (right_obstacle) {
11 // turn left
12 left_speed += 500;
13 right_speed -= 500;
14 }
15 // write actuators inputs
16 wb_differential_wheels_set_speed(left_speed,
right_speed);
Compile your code by selecting the Build > Build menu item. Compilation
errors are displayed in red in the console. If there are any, fix them and retry
to compile. Revert the simulation.
14 // internal variables
15 int i;
16 WbDeviceTag ps[8];
17 char ps_names[8][4] = {
18 "ps0", "ps1", "ps2", "ps3",
19 "ps4", "ps5", "ps6", "ps7"
20 };
21
22 // initialize devices
23 for (i=0; i<8 ; i++) {
24 ps[i] = wb_robot_get_device(ps_names[i]);
25 wb_distance_sensor_enable(ps[i], TIME_STEP);
26 }
27
28 // feedback loop
29 while (1) {
30 // step simulation
31 int delay = wb_robot_step(TIME_STEP);
32 if (delay == -1) // exit event from webots
33 break;
34
35 // read sensors outputs
36 double ps_values[8];
37 for (i=0; i<8 ; i++)
38 ps_values[i] = wb_distance_sensor_get_value(ps[i]);
39
40 // detect obstacles
41 bool left_obstacle =
42 ps_values[0] > 100.0 ||
43 ps_values[1] > 100.0 ||
44 ps_values[2] > 100.0;
45 bool right_obstacle =
46 ps_values[5] > 100.0 ||
47 ps_values[6] > 100.0 ||
48 ps_values[7] > 100.0;
49
50 // init speeds
51 double left_speed = 500;
52 double right_speed = 500;
53
54 // modify speeds according to obstacles
55 if (left_obstacle) {
56 left_speed -= 500;
57 right_speed += 500;
58 }
220 CHAPTER 7. TUTORIALS
59 else if (right_obstacle) {
60 left_speed += 500;
61 right_speed -= 500;
62 }
63
64 // write actuators inputs
65 wb_differential_wheels_set_speed(left_speed, right_speed);
66 }
67
68 // cleanup the Webots API
69 wb_robot_cleanup();
70 return 0; //EXIT_SUCCESS
71 }
7.5.5 Conclusion
Here is a quick summary of the key points you need to understand before going on:
• The controller entry point is the main() function like any standard C program.
• No Webots function should be called before the call of the wb robot init() function.
• The last function to call before leaving the main function is the wb robot cleanup()
function.
• A device is referenced by the name field of its device node. The reference of the node can
be retrieved thanks to the wb robot get device() function.
• Each controller program is executed as a child process of the Webots process. A controller
process does not share any memory with Webots (except the cameras images) and it can
run on another CPU (or CPU core) than Webots.
• The controller code is linked with the libController dynamic library. This library
handles the communication between your controller and Webots.
The section 6.1 explains in more detail controller programming. We invite you to read carefully
this section before going on.
Figure 7.11: Expected result at the end of the tutorial about compound solids.
Start from the results of the previous tutorial and create a new simulation
called compound_solid.wbt by using the menu File > Save World As....
Create the dumbbell by following the figure 7.12. Create the handle first
without placing it in a Transform node (so the handle axis will have the same
direction as the y-axis of the solid). The handle should have a length of 0.1
m and a radius of 0.01 m. The weights should have a radius of 0.03 m and a
subdivision of 2. The weights can be moved at the handle extremities thanks
to the translation field of their Transform nodes.
222 CHAPTER 7. TUTORIALS
Figure 7.12: Representation of the subnodes of a compound solid made of several transformed
geometries.
The aim of this subsection is to learn how to set some simple physics properties for a Solid node.
The Physics node contains fields related to the physics of the current rigid body (Solid).
The mass of a Solid node is given by its density or mass field. Only one
of these two fields can be specified at a time (the other should be set to -1).
When the mass is specified, it defines the total mass of the solid (in [kg]).
When the density is specified, its value (in [kg/m3]) is multiplied by the
volume of the bounding objects, and the product gives the total mass of the
solid. A density of 1000 [kg/m3 ] corresponds to the density of water (default
value).
Set the mass of the dumbbell to 2 [kg]. The density is not used and should be
set to -1.
By default, the center of mass of a Solid node is set at its origin (defined by
the translation field of the solid). The center of mass can be modified using the
centerOfMass field of the Physics node. The center of mass is specified
relatively to the origin of the Solid.
7.6. TUTORIAL 5: COMPOUND SOLID AND PHYSICS ATTRIBUTES (15 MINUTES)223
Let’s say that one of the weights is heavier than the other one. Move the
center of mass of the dumbbell of 0.01 [m] along the y-axis.
Note that when the solid is selected, the center of mass is represented in the
3D view by a coordinate system which is darker than the coordinate system
representing the solid center.
The rotation field of the Transform node determines the rotation of this
node (and of its children) using the Euler axis and angle representation.
A Euler axis and angle rotation is defined by four components. The first
three components are a unit vector that defines the rotation axis. The fourth
component defines the rotation angle about the axis (in [rad]).
The rotation occurs in the sense prescribed by the right-hand rule.
Modify the rotation of the Solid node of the dumbbell in order to move the
handle’s axis (y-axis) parallel to the ground. A unit axis of (1, 0, 0) and an
angle of π/2 is a possible solution.
7.6.6 Contacts
When two solids collide, contacts are created at the collision points. Contact-
Properties nodes can be used to specify the desired behavior of the contacts
(e.g. the friction between the two solids).
Each solid belongs to a material category referenced by their contact-
Material field (”default” by default). The WorldInfo node has a con-
tactProperties field that stores a list of ContactProperties nodes. These
nodes allow to define the contact properties between two categories of Solids.
We want now to modify the friction model between the dumbbell and the other solids of the
environment.
The most critical parameters for a physics simulation are stored in the basicTimeStep, ERP
and CFM fields of the WorldInfo node.
The basicTimeStep field determines the duration (in [ms]) of a physics step. The bigger this
value is, the quicker the simulation is, the less precise the simulation is. We recommend values
between 8 and 16 for a regular use of Webots.
It’s more difficult to explain the behavior of the ERP and CFM fields. These values are directly
used by the physics engine to determine how the constraints are solved. The default values are
well defined for a regular use of Webots. We recommend to read the Reference Manual and the
documentation of ODE2 (physics engine used in Webots) to understand completely their purpose.
There are also other physics parameters which are less useful in a regular use of Webots. A
complete description of these parameters can be found in the Reference Manual. Remark simply
that the Physics, WorldInfo and ContactProperties nodes contains other fields.
2
[Link]
7.7. TUTORIAL 6: 4-WHEELS ROBOT 225
Search in the Reference Manual how to add a linear damping on all the ob-
jects, how to unset the auto-disable feature and how to use the inertia matrix.
7.6.9 Conclusion
You are now able to build a wide range of solids including those being composed of several rigid
bodies. You know that a Geometry node can be moved and rotated if it is included in a Transform
node. You are aware about all the physics parameters allowing you to design robust simulations.
The next step will be to create your own robot.
You can test your skills by creating common objects such as a table.
Remove the nodes defining the e-puck, the ball, the dumbbell and the contact
properties. The ground, the walls and the lighting are kept.
Some definitions are required before giving rules to create a robot model.
The set containing the Solid node and all its derived nodes is called the solid nodes. A similar
definition is applied for the Device, Robot, Joint and Motor nodes. You can get more information
about the node hierarchy in the Reference Manual. Note that the solid nodes and device nodes is
close but don’t match perfectly.
226 CHAPTER 7. TUTORIALS
Figure 7.13: 3D view of the 4 wheels robot. Note that the coordinate system representations
of the robot body and of its wheels are oriented the same way. Their +x-vector (in red) defines
the left of the robot, their +y-vector (in green) defines the top of the robot, and their +z-vector
(in blue) defines the front of the robot. The distance sensors are oriented in a different way, their
+x-vector indicates the direction of the sensor.
Figure 7.14: Top view of the 4 wheels robot. The grid behind the robot has a dimension of 0.2
x 0.3 [m]. The text labels correspond to the name of the devices.
7.7. TUTORIAL 6: 4-WHEELS ROBOT 227
The main structure of a robot model is a tree of solid nodes linked together.
The root node of this tree should be a robot node. The solid are linked together
by joint nodes. A device node should be the direct child of either a robot node,
either a solid node or a joint node.
A joint node is used to add one (or two) degree(s) of freedom (DOF), between
its parent and its child. The direct parent and child of a joint node are both
solid nodes.
The nodes derived from Joint allow to create different kind of constraints
between the linked solid nodes. The most used in robotics is the HingeJoint
allowing to model amongst others rotational motors including wheels.
A joint node can be monitored or actuated by adding respectively a Position-
Sensor node, or a motor node to its device field.
Having these rules in mind, we can start to design the node hierarchy used to model the robot.
The first step is to determine which part of the robot should be modeled as a solid node.
In our example, this operation is quite obvious. The robot has 4 DOF corresponding to the wheel
motors. It can be divided in five solid nodes: the body and the four wheels.
Depending on the expected application of the robot model, reducing the number of DOF when
modeling could be important to get an efficient simulation. For example, when modeling a caster
wheel, a realistic approach implies to model 2 DOF. But if this degree of precision is useless for
the simulation, a more efficient approach can be found. For example, to model the caster wheel
as a Sphere having a null friction coefficient with the ground.
The second step is to determine which solid node is the robot node (the root node). This choice
is arbitrary, but a solution is often much easier to implement. For example, in the case of an
humanoid robot, the robot node would be typically the robot chest, because the robot symmetry
facilitates the computation of the joint parameters.
In our case, the body box is obviously the better choice. The figure 7.15 depicts the solid nodes
hierarchy of the robot.
At the end of the scene tree, add a Robot node having four HingeJoints having
a Solid child. Please refer to figure 7.15.
Add a Shape node containing a Box geometry to the Robot node. Set the color
of the Shape to red. Use the Shape to define also the boundingObject
field of the Robot node. The dimension of the box is (0.1, 0.05, 0.2). Add a
Physics node to the Robot. The figure 7.16 represents all the nodes defining
the robot. So far only the direct children nodes of the root Robot node are
implemented.
228 CHAPTER 7. TUTORIALS
7.7.3 HingeJoints
The initial position of the Wheel is defined by the translation and the rotation fields of the Solid
node. While the rotation origin (anchor) and the rotation axis (axis) are defined by the optional
HingeJointParameters child of the HingeJoint node.
For the first wheel, the Solid translation should be defined to (0.06, 0, 0.05) in order to define
the relative gap between the body and the wheel. The HingeJointParameters anchor should also
be defined to (0.06, 0, 0.05) to define the rotation origin (relatively to the body). Finally the
HingeJointParameters axis should define the rotation axis. In our case it’s along the x-axis (so
(1, 0, 0)).
We want now to implement the cylinder shape of the wheels. As the Cylinder node is defined
along the y-axis, a Transform node should encapsulate the Shape to rotate the Cylinder along the
along the x-axis.
Complete the missing nodes to get the same structure as the one depicted in
figure 7.16. Don’t forget the Physics nodes. Rotate the Transform node by an
Euler axis and angle of (0, 0, 1, Pi/2) in order to inverse the x-axis and the
y-axis. The Cylinder should have a radius of 0.04 and a height of 0.02.
Set the color of the wheels to green.
7.7.4 Sensors
The last part of the robot modeling is to add the two distance sensors to the robot. This can be
done by adding two DistanceSensor nodes as direct children of the Robot node. Note that the
distance sensor acquires its data along the +x-axis. So rotating the distance sensors in order to
point their x-axis outside the robot is necessary (see the figure 7.14).
Add the two distance sensors as explained above. The distance sensors are
at an angle to 0.3 [rad] with the robot front vector. Set their type field to
”sonar”. Set their graphical and physical shape to a cube (not transformed)
having a edge of 0.01 [m]. Set their color to blue. Set their name field
according to the labels of figure 7.14.
7.7.5 Controller
In the previous tutorials, you learnt how to setup a feedback loop and how to read the distance
sensor values. However actuating the RotationalMotor nodes is new. The following note explain
how to proceed.
230 CHAPTER 7. TUTORIALS
To program the rotational motors, the first step is to include the API module
corresponding to the RotationalMotor node:
1 #include <webots/motor.h>
A motor can be actuated by setting its position, its velocity, its acceleration or
its force (cf. Reference Manual). Here we are interested in setting its velocity.
This can be achieve by setting its position at infinity, and by bounding its
velocity:
1 double speed = -1.5; // [rad/s]
2 wb_motor_set_position(wheels[0], INFINITY);
3 wb_motor_set_velocity(wheels[0], speed);
7.7.6 Conclusion
You are now able to design simple robot models, to implement them and to create their control-
lers.
More specifically you learnt the different kind of nodes involved in the building of the robot
models, the way to translate and rotate a solid relatively to another, the way that a rotational
motor is actuated by the controller.
7.8. TUTORIAL 7: USING ROS 231
Once your workspace is set, you have to copy the webots ros folder located in projects/
languages/ros in the src folder of your catkin workspace. You will also need to copy the
list of the services and messages definitions of the webots ros package. Simply copy the srv
and msg folders located in projects/default/controllers/ros/include into the
webots_ros folder of your catkin workspace.
The webots ros package already contains a [Link] with build instructions for the
package. All you have to do, in order to build the package, is to run:
cd catkin_ws
catkin_make
Now that you have built the package, you can run the example you want. You will first have to
launch the master node with the following command:
roscore
You can then start Webots and open the world of the example you want to run (the example worlds
are located in projects/languages/ros/worlds). When you start the simulation the
controller should connect to the master and the simulation should start, waiting for instructions.
If the controller can’t connect to the master node, it probably means the master node doesn’t use
the standard ROS MASTER URI. You can check in the terminal in which the master node was
started what ROS MASTER URI is used and you can then add the correct address in the controller
arguments, in the environment variables or in a [Link] file in the controller directory.
You can then start the ROS node corresponding to this example in a new terminal using the
following command:
The seed of the Webots random number generator is initialized at the begin-
ning of the simulation and not when the ROS nodes connect. Webots has to
be running so that the ROS nodes can connect. However, we cannot guar-
antee how long it will run before the ROS nodes connect. Therefore, the
sensor measurements and motor commands will slightly differ from one run
to another, due to the noise being slightly different at the time of the con-
nection of the ROS nodes. This may have consequences on the behavior of
the robots, thus making such simulations non fully reproducible. You can use
the ’–synchronize’ argument in order to make sure that Webots will not run
before the ROS node connects. This is useful to make ROS-based simulation
reproducible.
If you want to use different computers for the ROS master, the Webots simula-
tion and/or the nodes, you must be able to connect to each of them with SSH
in both ways. The hostname and IP addresses of these computers should be
listed in the known hosts list of each computer and the ROS MASTER URI
variable should be adjusted accordingly.
These examples only show a few possibilities for interfacing ROS and Webots, but you can build
your own nodes to connect with Webots.
The robot information parser node is the most basic one and is a good base to start
building your own node. The complete test node doesn’t show any particular application
but contains an almost exhaustive list of the Webots API functions.
All the functions from the Webots API have their corresponding services or topics. You can find
in the Reference Manual the definitions of all the services and topics associated with each device.
The algorithmic to develop your controllers is not explained in the Webots documentation. How-
ever another tutorial known as ”curriculum” tackle some famous robot programming problems
through a sequence of exercises using the e-puck robot and the C language.
Chapter 8
Robots
• Elegant design: the simple mechanical structure, electronics design and software of e-puck
is an example of a clean and modern system.
• Flexibility: e-puck covers a wide range of educational activities, offering many possibilities
with its sensors, processing power and extensions.
• Simulation software: e-puck is integrated with Webots simulation software for easy pro-
gramming, simulation and remote control of the (physical) robot.
• User friendly: e-puck is small and easy to setup on a tabletop next to a computer. It doesn’t
need any cables, providing optimal working comfort.
• Robustness and maintenance: e-puck is resilient under student use and is simple to repair.
1
[Link]
235
236 CHAPTER 8. ROBOTS
Feature Description
Size 7.4 cm in diameter, 4.5 cm high
Weight 150 g
Battery about 3 hours with the provided 5Wh LiION rechargeable battery
Processor Microchip dsPIC 30F6014A @ 60MHz (about 15 MIPS)
Motors 2 stepper motors with 20 steps per revolution and a 50:1 reduction gear
IR sensors 8 infra-red sensors measuring ambient light and proximity of obstacles in a
4 cm range
Camera color camera with a maximum resolution of 640x480 (typical use: 52x39
or 640x1)
Microphones 3 omni-directional microphones for sound localization
Accelerometer 3D accelerometer along the X, Y and Z axis
LEDs 8 red LEDs on the ring and one green LED on the body
Speaker on-board speaker capable of playing WAV or tone sounds.
Switch 16 position rotating switch
Bluetooth Bluetooth for robot-computer and robot-robot wireless communication
Remote Control infra-red LED for receiving standard remote control commands
Expansion bus expansion bus to add new possibilities to your robot
Programming C programming with the GNU GCC compiler system
Simulation Webots EDU or PRO facilitates the programming of e-puck with a powerful
simulation, remote control and cross-compilation system.
Table 8.1: e-puck features
The e-puck model in Webots is depicted in figure 8.2. This model includes support for the
differential wheel motors (encoders are also simulated), the infra-red sensors for proximity and
light measurements, the accelerometer, the camera, the 8 surrounding LEDs, the body and front
LEDs; the other e-puck devices are not yet simulated in the current model. Besides standard e-
puck devices, the model also provides two slots that can be used to extend the functionality and
to equip the robot with additional devices. In particular, the ground sensors module extension of
the real e-puck robot is modeled in Webots to provide 3 optional infra-red sensors pointing to the
ground in front of the robot. The table 8.2 displays the names of the simulated devices which are
to be used as an argument of the function wb robot get device() (see the Robot section
of Reference Manual2 ).
2
[Link]
238 CHAPTER 8. ROBOTS
Device Name
Differential wheels differential wheels
Proximity sensors ps0 to ps7
Light sensors ls0 to ls7
LEDs led0 to led7 (e-puck ring), led8 (body) and led9 (front)
Camera camera
Accelerometer accelerometer
Ground sensors (extension) gs0, gs1 and gs2
Table 8.2: Devices names
The e-puck dimensions and speed specifications are shown in table 8.3. The functions wb -
differential wheels set speed(), wb differential wheels get left en-
coder() and wb differential wheels get right encoder() will allow you to set
the speed of the robot and to use its encoders.
8.1. USING THE E-PUCK ROBOT 239
As is the case for any Differential Wheels robot set at its default position in Webots, the forward
direction of the e-puck is given by the negative z-axis of the world coordinates. This is also the
direction the eye of the camera is looking to; in keeping with the VRML standard, the direction
vector of the camera is pointing in the opposite direction, namely the direction of the positive
z-axis. The axle’s direction is given by the positive x-axis. Proximity sensors, light sensors and
LEDs are numbered clockwise; their location and orientation are shown in table 8.3 and table
8.4. The last column of table 8.4 lists the angles between the negative x-axis and the direction
of the devices, the plane zOx being oriented counter-clockwise. Note that the proximity sensors
and the light sensors are actually the same devices of the real robot used in a different mode,
so their direction coincide. Proximity sensors responses are simulated in accordance with the
lookup table in figure 8.3; this table is the outcome of calibration performed on the real robot.
The resolution of the camera was limited to 52x39 pixels, as this is the maximum rectangular
image with a 4:3 ratio which can be obtained from the remote control interface with the real
robot.
The standard model of the e-puck is provided in the [Link] PROTO file which is
240 CHAPTER 8. ROBOTS
Control window
When opening a world containing an e-puck robot, Webots displays the e-puck control window
(which also appears when you double-click on the e-puck robot). This window is depicted in fig-
ure 8.6. It allows visualizing the devices of the robot. The distance measurements are displayed
in red, outside the body of the robot. The light measurements are displayed in yellow, above the
distance measurements. The 10 LEDs are displayed in black when off and red (or green) when
on. The motor speeds are displayed in blue, and the motor position is displayed in the Encoder
box in the bottom right hand corner of the window. The camera image (if present), the ground
sensor values (if present) and the accelerometer values are displayed in the corresponding boxes
on the right side of the window.
3
[Link]
4
[Link]
242 CHAPTER 8. ROBOTS
This e-puck control window appears because the robotWindow field of the Differential-
Wheel node in the world file was set to ”e-puck window”. Changing this robotWindow to an
empty string will disable this control window.
BotStudio overview
BotStudio is a user interface for programming graphically the e-puck thanks to a finite state
automaton. Behaviors such as wall follower, collision avoider or line follower can be imple-
mented quickly thanks to this interface. BotStudio is typically destinated for the education field,
particularly for beginners in robotics.
An automaton state of BotStudio corresponds to a state of the e-puck actuators while a transition
corresponds to a condition over its sensor values. A transition is fired when all of its conditions
are fulfilled (logical AND). A logical OR can be performed by several transitions between two
states.
The actuators available in BotStudio are the LEDs and the motors. Each automaton state have
two sliders for setting the motor speed value. Note that these values can be unset by clicking on
the cursor of the slider. Each state have also 10 square buttons for setting the LEDs states. A red
button means the LED is turned on, a black one means it is turned off and a grey one means there
is no modification.
The sensor available in BotStudio are the distance sensors and the camera. Moreover a timer can
be used to temporize the conditions by dragging the corresponding slider. Conditions over the IR
8.1. USING THE E-PUCK ROBOT 243
sensors can be set by dragging the 8 red sliders. A condition can be reversed by clicking on the
grey part of the slider. Finally, the camera is used for giving a clue on the front environment of
the e-puck. An algorithm is applied on the last line of the camera and returns a integer between
-10 and 10 indicating if a black line is perceived respectively at the left and at the right of the
e-puck field of view. A condition can be set on this value for getting a line follower behavior.
BotStudio is depicted in the figure 8.7. An example of BotStudio can be found by opening the
WEBOTS_HOME/projects/robots/e-puck/world/e-puck_botstudio.wbt world
file.
The BotStudio windows appears when the e-puck’s controller points on a .bsg file.
Bluetooth setup
The e-puck has a Bluetooth interface allowing it to communicate with Webots. This feature is
available under Windows, Linux and Mac OS X. The Bluetooth interface must be set up accord-
ing to your operating system (OS). Generally it is as simple as using the Bluetooth interface of
your OS in order to discover and to pair the e-puck as a regular Bluetooth device. The complete
instructions about pairing can be found on the GCTronic website5 .
On linux, the pairing has to be done manually (without using the Bluetooth interface of the OS).
This can be done by using the rfcomm command. Once generated, the rfcomm file has to be
given to Webots through an environment variable. It may also occur that the rfcomm file doesn’t
have the read rights. A typical pairing can be done using the following commands:
Scanning ...
[Link] e-puck_1368
# Bind the MAC adress of the e-puck with a non-existing rfcomm file
sudo rfcomm bind /dev/rfcomm1 [Link]
# (Optional) Grant the read rights to the rfcomm file
sudo chmod 666 /dev/rfcomm1
# Export the WEBOTS_COM? environment variable (with ? between 1 to 9)
export WEBOTS_COM1=/dev/rfcomm1
# Launch Webots
webots
Once properly set up, your Bluetooth connection to your e-puck should appear in the popup
menu of the control. If it doesn’t appear there, it means that your computer was not properly
configured to interface with your e-puck robot through Bluetooth. Please refer to the instructions
given in the previous section.
When selecting a specific Bluetooth connection from the popup menu of the control window,
Webots will try to establish a connection with your e-puck robot. Once connected, it will display
the version of the e-puck serial communication software on the Webots console (e.g. ’Running
real e-puck (Version 1.4.3 March 2010 (Webots))’), and will switch the control to the real robot.
That is, it will send motor commands to the real robot and display sensor information (proximity,
light, camera image, etc.) coming from the real robot. This makes the transfer from the simula-
tion to the real robot trivially simple. Note that in the same popup menu, the Refresh ports menu
item can be used for updating the COM ports.
The remote control has two requirements: the Bluetooth must be correctly set up (computer side)
and the e-puck must be programmed with the Webots last firmware. For setting up Bluetooth,
please refer to the official e-puck website. For uploading the last firmware on your robot, switch
on your robot, press the Upload to e-puck robot... button on the control window and finally select
the select the COM port which corresponds to your robot and the WEBOTS_HOME/projects/
robots/e-puck/transfer/firmware/[Link] file located in your
Webots directory (x.x.x has to be replaced by the current firmware’s version).
Cross-compilation
An alternative to the remote-control session for running the real e-puck is to cross-compile your
code and to upload it on the e-puck.
For using this feature, your code has to be written in C and to use the C Webots API. Moreover,
you need to define a specific Makefile called Makefile.e-puck in the controller directory.
This Makefile must include the following file:
8.2. USING THE NAO ROBOT 245
include $(WEBOTS_HOME)/projects/robots/e-puck/transfer/libepuck/
[Link]
Thanks to this, it is possible to cross-compile with Webots by using the Build > Cross-compile
menu item of the text editor. Note that the Upload to e-puck robot... button of the e-puck control
window allows you to upload a file generated by the cross-compilation extended by .hex on the
e-puck robot.
An example of cross-compilation is given in the WEBOTS_HOME/projects/robots/e-puck/
controllers/e-puck_cross-compilation subdirectory of your Webots directory.
This error can be fixed simply by installing the following packets from a terminal:
sudo apt-get install gcc-4.6-base:i386 libgcc1:i386 libc6:i386
8.2.1 Introduction
The Nao robot is a humanoid robot developed by Aldebaran Robotics6 . This section explains
how to use Nao robot simulated in Webots together with the Choregraphe program of Aldebaran
Robotics7 . Currently Webots supports the Nao v3.3, v4.0 and v5.0 versions, with and without
their articulated fingers (respectively with 25 and 21 degrees of freedom) for the first two.
The Webots installation includes several world files with Nao robots. You will find some in this
folder: WEBOTS_HOME/projects/robots/aldebaran/worlds. The [Link] and
nao_indoors.wbt are meant to be used with Choregraphe (see below). The nao_demo.
wbt is a demonstration of a very simple controller that uses Webots C API instead of Chore-
graphe. The nao_matlab.wbt world is an example of programming Webots using the Matlab
API. The nao_robocup.wbt world is an example of how to use the NAOqi API inside We-
bots. It is the same API that is used in Choregraphe, meaning that you can program Nao inside
Webots without using Choregraphe if you want to. In this world, Nao tries to shoot the ball in the
goal. You can find another NAOqi example in the WEBOTS_HOME/projects/contests/
6
[Link]
7
[Link]
246 CHAPTER 8. ROBOTS
These instructions have been tested with Webots 8.0.0 and Choregraphe [Link]. Please note
that Webots must not be launched as root when using any world containing naoqisim, otherwise
Choregraphe won’t be able to send instructions to the robot in Webots.
Start Webots and open this world file: WEBOTS_HOME/projects/robots/aldebaran/
worlds/[Link] You should see a red Nao in an empty environment. If the simulation is
paused, then please start it by pushing the Real-time button in Webots.
The camera images in Webots (small purple viewports) should reflect what the robot sees.
Several lines of text information corresponding to the output of NAOqi should be printed to
Webots console.
Now you can start Choregraphe with the –no-naoqi option. Please make sure the Choregraphe
version matches the NAOqi version printed in Webots console. In Choregraphe choose the menu
Connection > Connect to.... Then in the list, select the NAOqi that was started by Webots, on
you local machine, it will have the port number 9559, unless you change it. Note that the NAOqi
will not appear in the list if the simulation was not started in Webots. If the simulation was
started but the robot still doesn’t appear in the list, force the IP and port to [Link] and 9559 in
Choregraphe and then press connect.
At this point a Nao model matching the Webots model should appear in Choregraphe. Now, in
Choregraphe toggle the ”Wake up” button, which is a little sun in the rop right of the window.
Nao is currently in the ”Stand Zero” pose, you can change its starting pose using the posture
library in Choregraphe.
Then double-click on any of the Nao parts in Choregraphe: a small window with control sliders
appears. Now, move any of the sliders: the motor movement in Choregraphe should be reflected
in the Webots simulation. If you open the Video monitor in Choregraphe you should see the
picture of the Nao camera simulated by Webots.
You can switch between the Nao model thanks to the following Nao PROTO fields:
8
[Link]
8.2. USING THE NAO ROBOT 247
• version corresponds to the real Nao version. The supported versions are ”3.3”, ”4.0” and
”5.0”. The main difference between these models is the different calibration of the physics.
The field of view of the cameras is slightly different, too. Please refer directly to the
[Link] file to see the complete difference. Note that each version having a different
weight repartition in their body, the best contact properties in the simulated world aren’t
always the same. They are currently optimized for the version 5.0 of Nao in the default
Nao worlds and may not perform as well with previous versions of Nao.
• degreeOfFreedom corresponds to the degree of freedom of the real Nao. For versions 3.3
and 4.0 of Nao, the supported degreeOfFreedom values are 25 and 21. This corresponds
to a model respectively with and without articulated fingers. We recommend to use articu-
lated fingers only if necessary because of their big resource consumption. Version 5.0 does
not exist without articulated fingers, so the only possible value is 25 in this case.
3. In Webots Scene Tree, select a top level nodes, e.g. the Nao robot
6. Then select one of the Nao models from the list, the Nao is added to the current world
7. Select the Nao in the 3D view and move it away from the other one: SHIFT + left mouse
button
8. Select the controllerArgs field in the newly created robot and increase the port num-
ber, e.g. 9560
10. Now you can push the Real-time button to run the simulation with several robots
Repeat the above procedure for each additional robot that you need. Remember that every robot
must have a different port number specified in controllerArgs.
Choregraphe uses exclusively real-time and so the robot’s motions are meant to be carried out
in real-time. The Webots simulator uses a virtual time base that can be faster or slower than
real-time, depending on the CPU and GPU power of the host computer. If the CPU and GPU are
powerful enough, Webots can keep up with real-time, in this case the speed indicator in Webots
shows approximately 1.0x, otherwise the speed indicator goes below 1.0x. Choregraphe motions
will play accurately only if Webots simulation speed is around 1.0x. When Webots simulation
speed drifts away from 1.0x, the physics simulation gets wrong (unnatural) and thus Choregraphe
motions don’t work as expected any more. For example if Webots indicates 0.5x, this means
that it is only able to simulate at half real-time the motion provided by Choregraphe: the physics
simulation is too slow. Therefore it is important to keep the simulation speed as much as possible
close to 1.0x. There are currently no means of synchronizing Webots and Choregraphe, but this
problem will be addressed in a future release. It is often possible to prevent the simulation speed
from going below 1.0x, by keeping the CPU and GPU load as low as possible. There are several
ways to do that, here are the most effective ones:
• Switch off the simulation of the Nao cameras with the ”-nocam” option, as mentioned
above
• Switch off the rendering of the shadows: change to FALSE the castShadows field of
each light source in the Scene Tree
• Reduce the dimensions of the 3D view in Webots, by manually resizing the GUI compo-
nents
• Remove unnecessary objects from the simulation, in particular objects with physics
If for some unexpected reason Webots crashes, it is possible that the hal or naoqi-bin pro-
cesses remain active in memory. In this case we recommend you to terminate these processes
manually before restarting Webots.
On Windows, use the Task Manager (the Task Manager can be started by pressing Ctrl-Alt-
Delete): In the Task Manager select the Processes tab, then select each [Link] and naoqi-
[Link] line and push the ”End Process” button for each one.
On Linux, you can use the killall or the pkill commands, e.g.:
$ killall hal naoqi-bin
The table 8.5 shows which devices are supported by the model, and their names (using the Webots
terminology).
9
[Link]
250 CHAPTER 8. ROBOTS
The Thymio II distance sensor feedback is given on figure 8.9. The calibration was performed
using a regular A4 white paper.
8.3. USING THE THYMIO II ROBOT 251
These exercises11 can be reproduced by adding a Thymio2Ball node in your world. The ball
can be slightly moved by applying a force on it (ALT + mouse left click). An example
of this is located there (see the figure 8.13): WEBOTS_HOME/projects/robots/thymio/
worlds/thymio2_ball.wbt
In this section, you will learn how to use Webots simulation model of the Pioneer 3-AT robot.
(figure 8.14).
The Pioneer 3-AT robot is an all-purpose outdoor base, used for research and prototyping ap-
plications involving mapping, navigation, monitoring, reconnaissance and other behaviors. It
provides a ready-to-use set of devices listed in table 8.6.
11
[Link]
254 CHAPTER 8. ROBOTS
Feature Description
Dimensions 508 mm long, 497 mm large, 277 mm high
Weight 12 kg, operating playload of 12 kg on floor
Batteries 2-4 hours, up to 3 lead acid batteries of 7.2 Ah each, 12 V
Microcontroller 32 digital inputs, 8 digital outputs, 8 analog inputs, 3 serial extension ports
I/O
Skid steering drive Turn radius: 0 cm, swing radius: 34 cm, max. traversable grade: 35%
Speed Max. forward/backward speed: 0.7 m/s; Rotation speed: 140 deg/s
Table 8.6: Pioneer 3-AT features
More information on the specifications and optional devices is available on Adept Mobile Robots
official webpage12 .
The Pioneer 3-AT model in Webots is depicted in figure 8.15. This model includes support for 4
motors and 16 sonar sensors (8 forward-facing, 8 rear-facing) for proximity measurements. The
standard model of the Pioneer 3-AT is provided in the [Link] file which is located
in the WEBOTS_HOME/projects/robots/pioneer/pioneer3at/worlds directory
of the Webots distribution.
The [Link] world file is a simulation example of a simple obstacle avoidance be-
havior based on the use of a SICK LIDAR (see the obstacle_avoidance_with_lidar.
c controller file in the WEBOTS_HOME/projects/robots/pioneer/pioneer3at/controller
directory).
The Pioneer 3-AT motors are RotationalMotor nodes named according to figure 8.16. The wb -
set motor position() and wb set motor velocity() functions allow the user to
manage the rotation of the wheels. The sonar sensors are numbered according to figure 8.17.
12
[Link]
256 CHAPTER 8. ROBOTS
Figure 8.18: Pioneer 3-DX, an all-purpose base, used for research and applications
The angle between two consecutive sensor directions is 20 degrees except for the four side sen-
sors (so0, so7, so8 and so15) for which the angle is 40 degrees.
In this section, you will learn how to use Webots simulation model of the Pioneer 3-DX robot.
(figure 8.18).
The base Pioneer 3-DX platform is assembled with motors featuring 500-tick encoders, 19 cm
wheels, tough aluminum body, 8 forward-facing ultrasonic (sonar) sensors, 8 optional real-facing
sonar, 1, 2 or 3 hot-swappable batteries, and a complete software development kit. The base
Pioneer 3-DX platform can reach speeds of 1.6 meters per second and carry a payload of up to
23 kg.
The Pioneer 3-DX robot is an all-purpose base, used for research and applications involving
mapping, teleoperation, localization, monitoring, reconnaissance and other behaviors. Pioneer
3-DX is provided with a ready-to-use set of devices listed in table 8.7.
258 CHAPTER 8. ROBOTS
Feature Description
Dimensions 455 mm long, 381 mm large, 237 mm high
Weight 9 kg, operating playload of 17 kg
Batteries 8-10 hours, 3 lead acid batteries of 7.2 Ah each, 12 V
Microcontroller 32 digital inputs, 8 digital outputs, 8 analog inputs, 3 serial extension ports
I/O
Skid steering drive Turn radius: 0 cm, swing radius: 26.7 cm, max. traversable grade: 25%
Speed Max. forward/backward speed: 1.2 m/s; Rotation speed: 300 deg/s
Table 8.7: Pioneer 3-DX features
More information on the specifications and optional devices is available on Adept Mobile Robots
official webpage13 .
The Pioneer 3-DX model in Webots is depicted in figure 8.19. This model includes support for
two motors, the caster wheel, 7 LEDs on the control panel and 16 sonar sensors (8 forward-
facing, 8 rear-facing) for proximity measurements. The standard model of the Pioneer 3-DX is
provided in the [Link] file which is located in the WEBOTS_HOME/projects/
robots/pioneer/pioneer3dx/worlds directory of the Webots distribution.
The [Link] world file shows a simulation example of the Braitenberg avoidance
algorithm based on the use of the 16 sonar sensors (see the braitenberg.c controller file in
the WEBOTS_HOME/projects/robots/pioneer/pioneer3dx/controller direc-
tory). The pioneer3dx_with_kinect.wbt world file in the same directory is a simple
simulation example of an obstacle avoidance behaviour based on a Microsoft kinect sensor (see
the obstacle_avoidance_kinect.c controller file).
13
[Link]
8.4. USING THE PIONEER 3-AT AND PIONEER 3-DX ROBOTS 259
The Pioneer 3-DX motors are RotationalMotor nodes named according to figure 8.20. The wb -
set motor position() and wb set motor velocity() functions allow the user to
manage the rotation of the wheels. The sonar sensors are numbered according to figure 8.17.
The angle between two consecutive sensor directions is 20 degrees except for the four side sen-
sors (so0, so7, so8 and so15) for which the angle is 40 degrees.
260 CHAPTER 8. ROBOTS
Chapter 9
Webots FAQ
This chapter is a selection of frequently asked questions found on the Webots forum1 . You may
find additional information directly in the group. Other useful sources of information about
Webots include: Webots Reference Manual2 and Cyberbotics’ Robot Curriculum3 .
9.1.1 What are the differences between Webots PRO, Webots EDU and
Webots MOD?
Webots PRO provides a fully featured version of Webots intended for robotics research. Webots
EDU provides a special version of Webots well suited for education. Webots MOD provides
components tailored for specific uses of Webots, they include different models of robots with
different programming interfaces. The differences between Webots PRO, EDU and MOD are
explained here4 .
261
262 CHAPTER 9. WEBOTS FAQ
Before reporting a bug, please make sure that the problem is actually caused by Webots and not
by your controller program. For example, a crash of the controller process usually indicates a bug
in the controller code, not in Webots. This situation can be identified with these two symptoms:
1. Webots GUI is visible and responsive, but the simulation is blocked (simulation time
stopped).
2. The controller process has vanished from the Task Manager (Windows) or is shows as
<defunct> when using ps -e (Linux/Mac).
9.2 Programming
To get the position of a robot in the robot’s controller code: add a GPS node to the robot, then use
wb robot get device(), wb gps enable() and wb gps get values() functions.
Note that the GPS’s resolution field must be 0 (the default), otherwise the results will be noisy.
You will find more info about the GPS node and functions in Reference Manual6 . Note that the
GPS can also be placed on a robot’s part (arm, foot, etc.) to get the world/global coordinates of
that particular part.
6
[Link]
9.2. PROGRAMMING 263
1. To get the 3D position of any Transform (or derived) node in the Supervisor code:
you can use the wb supervisor node get position() function. Please check this
function’s description in the Reference Manual.
2. To get the 3D position of any Transform (or derived) node placed at the root of the
Scene Tree (the nodes visible when the Scene Tree is completely collapsed), you can use
the wb supervisor field get sf vec3f() function. Here is an example.
A simulation example that shows both the GPS and the Supervisor techniques is included
in the Webots installation, you just need to open this world: WEBOTS_HOME/projects/
samples/devices/worlds/[Link].
In the physics plugin you can use ODE’s dBodyGetPosition() function. Note that this
function returns the position of the center of mass of the body: this may be different from the
center of the Solid. Please find a description of ODE functions here7 .
Webots provides several functions to get the 3D position of a robot or an object (see above): by
taking the first derivative of the position you can determine the velocity. There are also some
functions (see below) that can be used to get the velocity directly:
To get the angular velocity of a robot (or robot part) in the robot’s controller code: add a
Gyro node to the robot (or robot part), then use wb robot get device(), wb gyro -
enable() and wb gyro get values() functions. You will find more information about
the Gyro node and functions in the Reference Manual.
Using the wb supervisor node get velocity() function it is possible to retrieve both
the linear and angular velocity of any Solid node. You will find more information about this
function in the Reference Manual.
7
[Link]
264 CHAPTER 9. WEBOTS FAQ
In the physics plugin you can use ODE’s dBodyGetLinearVel() and dBodyAngularVel()
functions. These functions return the linear velocity in meters per second, respectively the angu-
lar velocity in radians per second. Please find a description of ODE functions here: here8 .
9.2.4 What does this mean: ”Could not find controller {...} Loading void
controller instead.” ?
This message means that Webots could neither find an executable file (e.g. .exe), nor an in-
terpreted language file (e.g. .class, .py, .m) to run as controller program for a robot. In fact,
Webots needs each controller file to be stored at specific location in order to be able to executed
it. The requested location is in the controllers subdirectory of the current Webots project
directory, e.g. my_project. Inside the controllers directory, each controller project must
be stored in its own directory which must be named precisely like the controller field of
the Robot. Inside that directory, the executable/interpretable file must also be named after the
controller field of the Robot (plus a possible extension). For example if the controller field
of the robot looks like this, in the Scene Tree:
Robot {
controller "my_controller"
}
If Webots does not find any file at the above specified paths, then the error message in question
is shown. So this problem often happens when you:
• Have moved the project or source files to a location that does not correspond to the above
description.
• Use an external build system, e.g. Visual Studio, that is not configured to generate the
executable file at the right location.
8
[Link]
9.2. PROGRAMMING 265
9.2.5 What does this mean: ”Warning: invalid WbDeviceTag in API func-
tion call” ?
A WbDeviceTag is an abstract reference (or handle) used to identify a simulated device in
Webots. Any WbDeviceTag must be obtained from the wb robot get device() function.
Then, it is used to specify a device in various Webots function calls. Webots issues this warning
when the WbDeviceTag passed to a Webots function appears not to correspond to a known
device. This can happen mainly for three reasons:
1. The WbDeviceTag is 0 and thus invalid because it was not found by wb robot get -
device(). Indeed, the wb robot get device() function returns 0, if it cannot not
find a device with the specified name in the robot. Note that the name specified in the
argument of the wb robot get device() function must correspond to the name field
of the device, not to the VRML DEF name!
2. Your controller code is mixing up two types of WbDeviceTags, for example because it
uses the WbDeviceTag of a Camera in a wb distance sensor *() function. Here
is an example of what is wrong:
#include <webots/robot.h>
#include <webots/camera.h>
#include <webots/distance_sensor.h>
#define TIME_STEP 32
int main() {
wb_robot_init();
WbDeviceTag camera = wb_robot_get_device("camera");
wb_camera_enable(camera, TIME_STEP);
...
double value = wb_distance_sensor_get_value(camera); // WRONG!
...
}
3. The WbDeviceTag may also be invalid because it is used before initialization with wb -
robot get device(), or because it is not initialized at all, or because it is corrupted
by a programming error in the controller code. Here is such an example:
#include <webots/robot.h>
#include <webots/camera.h>
266 CHAPTER 9. WEBOTS FAQ
#include <webots/distance_sensor.h>
#define TIME_STEP 32
int main() {
wb_robot_init();
WbDeviceTag distance_sensor, camera = wb_robot_get_device("
camera");
wb_camera_enable(camera, TIME_STEP);
wb_distance_sensor_enable(distance_sensor, TIME_STEP); //
WRONG!
...
}
void webots_physics_init() {
// find the body on which you want to apply a force
body = dWebotsGetBodyFromDEF("MY_ROBOT");
...
}
void webots_physics_step() {
...
dVector3 f;
f[0] = ...
f[1] = ...
f[2] = ...
...
// at every time step, add a force to the body
dBodyAddForce(body, f[0], f[1], f[2]);
...
}
9.2. PROGRAMMING 267
There is more info on the plugin functions in the Reference Manual in the chapter about Physics
Plugins. Additional information about the ODE functions can be found here9 . You may also
want to study this example distributed with Webots:
WEBOTS_HOME/projects/samples/demos/worlds/[Link]
In this example, the physics plugin adds user computed forces to the robot body in order to
simulate Archimedes and hydrodynamic drag forces.
9.2.8 What does this mean: ”The time step used by controller {...} is not a
multiple of [Link]!”?
Webots allows to specify the control step and the simulation step independently. The con-
trol step is the argument passed to the wb robot step() function, it specifies the dura-
tion of a step of control of the robot. The simulation step is the value specified in World-
[Link] field, it specifies the duration of a step of integration of the physics
simulation, in other words: how often the objects motion must be recomputed. The execution of
a simulation step is an atomic operation: it cannot be interrupted. Hence a sensor measurement
or a motor actuation must take place between two simulation steps. For that reason the control
step specified with each wb robot step() must be a multiple of the simulation step. If it is
not the case you get this error message. So, for example if the [Link]
is 16 (ms), then the control step argument passed to wb robot step() can be 16, 32, 48, 64,
80, 128, 1024, etc.
9
[Link]
268 CHAPTER 9. WEBOTS FAQ
Webots does automatically detect collisions and apply the contact forces whenever necessary.
The collision detection mechanism is based on the shapes specified in the boundingObjects.
Now if you want to programmatically detect collision, there are several methods:
1. In controller code: you can detect collision by using TouchSensors placed around your
robot body or where the collision is expected. You can use TouchSensors of type
”bumper” that return a boolean status 1 or 0, whether there is a collision or not. In fact a
”bumper” TouchSensor will return 1 when its boundingObject intersects another
boundingObject and 0 otherwise.
2. In supervisor code (Webots PRO required): you can detect collisions by tracking the po-
sition of robots using the wb supervisor field get *() functions. Here is a naive
example assuming that the robots are cylindrical and moving in the xz-plane.
#define ROBOT_RADIUS ...
...
int are_colliding(WbFieldRef trans1, WbFieldRef trans2) {
const double *p1 = wb_supervisor_field_get_sf_vec3f(trans1);
const double *p2 = wb_supervisor_field_get_sf_vec3f(trans2);
double dx = p2[0] - p1[0];
double dz = p2[2] - p1[2];
double dz = p2[2] - p1[2];
return sqrt(dx * dx + dz * dz) < 2.0 * ROBOT_RADIUS;
}
...
// do this once only, in the initialization
WbNodeRef robot1 = wb_supervisor_node_get_from_def("MY_ROBOT1")
;
WbNodeRef robot2 = wb_supervisor_node_get_from_def("MY_ROBOT2")
;
WbFieldRef trans1 = wb_supervisor_node_get_field(robot1, "
translation");
WbFieldRef trans2 = wb_supervisor_node_get_field(robot2, "
translation");
...
// detect collision
if (are_colliding(trans1, trans2)) {
...
}
3. In the physics plugin (Webots PRO required): you can replace or extend Webots colli-
sion detection mechanism. This is an advanced technique that requires knowledge of the
9.3. MODELING 269
ODE (Open Dynamics Engine) API10 . Your collision detection mechanism must be imple-
mented in the webots physics collide() function. This function is described in
the Physics Plugin chapter of the Reference Manual.
The content of the camera windows will appear only after all the following steps have been
completed:
2. The WbDeviceTag for the Camera has been found with the function wb robot get -
device().
3. The Camera has been enabled using the function wb camera enable().
4. The function wb camera get image() (or wb camera get range image() for
a ”range-finder” Camera) has been called.
5. At least one wb robot step() (or equivalent function) has been called.
9.3 Modeling
The explosion is usually caused by inappropriate values passed to the physics engine (ODE).
There are many things you can be try to improve the stability of the simulation (adapted from
ODE’s User Guide):
1. Reduce the value of [Link]. This will also make the simulation
slower, so a tradeoff has to be found. Note that the value of the control step (wb robot -
step(TIME STEP)) may have to be adapted to avoid warnings.
3. Avoid large mass ratios. A Joint that connects a large and a small mass ([Link])
together will have a hard time to keep its error low. For example, using a Joint to connect
a hand and a hair may be unstable if the hand/hair mass ratio is large.
10
[Link]
270 CHAPTER 9. WEBOTS FAQ
4. Increase the value of [Link]. This will make the system more numerically
robust and less susceptible to stability problems. This will also make the system look more
spongy so a tradeoff has to be found.
5. Avoid making robots (or other objects) move faster than reasonably for the time step
([Link]). Since contact forces are computed and applied only
at every time step, too fast moving bodies can penetrate each other in unrealistic ways.
6. Avoid building mechanical loops by using Connector nodes. The mechanical loops
may cause constraints to fight each other and generate strange forces in the system that can
swamp the normal forces. For example, an affected body might fly around as though it has
life on its own, with complete disregard for gravity.
In order for a Webots simulation to be replicable, the following conditions must be fulfilled:
1. Each simulation must be restarted either by pushing the Revert button, or by using the wb -
supervisor simulation revert() function, or by restarting Webots. Any other
method for resetting the simulation will not reset the physics (velocity, inertia, etc.) and
other simulation data, hence the simulation state will be reset only partly. The random
seeds used by Webots internally are reset for each simulation restarted with one of the
above methods.
2. The synchronization flag of every robot and supervisor must be TRUE. Otherwise
the number of physics steps per control step may vary with the current CPU load and hence
the robot’s behavior may also vary.
3. The controllers (and physics plugin) code must also be deterministic. In particular that
code must not use a pseudo random generator initialized with an non-deterministic seed
such as the system time. For example this is not suitable for replicable experiments:
srand(time(NULL)). Note that uninitialized variables may also be a source of un-
deterministc behavior.
4. Each simulation must be executed with the same version of the Webots software and on
the same OS platform. Different OS platforms and different Webots versions may result
small numerical differences.
If the four above conditions are met, Webots simulations become replicable. This means that
after the same number of steps two simulations will have exactly the same internal state. Hence
if both simulation are saved using the Save as... button, the resulting files will be identical. This
is true independently of the simulation mode used to execute the simulation: Step, Real-Time,
Run or Fast. This is also true whether or not sensor noise is used (see below).
9.3. MODELING 271
1. In the lookupTables: the third column of each lookupTable in the .wbt and .proto
files must be reset to 0
3. In the Camera nodes: the colorNoise and the rangeNoise fields must be reset to 0
void webots_physics_init() {
void webots_physics_step() {
// nothing to do
}
void webots_physics_cleanup() {
// nothing to do
}
You will find the description of Webots physics plugin API in your Reference Manual or on this
page11 . You will find the description about the ODE functions on this page12 .
9.3.6 Should I specify the ”mass” or the ”density” in the Physics nodes?
It is more accurate to specify the mass if it is known. If you are modeling a real robot it is
sometimes possible to find the mass values in the robot’s specifications. If you specify the den-
sities, Webots will use the volume of each boundingObject multiplied by the density of
the corresponding Physics node to compute each mass. This may be less accurate because
boundingObjects are often rough approximations.
The rendering is also closely related to the Materials. To set a Material without texture,
set only its Appearance node. Then you can play with the diffuseColor field to set
its color (avoid to use pure colors, balancing the RGB components give better results). To set a
Material with texture, set only its ImageTexture node. Eventually, the specularColor
field can be set to a gray value to set a reflection on the object. The other fields (especially
the ambientIntensity and the emissiveColor fields) shouldn’t be modified except in
specific situations.
The color field of the ElevationGrid shouldn’t be use for a realistic rendering because it
is not affected by the ambient light with the same way as the other Shapes.
Here is a methodology to set up the lights:
1. Place the lights at the desired places. Often a single directional light pointing down is
sufficient.
3. Increase the ambientIntensity of the main light. The result will be the appearance
of the objects when they are in shadows.
4. Switch on the shadows if required. The shadows are particularily costly, and are strongly
related to the Shapes resolution.
9.4 Speed/Performance
You should verify your graphics driver installation. Please find instructions here section 1.3.
If you are using a laptop computer, please check the power options and make sure you are using
the high performance power plan.
On Ubuntu (or other Linux) we do also recommend to deactivate compiz (System > Preferences
> Appearance > Visual Effects = None). Depending on the graphics hardware, there may be a
huge performance drop of the rendering system (up to 10x) when compiz is on.
1. Use the Run button (Webots PRO only). This button runs the simulation as fast as possible
using all the available CPU power. Otherwise, using the Real-Time running mode, Webots
may not be using all the available CPU power in order to obtain a simulation speed that is
close to the speed of the real world’s phenomena.
2. Use the Fast button (Webots PRO only). This button runs the simulation as fast as possible
using all the available CPU power. In this mode the simulation speed is increased further
by leaving out the graphics rendering, hence the 3d window is black.
4. Decrease the value of [Link]. This field represents the maximum rate at which
the 3D display of the main windows is refreshed. With a lower value, the simulation
becomes faster but more flickering. With a higher value, the simulation becomes slower
but less flickering.
6. Disable unnecessary shadows. Webots uses a lot of CPU/GPU power to compute how
and where the objects shadows are cast. But shadows are irrelevant for most simulation
unless they should explicitly be seen by Cameras. Unnecessary shadows can be disabled
by unchecking the castShadows field of light nodes: PointLight, SpotLight,
or DirectionalLight.
8. Simplify the boundingObjects to increase the speed of the collision detection. Replace
complex primitives, like Cylinder, IndexedFaceSet and ElevationGrid by
simpler primitives, like Sphere, Capsule, Box and Plane. Avoid using a compo-
sition of primitives (in a Group or a Transform) when a single primitive would do the
trick.
Chapter 10
Known Bugs
This chapter lists the bugs known by Cyberbotics. They are not planned to be resolved on the
short term but possible workarounds are explained.
10.1.2 Virtualization
Because it highly relies on OpenGL, Webots may not work properly in virtualized environments
(such as VMWare or VirtualBox) which often lack a good OpenGL support. Hence, Webots may
exhibit some display bugs, run very slowly or crash in such environments.
275
276 CHAPTER 10. KNOWN BUGS
collision detection may occasionaly yield wrong contact points. Sometimes the contact points
may be slightly off the shape, therefore causing unrealistic reaction forces to be applied to the
objects. Other times there are too few contact points, therefore causing vibration or instabilities.
10.2 Mac OS X
10.3 Linux
10.3.2 ssh -x
There are known issues about running Webots over a ssh -x (x-tunneling) connection. This
problem is not specific to Webots but to most GLX (OpenGL on the X Window system) appli-
cations that use complex OpenGL graphics. We think this is caused by incomplete or defective
implementation of the GLX support in the graphics drivers on Linux. It may help to run the ssh
-x tunnel across two computers with the same graphics hardware, e.g., both nVidia or both ATI.
It also usually works to use Mesa OpenGL on both sides of the ssh -x tunnel, however this
solution is extremely slow.