• Nenhum resultado encontrado

Simulator for a Eco-Marathon's vehicle

N/A
N/A
Protected

Academic year: 2021

Share "Simulator for a Eco-Marathon's vehicle"

Copied!
98
0
0

Texto

(1)
(2)
(3)
(4)
(5)

Resumo O projecto ICARO ´e um projecto desenvolvido pela Departamento de Electr´onica, Telecominuca¸c˜oes e Inform´atica da Universidade de Aveiro que teve in´ıcio em 1998. O objectivo deste projecto ´e a constru¸c˜ao de um carro para competir na Eco-Maratona da Shell.

Esta disserta¸c˜ao apareceu de uma necessidade sentida no projecto ICARO: testar diferentes estrat´egias de condu¸c˜ao sem a necessidade de colocar o carro numa pista real. O objectivo proposto foi, consequentemente, a cria¸c˜ao de uma aplica¸c˜ao que permitisse desempenhar essa tarefa.

O trabalho realizado e apresentado nesta disserta¸c˜ao consistiu na especi-fica¸c˜ao e implementa¸c˜ao de um simulador para os ve´ıculos desenvolvidos no ˆambito do projecto ICARO, os quais participam regularmente na com-peti¸c˜ao internacional Eco-Maratona organizada pela Shell. A fase inicial deste projecto consistiu na cria¸c˜ao de uma aplica¸c˜ao gen´erica, que serviu de base para o simulador, que mostrava ao utilizador a interac¸c˜ao entre cor-pos r´ıgidos. Para desenvolver este simulador foram utilizadas as bibliotecas OpenGL e a Open Dynamic Engine(ODE), sendo um dos principais desafios a jun¸c˜ao entre a simula¸c˜ao f´ısica e a sua visualiza¸c˜ao. O simulador recorre ao ODE para fazer a modela¸c˜ao de parte do ve´ıculo e do ambiente que o rodeia, utilizando igualmente modelos matem´aticos para os elementos que n˜ao s˜ao directamente suportados por aquele.

Nesta disserta¸c˜ao ´e tamb´em apresentada uma vis˜ao global sobre o problema da simula¸c˜ao, bem como uma an´alise sucinta de outras bibliotecas que est˜ao dispon´ıveis e que podem ser usadas em aplica¸c˜oes do mesmo g´enero. Neste projecto foi desenvolvida uma arquitectura para um simulador bas-tante rubusta e que poder´a ser utilizada como base para outros simuladores. Para al´em da arquitectura tamb´em foi criado um simulador gen´erico que permite ao utilizador visualizar interac¸c˜oes entre corpos r´ıgidos, podendo o utilizador alterar o que est´a a ser simulado. Depois deste simulador desen-volvido o objectivo foi tornar este simulador gen´erico num simulador para o ICARO. Para isso foram adicionadas algumas funcionalidades ao simulador gen´erico. N˜ao foi possivel terminar o simulador para o ICARO, apesar de grande parte do carro ter sido modelado.

(6)
(7)

Abstract The project ICARO is developed in the Department of Electronics, Telecom-munications and Informatics of the University of Aveiro. The project stated in 1998 with the goal of developing a car to participate in the Shell Eco-Marathon Competition.

The motivation for this project was an objective problem that surfaced within the ICARO project: to test different driving strategies with the ICARO vehicle without having to place it in a real track. The project goal was therefore to implement an application that could perform this task. The work developed and presented in this thesis is a simulator engine with a graphical user interface for the vehicles build within the ICARO’s project, which regularly participate in the Shell Eco-Marathon international com-petitions. This work started with the development of a simulator system for the interaction between rigid bodies. To build this simulator some well known libraries were used like OpenGL and Open Dynamic Engine(ODE). The main purpose was to join the graphical and the physical simulation and make them interact with each other. The simulator models some parts and interactions of the vehicle using mathematical expressions while other parts using ODE.

An overview of the simulation problem and a short analysis of some other libraries that can be used in this type of applications, can also be found in this thesis.

In this project an architecture for a simulator was developed. This architec-ture is scalable and allow a programmer to develop one simulator with it. One example of implementation of this architecture is the generic simulator developed in this project. This simulator shows to the user interactions between rigid bodies. A goal of the project was the creation of a simulator to the ICARO vehicle, to do this some features were added to the generic simulator. It was not possible to finish the ICARO’s simulator but the major parts of the vehicle were modeled.

(8)
(9)

Contents

1 Introduction 1 1.1 Motivation . . . 1 1.2 Goals . . . 2 1.3 Overview . . . 3 1.4 Structure . . . 4 2 Simulation 5 2.1 Physical Simulations . . . 5

2.2 Graphical User Interface . . . 7

2.3 Interaction between Simulator Engine and Graphical User Interface . . . 12

2.4 Open Dynamic Engine . . . 12

2.4.1 Bodies . . . 13 2.4.2 Joints . . . 14 2.4.3 Simulation in ODE . . . 16 2.5 OpenGL . . . 18 3 Simulation Framework 21 3.1 Architecture description . . . 21 3.1.1 Cycle handling . . . 22 3.2 Physical simulation . . . 23 3.2.1 Modelling . . . 24 3.3 User interface . . . 25

3.3.1 User Interface structure . . . 26

3.3.2 Visualization using OpenGL . . . 26

3.3.3 Input device . . . 28 3.4 Initial configuration . . . 28 3.5 Implementation details . . . 29 3.5.1 Cycle handling . . . 30 3.5.2 Class diagram . . . 31 4 ICARO Simulation 33 4.1 The vehicle . . . 34

(10)

4.1.2 Graphical model of the vehicle . . . 38 4.2 The track . . . 38

5 Conclusions 47

6 Glossary 49

(11)

List of Figures

1.1 Overview of the rigid body simulation system. . . 3

2.1 Direct3D in the program stack . . . 8

2.2 Direct3D Transformation Pipeline . . . 9

2.3 Capped Cylinder form . . . 14

2.4 ODE Joints . . . 15

2.5 ODE cycle . . . 16

2.6 OpenGL hierarchy . . . 18

2.7 OpenGL Visualization Programming Pipeline . . . 19

3.1 Overview of the rigid body simulation framework . . . 22

3.2 The physical simulation cycle . . . 26

3.3 User Interface thread flow graph . . . 26

3.4 The visualization thread flow graph . . . 27

3.5 Clock Handling . . . 30

3.6 The general construction of a part . . . 32

4.1 ICARO’s cars . . . 34

4.2 Traction system simulator . . . 35

4.3 Nogaro track . . . 39

(12)
(13)

Chapter 1

Introduction

1.1

Motivation

ICARO is a project, supported by the University of Aveiro and developed in its Depart-ment of Electronics, Telecommunications and Informatics, that, with the goal of developing a car to participate in the Shell Eco-Marathon Competition [10], appears as a multidisciplinary environment where students can apply their knowledges and skills in areas like electronics, mechanics, and informatics.

