FEMTO-ST Institute / DISC /OMNI VisibleSim BlockCode tutorial September 2015

VisibleSim BlockCode tutorial

Structure of VisibleSim

VisibleSim is a behavior simulator for modular connected robots. Each robot executes the same code named BlockCode that manages exchanges of messages between connected modules, internal events (like changing color, moving, aso) and communication with the user interface of the simulator.

The structure of the source code is organized in 3 main directories:

In order to create a BlockCode for the simulation of a distributed program, we have to fill a subdirectory of applicationSrc. This tutorial will help you to generate the files used by the simulator. The name of the files are deduced from the name of the application, for example we create here a simple application that color blocks depending on the distance to the #1 block, we call it simpleColor. Three files are necessary to run the simulation, they will be automatically created by the following webApp:

BlockCode generator

You can already generate a first code, just by filling the name of your program (for example simpleColor), then select a type of block and click on "Generate" button. Then you can download a zip archive which contains all you need to test your application.

General information
Application name:
Robot type: Blinky Block Smart Block Sliding Cube 2D catom 3D catom Datom
Events parseUserElements(...)
New messageName: , Type:

Download all the files in the zip archive: ./zipFiles/simpleColor_1590792484.zip (4 files)

File: simpleColor.cpp

#include <iostream>
#include "simpleColorCode.hpp"

using namespace std;
using namespace BlinkyBlocks;