The Shell Eco-Marathon begun in 1939 in the Shell research laboratory in the U.S. and it was a friendly wager, among the researchers of Shell, to see who could do more miles per gal-lon, with their vehicles. This competition was expanded to Europe and in 1985 started with the current form in France, attracting many engineers and scientists from over 20 countries in Europe. For the first time in 2007 happened in California Speedway the Shell Eco-marathon Americas that involved some countries from the American continent. In the European com-petition, a new category of competition appeared: the ”UrbanConcept” vehicles. They are futuristic prototypes, designed to reduce the drag and maximize the efficiency, going towards the needs of today’s drivers. In the Shell Eco-Marathon competition, the vehicles can be powered with any of the available fuels like diesel, petrol/gasoline and liquid petroleum gas, as well as alternatives like GTL, solar, ethanol, hydrogen and biofuels.

The main challenge of this competition is to build a vehicle that with a fixed amount of fuel travels the farthest distance, although this is done in an indirect way. All cars have to travel a fixed distance with an average speed at least equal to 30km per hour. The car with the lower consumption wins. In order to compare the efficiency of cars using different types of fuel, a formula is used that translates the car’s fuel consumption to an equivalent one.

To increase the interest of this competition and to award some other aspects of the vehicles some other competitions were created inside the Eco-marathon. These competitions award different areas where the competitors should pay some attention. They are: Safety Award, Technical Innovation Award, Design Award, Communications Award and Social/Hospitality Award.

The project ICARO was born in 1998 in the University of Aveiro (UA). It is leaded by the Department of Electronics, Telecommunications and Informatics, but it has benefit

(14)

from the participation of other institutions, like the Superior School of Arts and Design from Matosinhos, the Laboratory of Optics and Experimental Mechanic, and the Dept. of Mechanics from ESTGA, Dept. of Mechanics from UA, Dept. of Environment and Planning from UA and Dept. of Comunication and Art from UA. A first car, gasoline based, started to be built at that year, which have participates every year til 2006. The ICARO vehicle won, along the years, some awards in parallel competitions of the Eco-marathon. Also, year after year the car was evolving making better results in the fuel consumption. Here are the awards won and the evolution in terms of fuel consumption:

In its first participation, in 1998, the vehicle won the first prize of design and the prize of International Communication. Its performance was 208km with 1 liter of fuel.

In 1999 ICARO accomplished a new team record, doing 301km with 1 liter of fuel.

In 2000 ICARO accomplished a new team record, doing 510km with 1 liter of fuel. It also won the first prize for International communication.

In 2002 the best results were achieved. 598Km with 1 liter of fuel, followed by 673Km marked the top results of the first version of this prototype.

Since 2006 a new car is under development, but its construction has been delayed essentially because of budget problems.

In the last years, the competitions took place in the track of Nogaro, France. This is quite far from Aveiro. The vehicle needs to be tested prior to the competition to ensure that it doesn’t have any problem. Most of these tests do not need to be performed on the racing track. But, to obtain a good fuel consumption it is important to know quite well the track. This is a major problem, because it is almost impossible to go to the track to test the vehicle. A track nearby could be rented to test ICARO but it is still too expensive and does not completely substitute the one where the competition is taken place.

The construction of a simulation system that could simulate the movement of the ICARO’s car in the competition track, while estimating the fuel consumption, appears as a desired framework. This system should create virtual prototypes of the vehicle and track and allow the driver to drive it. The ICARO’s car is equipped with a wireless steering wheel. It should be interesting if this wheel could be used to drive the virtual car. The creation of this framework was the main motivation to this work.

1.2

Goals

The main goal of this project is to design and implement the simulation framework referred to in the previous section. It must include a physical simulation part and a user interface part. The system should be fed with real data, like specifications of the vehicle and the topographic information of the track. In this way, it can be adapted to changes in the vehicle and to different tracks.

Since we are interested in fuel consumption, the physical simulation of the car must include the traction system.

(15)

The user is part of the system, since he/she is going to drive the virtual car. Due to these characteristics, a car moving in a track, where the user is the pilot, a 3D visualization is required. The car can be controlled through the keyboard or the mouse. But, the possibility of using the steering wheel of the real car should be considered in the design of the system.

1.3

Overview

The design and implementation of the simulator was divided into two stages. In the first stage, a system to simulate and show the interaction between rigid bodies in a 3D space was built. The design of this system took into consideration the existence of supporting libraries. In one side, the Open Dynamics Engine (ODE) library was used to aid in implementing the physical simulation part. In the other side, the OpenGL graphical library was used to implement the 3D visualization.

Figure 1.1 gives a general view of this simulation system. It was developed to ensure the separation between the physical simulation and the user interfaces parts. There is a central memory where the world (interacting bodies) is represented. This representation is both physical and graphical. A physical processing module determines how the bodies move over time, updating the world accordingly. The graphical module shows the bodies to the user. In the figure there is a unit called Input on physics. This unit exist to create an abstraction to the possible means of input available. This happens because the user is given the possibility of driving the vehicle using either the keyboard or the steering wheel of ICARO. When the vehicle is driven with the keyboard OpenGL is used to capture the event of the keys and act

User Graphic Physic Memory Parser Initial data Input on physics Keyboard Icaro Wheel

(16)

over that unit to apply them on the physical simulation. When the vehicle is driven using the steering wheel of ICARO a new module is used to catch the event generated by it and then acts over the unit to apply the changes on the physical simulation. Another feature of the system is its configurability. Through a human readable configuration file the user defines the characteristics of the objects to simulate and their initial states.

In the second stage, the rigid body simulator is adapted to simulate the ICARO’s vehicle and the Nogaro’s track. To adapt the simulator there were some aspects of the vehicle that needed to be modeled. Also the track needed to be modeled to the existing environment. The track was mapped using the cartographic map. To model it into the format that is used to input data to the simulator, a translator was implemented. To model the vehicle, it was also necessary to develop a set of equations in order to ensure the model is as accurate as possible.

1.4

Structure

Apart from this introduction this document is composed of four more chapters and four appendices. Chapter two is dedicated to describe some possible libraries that can be used to achieve the goals of this thesis. In chapter three a detailed description of the simulator created is made. The chapter four has the description of the features added to the application, that is described in chapter three, to simulate the vehicle of ICARO. The appendices include some additional technical information, and a user manual. Some examples are also included.

(17)

Chapter 2

Simulation

This thesis main goal is to provide a simulator to ICARO team. A simulation is an attempt to model a real-life or hypothetical situation. Therefore a simulator isn’t only useful to model something like a piece of a machine but it’s also useful to predict a behavior that can occur in real-life by changing some of the variables that are used. A virtual visualization of any object can be considered a simulation of reality. This type of simulation is the main basis of computer games. Other types of simulations also exist, like the simulation of a natural system, of a volcano eruption or of a hurricane. In this type of simulations the graphical part is not very important, while the physical data is maybe crucial to conduct scientific studies. In this chapter a more detailed overview of the physical and graphical simulation is given, as well as the way they can interact to provide useful results.

2.1

Physical Simulations

The most important part of the ICARO simulator that needed to be developed was the physical part. There could be two possible approaches: either to build a physical simulator for the vehicle from scratch or use a physical engine that already exists do model the system. The approach of building a physical simulator for the vehicle have been addressed in a pre-vious work, and most of the physical calculation work was already made [9]. Nevertheless, the decision for using a physical engine that already exists was adopted, both to explore its capabilities and because it has been assumed that it would be a more efficient way of getting practical results.

There are several physical simulation engines available that could be used and most of them are open source (Open Dynamics Engine, Bullet, Tokamak physics engine and others). Others, on the other hand, have closed source or limited distribution, like PhysX[3]. The main purpose of these engines is to save the developers from the work of writing the code to handle the complex physical interactions between all the objects involved in the simulation.

(18)

PhysX

PhysX[3] is an engine created by AGEIA. Due to the success of this engine, one of the first extension cards with a PPU1 that used the PhysX algorithm’s to speed up the physics

processing was created. In February of 2008 NVidia bought AGEIA and now the PhysX engine is integrated in the NVidia CUDA framework2 and due to the cancellation of Havok

FX by Intel, PhysX on CUDA is the only available solution for effective physical processing on a GPU. There isn’t much information available about the structure or the way the engine works.

This engine is used in some important software, like the Unreal 3 engine, Microsoft Robotics Studio,Adobe Director 11,Unity. The Physics Abstraction Layer3 can also use

PhysX. PhysX has support for COLLADA, which is an interchange file format for inter-active 3D applications supported by almost all the most important digital content creation tools. This feature gives a great advantage to the library, because the developers don’t need to waste time creating conversion tools from the CAD program format into the format their application uses.

In short this is a very good physics engine. The only real problem is that its not open source. That was the main reason why this library wasn’t selected as the physical engine to use in this particular simulator.

Bullet

Bullet[5] is a professional collision detection and physics library. The development of the library started in 2003 and since 2005 it’s as open source library under the ZLib license.

The library run under *nix OS, Mac OS and Windows and is written in C++. A new port have been made to C] that works on Windows and Xbox 360 XNA. This is a library that is currently under active development. One of the last developments was the multithread support.

COLLADA Physics is used to specify the physical contents that are going to be simulated. These contents can be created using 3D modelers like Maya, Max, XSI, Blender and Ageia’s CreateDynamics tools. Bullet is also integrated in the Blender 3D modeler.

The main features of Bullet are:

Collision detection using ray casting in a continuous or discrete time.

Includes all the basic shapes (Box, Cylinder, Cone, Sphere, ConvexHull, Capsule) and concave and convex meshes.

1PPU - Physics Processing Unit

2CUDA is Compute Unified Device Architecture, which is a framework that allows programmers to develop

programs to the graphic processing units using the C programming language

3Physics Abstraction Layer is a well known library that creates a layer between applications and the physical

(19)

COLLADA physics import/export with tool chain.

Cell SPU optimized version available through Sony PS3 DevNet.

This is a very complete library that can be used in several platforms. It could have been the choice to serve as basis for this simulator.

Open Dynamic Engine

Open Dynamic Engine (ODE) was the chosen engine to simulate the physics for the ICARO application. The choice falls into this engine because it is an engine that is used in a big amount of other simulator as well as in some computer games. This engine is used for simulating articulated rigid body structures and, due to some of its features, it is fairly easy to use and to understand where and what to do to get a good simulation.

This engine uses and approach to a continuous time simulation by implementing time steps. These steps can be defined by the user, making the simulation more or less accurate. This engine separates the collision event from the normal behavior using two different entities, one to represent the bodies and the other to represent their form. Another good feature of ODE is the amount of forms that can be represented as well as the amount of connections available between these forms. In section 2.4 a more detailed description of ODE is made.

2.2

Graphical User Interface

The most widely spread simulation graphical user interface applications that exist, at this moment, are computer games. Although the main purpose of these applications is the entertainment of their players, the graphical visualization is not only intended to be used as an entertainment tool. The area of computer graphics is the base of the graphical interface for simulations, and this area is being developed at a very high rate. The computer graphic science is a pretty new science and one of its main goals is to create a computer environment that resembles real life.

Other significant use for the graphical user interface is the scientific area. Its quite common to found scientific studies that produce huge amounts of results, almost impossible to interpret without a practical way of showing them in a way that allow a global understanding. Graphical data visualization is, therefore, a major help on the analysis of any kind of scientific data.

A huge amount of libraries can be found to help the creation of applications for data visualization or even to make applications more attractive and easier to work with. One of the main problems facing the use of these libraries are the portability issues; we can find libraries that only work either on Windows Systems or in *nix Systems.

Examples of graphical libraries available for development support are: OpenGL, DirectX, VTK. These libraries are well-known libraries that are used in a great amount of applications that exist today. The main difference between the mentioned libraries is that OpenGL and VTK can run under more then one OS, while DirectX can only be used in the Microsoft OS’s.

(20)

DirectX

The DirectX[6] library was developed by Microsoft and it’s the most used library on applications that run under Microsoft OS’s. This library was designed to deliver the most advanced, stable, and visually impressive graphics experience on Microsoft platforms. It is a package of small libraries which is distributed as a kit to programmers, containing a graphical library, an input library and a sound library. The graphical library has Direct3D, D3DX utility library, and DXGI components.

The most important graphical component is the Direct3D, and the aim is to create an abstraction communication layer between the user applications and the graphics hardware driver.

Figure 2.1: Direct3D Component found in the system[2].

As can be seen in figure 2.1 the Direct3D is found at the same level as GDI4. The main

difference between GDI and Direct3D is that Direct3D is directly connected to the graphical driver getting a better performance.

In figure 2.2 the Direct3D 10 API rendering pipeline is shown. All the stages can be configured using the API. Stages featuring common shader cores (the rounded rectangular blocks) are programmable using the HLSL5 programming language. The possibility of

pro-gramming these blocks makes the pipeline extremely flexible and adaptable. The purpose of each of the stages is listed below.

Input-Assembler Stage This stage is responsible for the data supply to the pipeline.

Vertex-Shader Stage In this stage all the vertex are processed, one, and only one, at a

time; the operations typically performed are transformation, skinning, and lighting.

Geometry-Shader Stage In this stage a entire primitive is processed. A primitive can be

a triangle, a line or a point. Each primitive can include vertex information for processing any edge-adjacent primitives.

4GDI stands for Graphics Device Interface and it’s one of the three core components of the Windows User

Interface.

(21)

Figure 2.2: The transformation pipeline of the Direct3D API[6].

Stream-Output Stage This stage places in memory the primitives data. From the

mem-ory the data can either re-feed the pipeline to build another primitive or can be read by the rastering stage.

Rasterizer Stage In this stage the primitives are clipped and prepared to the pixel

shader. This stage also determines how pixel shader is invoked.

Pixel-Shader Stage This stage receives the data of the interpolated primitives and

gen-erates data per pixel; one of the examples of the data generated is the color of each pixel.

Output-Merger Stage This is the final stage of the pipeline and its main responsibility

is to combine all the output data generated by the previous stages with the contents of the render target.

In short, this is a good library that could be considered if the simulator was meant to be developed for a Microsoft environment.

(22)

VTK