int main(int argc, char **argv) {
    try {
        createSimulator(argc, argv, SimpleColorCode::buildNewBlockCode);
    } catch(std::exception const& e) {
        cerr << "Uncaught exception: " << e.what();

    return 0;

File: simpleColorCode.hpp

#ifndef simpleColorCode_H_
#define simpleColorCode_H_

#include "robots/blinkyBlocks/blinkyBlocksSimulator.h"
#include "robots/blinkyBlocks/blinkyBlocksWorld.h"
#include "robots/blinkyBlocks/blinkyBlocksBlockCode.h"

using namespace BlinkyBlocks;

class SimpleColorCode : public BlinkyBlocksBlockCode {
	BlinkyBlocksBlock *module = nullptr;
public :
	SimpleColorCode(BlinkyBlocksBlock *host);
	~SimpleColorCode() {};

  * This function is called on startup of the blockCode, it can be used to perform initial
  *  configuration of the host or this instance of the program.
  * @note this can be thought of as the main function of the module
    void startup() override;

/** needed to associate code to module                                      **/
	static BlockCode *buildNewBlockCode(BuildingBlock *host) {
	    return(new SimpleColorCode((BlinkyBlocksBlock*)host));

#endif /* simpleColorCode_H_ */

File: simpleColorCode.cpp

#include "simpleColorCode.hpp"

SimpleColorCode::SimpleColorCode(BlinkyBlocksBlock *host):BlinkyBlocksBlockCode(host),module(host) {
    // @warning Do not remove block below, as a blockcode with a NULL host might be created
    //  for command line parsing
    if (not host) return;


void SimpleColorCode::startup() {
    console << "start " << module->blockId << "\n";
    if (module->blockId == 1) { // Master id is 1


# Get current directory's name
mkfile_path := $(abspath $(lastword $(MAKEFILE_LIST)))
current_dir := $(notdir $(patsubst %/,%,$(dir $(mkfile_path))))
APPDIR = ../../applicationsBin/$(current_dir)

# --- Sample User Makefile ---
# GLOBAL_LIBS, GLOBAL_INCLUDES and GLOBAL_CFLAGS are set by parent Makefile
# HOWEVER: If calling make from the codeBlock directory (for more convenience to the user),
#	these variables will be empty. Hence we test their value and if undefined,
#	set them to predefined values.
# You will find instructions below on how to edit the Makefile to fit your needs.
# SRCS contains all the sources of your codeBlocks
SRCS = simpleColor.cpp simpleColorCode.cpp
# OUT is the output binary, where APPDIR is its enclosing directory
OUT = $(APPDIR)/simpleColor
# MODULELIB is the library for your target module type: -lsimBlinkyBlocks
MODULELIB = -lsimBlinkyBlocks
# TESTS contains the commands that will be executed when `make test` is called
TESTS = ../../utilities/blockCodeTest.sh simpleColor $(OUT)
# CUSTOM_LIBS are the external dependencies of your blockcode, empty by default
# End of Makefile section requiring input by user

OBJS = $(SRCS:.cpp=.o)
DEPS = $(SRCS:.cpp=.depends)

OS = $(shell uname -s)
SIMULATORLIB = $(MODULELIB:-l%=../../simulatorCore/lib/lib%.a)

INCLUDES = -I. -I../../simulatorCore/src -I/usr/local/include -I/opt/local/include -I/usr/X11/include
INCLUDES = -I. -I../../simulatorCore/src $(GLOBAL_INCLUDES)

ifeq ($(GLOBAL_LIBS), )
ifeq ($(OS),Darwin)
LIBS = -L./ -L../../simulatorCore/lib -L/usr/local/lib -lGLEW -lglut -framework GLUT -framework OpenGL -L/usr/X11/lib /usr/local/lib/libglut.dylib /usr/local/lib/libmuparser.dylib $(MODULELIB)
LIBS = -L./ -L../../simulatorCore/lib -L/usr/local/lib -L/opt/local/lib -L/usr/X11/lib -lglut -lGL -lGLU -lGLEW -lpthread -lm -ldl -lmuparser $(MODULELIB)
endif				#OS
LIBS = $(GLOBAL_LIBS) -L../../simulatorCore/lib
endif				#GLOBAL_LIBS


CCFLAGS = -g -Wall -std=c++17 -Wsuggest-override -fno-stack-protector
ifeq ($(OS), Darwin)
CCFLAGS += -DGL_DO_NOT_WARN_IF_MULTI_GL_VERSION_HEADERS_INCLUDED -Wno-deprecated-declarations -Wno-overloaded-virtual

CC = g++

.PHONY: clean all test

	$(CC) $(INCLUDES) $(CCFLAGS) -c $< -o $@

%.depends: %.cpp
	$(CC) -M $(CCFLAGS) $(INCLUDES) $< > $@

all: $(OUT)


autoinstall: $(OUT)
	cp $(OUT)  $(APPDIR)

$(APPDIR)/$(OUT): $(OUT)

	$(CC) -o $(OUT) $(OBJS) $(LIBS)

ifneq ($(MAKECMDGOALS),clean)
-include $(DEPS)

	rm -f *~ $(OBJS) $(OUT) $(DEPS)

The last step to compilate this BlockCode in the simulator consists in copying this Makefile in the applicationSrc/simpleColor directory. Then add the BlockCode directory in the list of compilation directories. To do that, edit the applicationSrc/Makefile and add the directory simpleColor to the SUBDIRS variable.

SUBDIRS = simpleColor

Compile codes from the VisibleSim root directory, go to applicationBin subdirectory and run the program:

VisibleSim$ make
VisibleSim$ cd applicationBin/simpleColor
VisibleSim/applicationBin/simpleColor$ ./simpleColor

This first code does not simulate any interesting behaviour anyway. It just runs the startup() function for each block and then stops the simulation.
The developper has to complete the code of the startup function called at the beginning of the simulation for each module.

In order to test this code, you have to download this example of config.xml in the applicationBin/simpleColor directory.


In order to make a distributed program, one module or more must send messages to one of its neighbors. For each kind of message, we associate a method in the main class, this method will be automatically called when a message of this kind is received by the module.

You can complete the previous code by adding events, for each event you must precise a unique name and a class (or simple) type. For example, you can create a message broadcast that sends an integer value int, representing the distance of the sender to the master module.

Message template

A message is a data packed in a object with an id of message type. We propose a template class MessageOf<T> that manage data of type T, T being the type of the message content. This class inherits from the generic class Message. It is possible to use it with simple types (like in the Exemple 1) or more complex class objects. The method getData() returns a pointer to the data of the message.

class Point {
	public :
	float x,y,z;

MessageOf<Point*> mp = new MessageOf<Point*>(ID1,new Point());

Point *ptr = mp.getData();
delete ptr;

Send messages

We propose two functions that send messages from one modules to neighbors:

The two following functions do the same actions but add console message at the sending of each message:

Example 1: coloring

Each module gets an integer variable named distance. Then we propose to complete the code according to the following rules:

  1. Module #1 is elected as the master, it has distance=0 and is drawn in red.
  2. Other modules get distance=-1 that indicates that the distance to the master is not already defined for these modules and they are temporarly colored in light grey.
  3. Module #1 sends its distance to all of its neighbors using a message (BROADCAST_MSG(distance)).
  4. When a module receives a message BROADCAST_MSG(d):
    • If a module receives the message for the first time, (distance==-1), it can deduce that its distance to the master is the distance of the sender plus 1, then distance=d+1.
    • If a module receives the message and has already a distance (distance!=-1), it must compare its distance to the recieved one plus 1 in order to get the shortest.
    • And when a module changes its distance value, it must send it to its neighbors in order to propagate the correction.
    • Then if a module has distance==-1 or distance>d, it sets distance=d+1, change its color and sends its distance to the other neighbors (BROADCAST_MSG(distance)).

We complete the startup function in simpleColorCode.cpp code:


void SimpleColorCode::startup() {
// link function to BROADCAST_MSG message
    console << "start\n";
// initialize random number generator
    if (module->blockId==1) { // master id is 1
        setColor(RED); // initial color of master block
        distance=0; // distance to master block is 0
// send message to all neighbors
        sendMessageToAllNeighbors("Broadcast",new MessageOf<int>(BROADCAST_MSG,distance),100,200,0);
    } else {
// for other blocks
        distance=-1; // already unknown distance
        setColor(LIGHTGREY); // initial color

and the SimpleColorCode::myBroadcastFunc function:

void SimpleColorCode::myBroadcastFunc(const MessageOf<int>*msg, P2PNetworkInterface*sender) {
// reference distance given by the message data
  int d = *msg->getData()+1;
  console << "receives d=" << d << " from " << sender->getConnectedBlockId() << "\n";
  if (distance==-1 || distance>d) {
    console << "update distance=" << d << "\n";
    distance = d; // update distance
    setColor(tabColors[distance%8]); // change color
// send update to all neighbors but the sender
    sendMessageToAllNeighbors("Broadcast",new MessageOf<int>(BROADCAST_MSG,distance),100,200,1,sender);

Figure 1 : Result of the running of the simulation with a configuration of 2240 robot blocks placed in a tube (8≤ r < 10 and h=20). Figure 2 : Result of the running of the simulation with a configuration of 2520 3Dcatoms placed in a tube (8≤ r < 10 and h=20).

Actuators and sensor events

Some of the modules admits actuators to move or sensors to detect 'tap' of the user on the module.

Sensors first are associated to an event function that is run when the detection occurs. For example, blinky blocks admit tap sensors, then if we define the onTap method in our codeblock class, it automatically runs when you use the "tap" menu on the blinky block in the visual interface of VisibleSim.

To move a module (that is able to move, like smartblocks, robotblocks, 2D catoms or 3D catoms) you can schedule an event with of adapted type to the module system. For example, considering a smart block, you can schedule a TranslationStartEvent event precising the time of starting, the module that must be affected and a final position of the module. At the end of the motion, the onMotionEnd function will be automatically ran.

void SimpleMotionCode::startup() {
	if (module->blockId==1) { // if id is 1, it moves
		Vector3D finalPosition;
		scheduler->schedule(new TranslationStartEvent(scheduler->now()+1000,module,finalPosition));

void SimpleMotionCode::onMotionEnd() {

Communication with VisibleSim interface

Output to the simulator console

VisibleSim interface has a console panel on the right that can be used to write some execution information allowing to follow the execution of programs.

This panel shows the global list of outputs of all the running modules or only outputs that concerns the selected block.

In order to add a line in the console from a BlockCode, we can use the console object like a classical output streambuffer. For example, the following code will be used to draw a text and the content of the variable d. In the interface, the entry will precise the time and the id of the block that generate the message.

    console << "update distance=" << d << "\n";

Be carefull, use "\n" end line character instead of "endl" in this case.

Benoît Piranda