VTK[14] library is a well known and used library in the computer graphic area that supports the representation of data information in a visual way. This library is used for 3D computer graphics, image processing, and visualization. This library was created and is maintained by Kitware Inc.

The VTK library was written in C++ and is class oriented. Wrappers for Tcl/Tk, Java, and Python cam also be found. VTK supports a wide variety of visualization algorithms in-cluding scalar, vector, tensor, texture, and volumetric methods as well as advanced modeling techniques such as implicit modeling, polygon reduction, mesh smoothing, cutting, contour-ing, and Delaunay triangulation.

The design goals of VTK were:

Easy to use and easy to distribute and embed a library.

Flexibility, by having the possibility of use a compiled and a interpreted application.

The use of standard languages, instead of implementing is own.

Portability of the library, making sure it can be used in different systems.

An Open Source library.

Simple API that could easily be used by anyone.

These goals have been globally accomplished and, as a result of that, VTK is a very powerful library which is used in a great number of applications. The design of the object is divided in two distinct parts. The first one is the graphical model that is an abstraction model for 3D graphics. The second one is the visualization model, which is the data-flow model of the visualization process.

The graphical model of VTK is used to create an abstraction to the 3D graphical model making it easier to use and understand. This abstraction is influenced by the current win-dowing system. The graphical mode can be divided in nine basic objects.

Render Master - Creates the render window and implements the abstraction for the

window manager.

Render Window - Used to manage the Render Window. In each Render Window it is

possible to have more then one Renderer drawing the final scene (the image that will be displayed to the final user).

Renderer - Coordinates and create the rendering of the lights, cameras, and actors.

Light - Creates the lights used in each scene.

Camera - Used to manage all the properties that can be attributed to a camera, like

(23)

Actor - An actor is an object that will be rendered and drawn in a scene. The actor

can be a mapper, property, and a transform object.

Property - This represents the rendering attributes that an actor can have, which can

be color, lighting, texture map, drawing style and shading style.

Mapper - Represents a geometric definition of an actor and maps it through a lookup

table.

Transform - This object is a 4 x 4 matrix that specifies the position and the orientation

of actors, cameras, and lights.

The visualization model is based in a paradigm that was adopted by many commercial sys-tems, the data-flow paradigm. In this paradigm we have a group of modules that interact with each other responding either to demands or to the user input. The modules interact with each other using a network. This is a flexible paradigm because the modules can be changed, changing its algorithms, without having to change all the application.

To implement this paradigm VTK was divided in two groups of objects, the data objects and the process objects. The process objects are the modules, from the paradigm, and they perform all the action needed by the visualization. They can be from three different types: sources, filters, and mappers. The source modules are the first modules in the chain and they create the datasets. Filter modules are the middle modules. Mapper modules are the end of the chain.

The data objects, on the other hand, are the objects that are passed between the modules. VTK has five different types of data: polygonal data, structured points, structured grid, unstructured grid and unstructured points.

One of the major advantages of VTK is the possibility of code distribution in order to ensure that, if the input is fed with is a big amount of data, it can be processed as quick as possible. This is feasible in VTK because of the data-flow paradigm and the division in modules of the application.

In short, VTK is a good library that is used in a significant number of applications that perform simulations with a big set of data as the input. Another good thing about this library is the simplicity of its interface.

OpenGL

OpenGL is one of the most well-known graphical libraries under an open source license. This is a library that is used in a big amount of application as the graphical library basis, because it’s easy to use and the documentation is both very good and very easy to found. Another advantage of this library is its portability due to the way the library works. This library interacts directly with the hardware. This allows the application to run faster and be portable.

OpenGL can be used to draw simple or complex forms on the screen. A set of programming languages can also use it due to specific wrappers that are available to software developers. A more detailed description of this library is made in section 2.5.

(24)

2.3

Interaction between Simulator Engine and Graphical User

Interface

A simulator doesn’t need to have both a graphical user interface and a physical simulation engine to be a good simulator. In some cases no physical engine is needed, or it may add an overhead to the system that it’s not bearable for a particular application. On the other hand, there can be simulators that don’t need a graphical environment because the only purpose of the simulator is to generate data either to other applications or to be independently analyzed in other sense. In the developed simulator for the ICARO project both the simulation engine and the graphical user interface are needed.

The ICARO simulator is intended to show the user the behavior of the vehicle while it’s being driven. The interaction between the graphical interface and the physical simulation can be made in two distinct ways: either by mixing everything wrapping the simulator in a single application, or by separating both, and make them interact through the use of a shared memory. The apparent advantage of mixing everything is the speed at which the code can be made, because there is no need to think in a structure of the application. This can, on the other hand produce a cluttered piece of code, where evolution and maintenance can be very hard to perform. The great advantage of separate the simulation engine from the user interface is the low coupling between the applications, leading to a well structured solution. In this approach all the structure of the applications must be pre-established regarding the fact that, although being independent, there must be an interface point between them. This type of architecture sometimes can take long to be created and developed but there are bigger advantages in the future if something needs to be changed or if any problem would appear.

2.4

Open Dynamic Engine

ODE[11] library was chosen as the engine to the physical simulation because it is a mature and stable library. With a fast search a big amount of applications can found that use this library as their physical engine. Among them we can find games, CAD applications, simulation applications and more. One of the samples of an application that uses ODE is a simulator developed by Humanoid Team Humboldt to simulate the behavior of their robot in the field. Another good example of the use of ODE is Gazebo[7] that is a multirobot simulator for outdoor environments.

The library also provides a set of tools that allow the user to change almost all the aspect of the created bodies, as well as the external conditions and forces to be applied, when these forces are to be applied and how the bodies are connected to each other.

ODE is a good tool for simulating rigid bodies and, in particular, the articulated ones. Articulated rigid bodies are groups of rigid bodies that are inter connected in a hard or soft6

way. The library is designed to allow the user to define the type of simulation, iterative or real-time, and also to allow the user to change the world while the simulation is running. Another

6The bodies that are connected in a hard way are bodies that can’t move apart from each other, while the

(25)

feature of the library is the possibility of using one external collision detection system. The available collision primitives are: sphere, box, capped cylinder, plane, ray, and triangular mesh.

The supported features by ODE are[12]:

Rigid bodies with arbitrary mass distribution.

Joint types: ball-and-socket, hinge, slider (prismatic), hinge-2, fixed, angular motor, universal.

Collision primitives: sphere, box, capped cylinder, plane, ray, and triangular mesh.

Collision spaces: Quad tree, hash space, and simple.

Simulation method: The equations of motion are derived from a Lagrange multiplier velocity based model due to Trinkle/Stewart and Anitescu/Potra.

A first order integrator is being used. It’s fast, but not accurate enough for quantitative engineering yet. Higher order integrators will come later.

Choice of time stepping methods: there are two different method available. The major difference between them is the time they take to simulate a step and the accuracy of the calculus.

Contact and friction model: This is based on the Dantzig LCP solver described by Baraff, although ODE implements a faster approximation to the Coulomb friction model.

Has a native C interface (even though ODE is mostly written in C++).

Has a C++ interface built on top of the C one.

Platform specific optimizations. 2.4.1 Bodies

A rigid body, in ODE, is described in two different ways: the Body and the Geom. The Body is the physical definition of the rigid body. This definition include the mass of the body, the forces to be applied to it and the position of the centre of mass. No form is saved in a Body.

The Geom is the collision forms that can be define to a body. A Geom can be associated with a Body or not. It is possible to create a rigid body without using a Body definition. The main difference between a rigid body without a Body and a rigid body with a Body is the possibility of the later to move around the world. So, if a floor is needed in our application a Geom that isn’t associated with any body should be created.

The possible Geoms forms are:

(26)

Figure 2.3: Representation of a capped cylinder.

Box — To define a box is needed the length of the box in all the 3 coordinates.

Plane — To define a plane the equation of the plane is needed. This is given by

a ∗ Px+ b ∗ Py + c ∗ Pz = d

where a,b,c and d must be supplied.

Capped Cylinder — A representation of a capped cylinder can be found in figure 2.4.1. To define this Geom the length of the cylinder and the radius of the half-spheres that are in the tops of the cylinder are needed.

Ray — A ray is different from all other Geoms because it doesn’t represent any solid object. It’s an infinitely thin line that starts in a specified point and extends itself into a defined length in the direction of the Geom’s local Z-axis.

Triangle Mesh — A triangle mesh can represent one approximation to any surface. With it it’s possible to create all the forms that where mentioned as possible Geom or any other form. To create a form of this type, a group of points must be defined as well as the triangle that these points create with each other.

Geometry Transform — This form is, like the name says, a transformation of another geometric form. Allows the Geom to be more flexible; for example, you can offset the centre of a sphere, or rotate a cylinder so that its axis is something other than the default.

User Defined — This type of form is a new type that can be defined by the user and can be almost anything. The user must define the collision detection function and need also to define the bounding box that involves the Geom which is used to see if this object is colliding with another object.

2.4.2 Joints

Using ODE it’s possible to create a very complex structure of objects using multiple geoms with one body. A structure like this it’s solid and the parts cannot have movement between them; one example of this is a table. Creating a complex structure of objects that can change

(27)

Figure 2.4: Joints available in ODE: 1)Ball and Socket Joint 2)Hinge Joint 3)Slider Joint 4)Universal Joint 5)Hinge-2 Joint 6)Contact Joint 7)Angular Motor Joint[12].

position between them, like a bicycle, it’s also possible using joints to connect each part of the structure.

ODE have a a set of seven joints available to the user and they can be depicted in figure 2.4.

Ball and Socket — This joint can be used to connect 2 objects that can move over each other in different directions. An example of this behavior is a human knee.

Hinge — This joint can be used when we have 2 objects that can move around only one axis. An example of this behaviour is a door.

Slider — This joint can be used when the 2 objects only change their relative position along one axis. An example of this behaviour is a shock absorber.

Universal — This joint can be used when we have 2 objects that can move around two axis. An example of this behaviour is a car transmission.

(28)

Object definition User changes ODE simulation step Collision Solver User intervention area

ODE simulation cicle

Figure 2.5: ODE’s cycle of simulation with the highlight of the user interaction areas.

Hinge-2 — This joint can be used when we have 2 objects that can move around two different axis which are perpendicular to each other. An example of this behaviour is the steering wheel of a vehicle.

Contact — This joint is only created when 2 objects collide. The main purpose of this joint is to ensure that when 2 objects collide they are bound together.

Angular Motor — This is the most complex joint available. With this joint it is possible to control the relative angular velocity of the 2 objects. The velocity can be controlled on the 3 axis. This joint works in 2 different modes, Euler and User mode. In the User mode it is the user that directly controls all the axis of the motor. In the Euler mode the motor calculates the Euler angles7 and the axis rotation.

Fixed— This joint is used to connect two bodies or a body and the environment. This joint only make sure that the 2 connected objects are always fixed to each other. The joint shouldn’t be used on a final application and only for debugging purpose. If the two bodies need to be fixed it’s better to combine them in only one body with two Geoms. 2.4.3 Simulation in ODE

The figure 2.5 depicts the simulation cycle in ODE. An highlight is presented where the user can intervene in the cycle. The first step of the cycle is the creation of all the objects that are going to be simulated. The user is fully responsible for the creation of this step. If nothing is defined in here nothing will be simulated. The User changes is one of the most important steps in the simulation because it is in here that the user can either add forces applied to the bodies or move the objects. Changes on forces resulting from this user intervention are only

(29)

applied for one cycle and then they are reseted. If a force must be applied for more then one step it must also be added every single cycle. The last step is the ODE simulation step. In this step all final results and changes are calculated. If a collision is detected while performing the step a routine is called to solve it. This routine is written by the user and can define the behaviour of the objects when they collide with each other.

To do a simulation in ODE some basic components are needed such as the world, the space and the collision handling. The world, in ODE, is where all the objects that are going to be simulated exist. A set of attributes can be define for the world, like the gravity force, the default ERP value(see page 50) or the default CFM value(see page 49).

The steps of the world can be calculated using two different approaches. In the first one, the world consists off a big matrix that takes m3 to calculate each step and uses m2 memory,

where m is the total number of constraint rows. This is the most accurate method to use but, for large systems, is very slow and demands a lot of memory resources. The second approach, that can be used in larger systems but has poorer accuracy, in a near-singular system8. This

approach takes time in the order of m ∗ N and memory in the order of m, where m is the total number of constraint rows and N is the number of iterations.

To detect a collision ODE uses a predefined cube that surrounds the geom. When two of these cubes intercept the probability of occurrence of a collision is huge; when this happens the collision routine is called. This routine is responsible for evaluating the collision and creates the contact joints between the geoms that have collided. When a collision occurs one or more contact joints are created between the bodies. The user can define the maximum number of contact joints that can be created for each collision. The time taken to calculate both the collisions and the step of simulation depends on the number of contact joints created. The space, in ODE, is almost the same as a world but know applied to the collisions. The space is a container of geoms and/or other spaces. This method is used to speed up the collision detection. Without the cubes the collision detection has to be made per two geoms that could be colliding in the entire world. Using the subdivision in spaces the collision detection is made only inside the spaces and between spaces, making it very fast because the number of objects passed to the collision detection function is smaller. Therefore the collision detection function has a smaller number of collisions to detect per call. In ODE three types of spaces are available to be used: simple spaces, hash spaces and quadtree spaces.

In the simple spaces the collision detection is made by comparing the cubes around the geoms to see if there are areas where these cubes are intersecting. The time required to calculate the intersections for n objects is O(n2). This space shouldn’t be used for large

systems.

In the hash spaces all the overlap cells of the geoms are recorded internally in a hash structure. The time required to calculate the intersecting geom is O(n) where n is the number of objects. The major difference is that with this structure the objects can be quickly paired. In the quadtree spaces a pre-allocated hierarchical grid-based AABB tree is used to check intersections. This type of spaces should be used when a large amount of objects is

8A near-singular system is a system where high-friction contacts, motors, or certain articulated structures

(30)

considered inside the space.

ODE is a very generic physical simulation engine and, because of that, the only force that is applied by default is the gravity force. All other forces that are needed to any type of simulation have to be added by the user in run-time. The possibility of adding forces to the simulation in every step of the simulation is, therefore, another of its significant features. In fact, forces are not the only thing that can be changed during the simulation; all the world can actually be altered between steps. This allows the user to get total control of the simulation and of the bodies that need to be rendered. For instance, if we want to simulate a car moving in a track, a user set of forces should be considered such as drag force, rolling resistance and friction.

2.5

OpenGL

The graphical library chosen for this application was OpenGL[8]. The library was chosen because it’s one of the most used library in games and also in most of the application that are used under *nix OS. It’s a library used to graphically represent, on the screen, any scene the user may need. The represented scene can be in 2D or in 3D. One of the great advantages of OpenGL is the portability because it ensures that, no matter the OS where the application is running, the visual results are the same. The main reason of this library portability is the level at which it works. It can either interact directly with the hardware or can use any additional software to pre-render the images. With the interaction at this level the library is faster then many others that are based on software only. Another reason to use this library was the amount of documentation and the quality of it, as well as the simplicity to build a graphical environment with a small amount of instructions. In figure 2.6 the API hierarchy of OpenGL is shown.

Figure 2.6: This diagram demonstrates the relationship between OpenGL GLU and window-ing API’s[4].

This OpenGL library can be used to draw from the simplest geometric figure, like a point, to a surface with a complex light schema with a complex texture associated to it. OpenGL gives the programmer access to a great amount of features like geometric and image primitives, display lists, modelling transformations, lighting and texturing, anti-aliasing or blending.

OpenGL library also has wrappers for C, C++, Fortran, Ada, and Java. Due to the abstraction provided, showed in the hierarchy’s diagram, the programmer can save plenty of

(31)

Figure 2.7: In this diagram the visualization programming pipeline is shown[4].

time because he doesn’t need to worry about the compatibility of the graphical code between OS’s.

Finally, another advantage of the OpenGL library is the group of libraries that were created on top of it, which can help developers to create more user friendly applications without having to build all of them from scratch. Examples of these libraries are FreeGLUT and GLUI. Those were also used in this project to create menus, scroll bars and other features.

(32)
(33)

Chapter 3

Simulation Framework

Instead of developing a specific simulation system to support the ICARO project, it was decided to build up a more general purpose configurable simulation environment, which should be used to model ICARO among other systems. While general and configurable, this frame-work is targeted to model systems composed of volume bodies and their interactions. Also, it is assumed that the dynamics of the modelled world should be visualized in a graphic en-vironment. So, a 3D visualization module is part of the framework. Finally, a user, either human or virtual, should interact with the simulation. Thus, an input module must also be included.

In this chapter, this general purpose configuration simulation framework is described. First, the general architecture is presented. Then some implementation details are also con-sidered.

3.1

Architecture description

Figure 3.1 depicts a general view of the simulation framework architecture. It is a multi-thread environment with a shared central memory. This memory is used to represent the world intended to be simulated. Both the objects of the world and its initial state must be loaded at start up through a configuration file. This configuration file uses a XML-based, user readable format, making it simple to describe the system to be simulated.

There are three threads in total. The first one is devoted to the physical simulation and implements a time-driven algorithm. At each simulation time step the world state is updated. As has been stated in the previous chapter, the Open Dynamics Engine (ODE) was used to add in the implementation of this thread. However, as it will be explained later on, not everything in this thread is done in ODE. A second thread is used to show the dynamics of the system to the user. In this thread, as will be explained later, any visual representation can be used to present the system to the user. To test it, OpenGL was used. Finally, a third thread is used to allow user interaction with the system. Here, the input device can be a keyboard, a joystick, a steering wheel, or any other device. Often this thread is merged in the graphical user interface and supported by the visualization library. However, it can also be an independent one.

(34)

Figure 3.1: Overview of the rigid body simulation framework.

Using a multi-thread approach has a number of advantages. With this separation it is possible to work in one of the parts of the application knowing that the other part will not be affected by it. Also, future library updates or specific future code change will only have impact on the particular thread of the application ensuring all the others are untouched and working.

Another clear advantage is related to real-time execution. On one hand, the physical simulation can be a time consuming task. The 3D visualization, on the other hand, can also be a time consuming task, specially if graphical hardware acceleration is not provided. Putting these two tasks in different threads make it possible to update the visualization environment at a different rate than the one at which the simulation is done. Also, one can have different visualization modules, with less or more graphical details, and choose the one to use depending on the hardware available. In this way, one can ensure that the physical simulation is performed at a rate at least close to real time, at expenses of a possible lower visualization frame rate.

3.1.1 Cycle handling

To create a simulator in a computer system we need to use a discrete system, because computers are also discrete systems. This can be accomplished by performing the simulation on a step by step basis. In each step the simulated environment evolution is calculated according to what could have happened in that elapsed time. In most simulators, the time between cycles is made constant, which can simplify the simulation approach. However, simulators with variable step size are also common when this provides a more time efficient

(35)

solution. In the case of the simulator developed for ICARO, the idea is to try to have the same time between steps to make the application more light. To accomplish this, a system that could manage the cycles is needed. This system should manage the time steps of both the physical simulation and the graphical visualization to ensure they are performed at the correct time.

3.2

Physical simulation

The reality to be simulated is composed of volume bodies which can interact among themselves and with fixed surfaces. For instance, a car on a road is a rigid body, or a collection of rigid bodies, interacting with a fixed surface. The bodies can have different masses and different shapes (geometries). Their movements depend on the forces applied and on the points where they are applied. A number of different type of forces is to be considered: gravity, drag, rolling resistance, slip, and friction.

Gravity

Since we are talking about real systems, gravity is always present. It is applied to the centre of gravity of the rigid body.

Drag

Real bodies moving in a fluid, either gas or liquid, are subject to drag, a force that resist their movement. This force is typically modelled using the drag coefficient, a dimensionless value that describes aerodynamic characteristic of the body. It depends upon the velocity of the body, the viscosity of the medium, the shape of the body, and the roughness of the body’s surface. For a car, the usual values are between 0.25 and 0.45.

To calculate the drag resistance [13] the following expression can be used:

F = (1/2) ∗ ρ ∗ v2∗ Cd∗ A

where ρ is the density of the fluid, v is the velocity of the object relative to the fluid, Cd is

the drag coefficient, and A is the reference area. The drag coefficient depends on the shape of the object and on the way it faces the fluid.

Rolling resistance

The rolling resistance is a resistance that is applied to a round object when it gets in contact with another surface, and it is caused by the deformation of the object, or the deformation of the surface, or by the deformation of both. This resistance depends heavily on the material of both the object and the surface, but there are other also factors that contribute to its value, like the radius of the object, its speed or the normal force exerted between the object and the surface.

(36)

To calculate the rolling resistance the following expression can be used:

F = CrrNf

where F is the resistant force, Crr is the dimensionless rolling resistance coefficient or

coeffi-cient of rolling friction (CRF), and Nf is the normal force. Slip

A main motivation for this simulation framework is to model a vehicle in a track. Thus, slip must be considered. It is the relative motion between a tire and the road surface it is moving on. It can be caused by the slip angle, the angle between a rolling wheel’s actual direction of travel and the direction towards which it is pointing, or by the relation between tire’s rotational and free-rolling speeds.

Friction

Relative motion of two surfaces in contact are subject to a resistance force called fric-tion, which is derived from electromagnetic forces between atoms and electrons. Often, it is modelled using the Coulomb friction, which makes the friction force proportional to the normal force exerted between the surfaces in contact. The proportionality is given by the coefficient of friction, a dimensionless scalar value which depends on the materials of the two surfaces.

3.2.1 Modelling

Instead of constructing everything from scratch, it was decided to take advantage of existing rigid body simulation engines. ODE was the one chosen and its main features were described in section 2.4. ODE covers much of the elements needed to implement the physical simulation, but not all of them. Rigid bodies are easily implemented in ODE and have associated masses and shapes (geoms on ODE jargon). Surfaces are implemented by elements with shape but without mass. Since they have no mass, forces have no effect on them. Bodies can be interconnected though joints, which determine their relative movements. For instance, if two bodies are interconnected using a slider joint, their relative movement is limited by the axis of the slider.

ODE evaluate movements of the bodies based on applied forces. There are three different cases to be considered.

Gravity force is always present and ODE takes care of it. Only its value must be given at start.

Friction and slip are only present when two bodies or one body and one surface are in contact. The values of the associated forces depends on the properties of the materials under contact and so can be different for different contact points. ODE, through its collision solver, determines all the contact points and ask the user to provide the contact properties for every contact point. This is done at every simulation step.

(37)

Drag resistance and rolling resistance are not covered by ODE. So, if they are to be considered, the corresponding forces must be provided by the user before the simulation step. As previously referred, ODE provides a way for doing this.

Physical simulation cycle

Under ODE the simulation cycle is implemented by the user, which must explicitly call the simulation step function. Thus, it is possible to execute preparation actions, like reposition of objects or application of forces, before executing the next simulation step. This allows for the implementation of the physical simulation step as it is depicted in figure 3.2 and explained next:

1. (Wait for clock permission) — The thread waits until the clock handler gives permission to proceed.

2. (Check if simulation is still running) — After resuming execution, the thread checks if the simulation is still running. If so, proceeds to the next step; otherwise finishes thread execution.

3. (Prepare next simulation step) — Two actions are preformed: the world is accessed to reposition all the objects, if necessary, and all the forces and torques needed are applied to the objects. Also, some ODE pre-simulation actions are made, like registering callbacks.

4. (Next ODE step) — The ODE function that simulates the step is called. Occasionally, this function detects collisions between objects and calls back a user function to deal with the contact points.

5. (Update World) — The world representation is updated.

3.3

User interface

The user interface is the part of the application the user can see and interact with. It doesn’t need to be a 3D system with wonderfull graphics but should be adapted to the simulation needs. It’s possible to have a user interface that will only show the actual position of the objects in the screen or we can have a racing track with a car driven by the user.

Being a simulator for ICARO, this architecture assumed, from the start, that a graphical user interface was needed to ensure that the user could both drive the vehicle and get feedback from the simulator. But the architecture was changed and a more generic idea of simulator was created. To ensure that this simulator could be used in many other applications, the idea was to change this specific user interface into something the user can create to fulfil his requirements. To develop an architecture like this, an abstraction layer was created using the

Output thread, see figure 3.1. Using this abstraction the user can create his own viewer. This

(38)

Figure 3.2: The physical simulation cycle. 3.3.1 User Interface structure

The thread that control the user interface have some actions that need to be preformed to ensure the user can have the desired feedback from the simulator. To better understand the required actions that are performed a small explanation of figure 3.3 follows.

(Initialize UI) — It’s in this state that all the initial requirements for the user interface (windows, consoles) need to be created and initialized.

(Wait for clock permission) — The thread waits until the clock handler gives permission to proceed.

(Get Data) — Get the data from the shared structure.

(Display Data) — All the data the user want to display should be displayed in this state.

Figure 3.3: The user interface thread flow graph.

3.3.2 Visualization using OpenGL

The User Interface created for the project uses the library OpenGL. This decision was taken because a graphical interface was needed to allow the user to see the result of the experiences he is doing. The simulator will allow a creation of a world composed of objects moving in a 3D space and the visualization should be able to handle them. So, 3D visualization

(39)

support is mandatory. The OpenGL library, whose main features were described in section 2.5, was therefore used to implement the 3D component of the visualization thread.

Typically, any graphical user interface (GUI) application or thread is event-driven. This means that actions, like screen redraw, only occur as a consequence of an event. Events can be posted by a user – a key pressed, a mouse movement, or a mouse button pressed – and by any other event producer. Thus, in the simulation framework, every time the world is updated an event should be posted if we want the view to be updated too. If events that cause a redraw occur at a high rate, it can cause a degradation of the overall system. This degradation can result in the impossibility to implement a real-time simulation. To avoid this, the visualization thread can be executed at a different rate than the physical simulation. Figure 3.4 represents the sequence of actions performed by the visualization thread. These

Figure 3.4: The visualization thread flow graph. actions are:

1. (Initiate OpenGL) — The OpenGL window is initialized.

2. (Creation of the UI) — All the UI is created and placed in the spot where it should be found. At the end of this step the window is shown to the user.

3. (Check if simulation still running) — If the simulation is still running, proceed to next step; otherwise finishes thread execution.

4. (Call main Glut cycle function) — In this step the OpenGL cycle function is called to perform the OpenGL actions.

(40)

5. (Sleep) — In this step the thread goes to sleep to prevent the thread to be always running and going to the processor if its not needed.

6. (Call idle function) — The Idle callback is called to see if a redraw is needed.

3.3.3 Input device

There are two different types of actions a user can apply to the simulation system. On one side, the user may wish to change the way things are shown in the visualization environment. For instance, he/she can change the point of view, the zoom, or a window position in the screen. In this sense, the physical simulation parameters are not affected. Occasionally, if the number of events generated by the user is high, a performance degradation can occur. On the other side, the user may wish to actuate in the physical simulation parameters. For instance, if the system is been used to model a car in a track, the user can press the throttle pedal, which means an external force should be applied to the physical part of the system. This throttle pedal can be a keyboard key that, when pressed, simulates a throttle change action, or it can also be a real pedal that somehow is connected to the system. This type of input actions, that only affect the simulation parameters, doesn’t directly affect the view, since they only change the parameters used in the next simulation step.

If the input device is the computer’s keyboard or mouse, it is likely to be part of the GUI interface, since their events are associated to the active window. In that sense we can assume that the input device is merged in the visualization thread. Actually, the GUI interface capture the keyboard or mouse events and call predefined callback routines that handle them. These routines can change the visualization and simulation parameters. The dashed box around the output and input thread represents that fact. Nevertheless, a real separation between the input and output threads can also exist. For instance, the ICARO’s car is equipped with a wireless steering wheel that can control all variables of the car, like breaks, throttle, steer, horn, or turning motor On and OFF. If we use a device driver to receive commands from that steering wheel, we can also control the simulation physical parameters. This device driver has nothing to do with the GUI interface, and so, in this case, the input and output threads are independent.

3.4

Initial configuration

If one plan to develop a simulation system that, based on a user configuration, can be used to model different real systems, an easy and powerful way of given such initial configuration must be defined. This configuration must cover different aspects of the system, such as:

The bodies that populate the world must be defined in terms of their physical properties, namely mass and shape.

The environment where the bodies move around must also be defined. It is represented as shapes without mass, thus been fixed in the world.

(41)

The initial positions of the bodies in the world must be defined.

If visualization is required, the way bodies and environment are shown to the user must be defined.

¿From the beginning of this project, it was clearly assumed that configurability should be file-based and that the configuration file should be human readable. It was also assumed that a single configuration file should exist, covering the physical and graphical properties of the world elements and their initial positions. An XML-based format appears as the more appropriated to be used. Thus a XML-based language was defined.

The language create a clear separation between the physical and graphical simulation aspects of each object that is going to be modelled. With this configuration its possible to create objects in only one of the sides of the simulation (physical simulation or graphical visualization). The definition of this language can be found in section ??.

3.5

Implementation details

To understand some of the choices made to create this simulator a more detailed expla-nation about the implementation of the application is made in this section.

The programming language used to develop this application was the C++. The decision of using it to develop the application was made because, on one side, almost all the library’s that where researched had a wrapper or were implemented in C/C++, and on the other side the author has good experience using that language. Another reason for the choice of C++ was the underlying paradigm, OOP1. OOP is a good paradigm and the great advantage of

using it is the possibility of hiding the complexity of the operations made over one part inside itself. Therefore, the structure of the application is easier to understand and develop.

As explained in section 3.1 (see figure 3.1), the application was split in two major parts: user interface and physical simulation. To ensure properly communication between them, a central data structure is used. This data structure contains the world description as well as the simulation and interface parameters. Thus, it is the place where all the information about the simulated objects is stored, so that they can be accessed by all the threads. This world was created using one of the properties of C++ that is the static attributes in a class. This way the world is unique. When an instance of the class is created it just represents a connection to the world.

Using this approach, all the information about all the simulated parts can be accessed using an instance of the class by any of the threads of the application. Having only one point with all the information is therefore possible. This type of centralization of information can also become a problem, since it also needs to be both updated and read by different threads.

1Object-Oriented Programing, Object-oriented programming may be seen as a collection of cooperating

objects, as opposed to a traditional view in which a program may be seen as a group of tasks to compute

(”subroutines”). In OOP, each object is capable of receiving messages, processing data, and sending messages to other objects

(42)

Figure 3.5: Sequence of actions performed by the clock handler.

If, at a certain moment in time, there is more then one instance trying to access the infor-mation a conflict may occur. This wouldn’t be a problem if the only access allowed is the reading access. Unfortunately this is not the case, because we must have accesses that read while others are writing back information. In this scenario we have a concurrence problem, and the information can be outdated or can be corrupted due to the writing process that hasn’t ended. To avoid this type of problems a solution must be found to guarantee that the data can only be accessed by one instance at a time. The methods that can be used to ensure this are the creation of semaphores and monitors. In this way it is possible to ensure that only one instance is inside the protected area at a time.

The solution adopted to solve the concurrence problem was the creation of semaphores to ensure that only on instance access the information at a time. This solution can cause some delay on the simulation, because the time spent by the other threads inside the data area can delay the physical simulation. To try to minimize the probability of this problem, all other threads apart from the simulation threads, should be as quick as possible accessing and unlocking the shared data. Synchronization is also needed in this simulator because their will be two threads that are going to change the data. One thread, Input Thread, is responsible for the inputs to the system and can add forces to the world. The other thread, Simulator, will simulate the world and change the position of all the simulated objects.

3.5.1 Cycle handling

To create a simulation that is done step by step there must be a system that can manage it. The developed system is shown in figure 3.5. This system uses the OS signal SIGALARM. A routine was installed in this application to deal with this signal. When the signal is sent

(43)

by the OS the handler is called.

This handler have to decide when the physical simulation can perform another step and also if it’s time to refresh the screen. When these decisions are made the handler wakes up the needed threads to perform their work.

To better understand what is done inside the handler, a small explanation of the actions preformed follows.

Check for pause — See if the simulation is paused; if its paused just end the routine, if

not continues.

Check end simulation — See if the simulation has ended; if ended wakes both threads

and ends the routine, if not continues.

Wakes physic simulation — Wakes the physical simulation thread to perform the

phys-ical simulation steps.

Check graphics — Checks if it’s time to refresh the graphical display of the simulation.

If so wakes the graphical thread and then ends the routine, if not ends the routine. 3.5.2 Class diagram

The original idea of this simulator was to create one application that could easily be changed and that could separate the physical simulation from its visualization. This goal was met and the application is split in two well defined parts. The class diagram can be found in figure ??. With this type of architecture it’s very easy to change a support library or to change the structure of one of the parts without affecting the other.

For this separation to be effective it can not only be made in the overall architecture. It has to be made also in the objects that are going to be modelled. In this way, each of the parts of the application interacts with only one of the parts of the object, creating a fully independent system. The objects modelled have the organization shown in the figure 3.6. To make it simple to distinguish classes defined in the context of this project and, ad-ditionally, to distinguish the purpose of its definition, the class names were built using the following form

I(I|P|)Name

The starting I is used to indicate the class belongs to ICARO’s project. A second capital letter between the former I and the class name can exist to associate the class to either the physical simulation part or the user interface. In the former a P is used; in the latter an I is used. If this letter is absent, the class is common to both parts. The names given to the classes try to be self explanatory.

Referências

Documentos relacionados

eles: coeficiente de uniformidade de distribuição (CUD), coeficiente de uniformidade absoluta (CUa), uniformidade de emissão do sistema (UE), uniformidade

processamento pós-situação (“autópsia” da situação). Estes processos cognitivos de antevisão detalhada do que poderá acontecer e de revisão minuciosa do que

Os objetivos específicos são: discernir os diferentes aspectos pertinentes a gestão do fundo Brasil de Direitos Humanos; verificar organizações e projetos apoiados pelo

Este artigo examina as páginas de Facebook dos candidatos à Prefeitura de Curitiba no primeiro turno da eleição de 2016, com o objetivo de avaliar as principais formas de uso de

Observa-se ainda que o teor de arsénio aumentou não só com a aplicação do adubo — sulfato de amónio ou superfosfato — contendo arsénio, mas também com o emprego de

La hipótesis que se presenta es que debido a los intereses diferenciados y a la falta de orientación al mercado, los prestadores de servicios turísticos no cumplen con los

O estudo, que envolveu 7 docentes e 17 alunos das referidas edições do programa doutoral, teve como uma das suas finalidades verificar a perspetiva do aluno sobre

Selected studies were included in the meta-analysis if they met the following criteria: 1) case-control or cohort studies; 2) evaluating the association of the rs2435357 and