Monday, December 3, 2007

Repast - Wave 2

This is a more complex situation for the wave.

Here we have the agents (green) and a lot of other feature layers.

The agents travel from their home locations (pink) to the safe points (red) ... not always through the safest path.


Saturday, November 3, 2007

Repast - Wave

Here goes a glimpse of the wave we're going to use with the simulation.

It uses geographical information to calculate it's boundaries, and a set of marks collected from the output of the scenario fluid simulation.

The progression of the wave follows a cellular automaton model to simulate the progression of a fluid between the marks.

Tuesday, August 21, 2007

Direct Draw video on Ogre Texture

Today I decided to try something different, following Hernan Moraldo's code snippet I made a video playing in the texture of an object:

fig.1 - movie playing in the texture of a knot mesh

I had to install the DirectX SDK to be able to use direct draw. The movie played synchronized and with sound.


Wednesday, August 15, 2007

Ogre: Object Picking

To create the effect that we are clicking on an object in Ogre we use a ray query. The ray is traced from the place were the mouse is and then goes perpendicularly to the screen. The query will result in a list of objects that were in the ray's way. An object is in the way, if its bounding box is in the way.

fig.1 - In this example if we click inside
the box that contains the Ogre's Head
it will play a sound

This is the code that I used, first we must declare a RaySceneQuery *mRaySceneQuery as a global, and then initialize it:

mRaySceneQuery = mSceneMgr->createRayQuery(Ray());
then in the mouse clicking event we make the following sorted query and try to see if the touched the Entity named "Head" :

bool GuiScene::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
OgreApplication::mousePressed( arg, id );

mGUISystem->injectMouseButtonDown(convertOISMouseButtonToCegui(id));


CEGUI::Point mousePos = CEGUI::MouseCursor::getSingleton().getPosition();
Ray mouseRay = mCamera->getCameraToViewportRay(mousePos.d_x/float(mWindow->getWidth()), mousePos.d_y/float(mWindow->getHeight()));

mRaySceneQuery->setRay(mouseRay);
mRaySceneQuery->setSortByDistance(true);

// Execute query
RaySceneQueryResult &result = mRaySceneQuery->execute();
RaySceneQueryResult::iterator itr;

// Get results, create a node/entity on the position
for ( itr = result.begin(); itr != result.end(); itr++ )
{
if (itr->movable && itr->movable->getName() == "Head")
{
soundMgr->StopSound( &jaguarSoundChannel );
soundMgr->PlaySound( jaguarSound, headNode, &jaguarSoundChannel );
break;
} // if
}
return true;
}
Now if you touch the bounding box a jaguar sound will be heard.

Tuesday, August 14, 2007

Ogre: Multiple Viewports

fig.1 - Two viewports, one frontal fullscreen,
the other small left bottom with a sideways camera

To create multiple viewports in ogre3D it is necessary to add another viewport to the Rendering window. Viewports can use the same SceneManager with different cameras, or use completely different scene managers. Here's an example:

void GuiScene::createViewports()
{
// Create one viewport, entire window
Viewport* vp1 = mWindow->addViewport(mCamera);
vp->setBackgroundColour(ColourValue(0,0,0));

// Create one viewport, left bottom corner
Viewport* vp2 = mWindow->addViewport(mCamera,1,0,0.8,0.2,0.2);
vp2->setBackgroundColour(ColourValue(1,1,1));

// Alter the camera aspect ratio to match the viewport
mCamera->setAspectRatio(
Real(vp->getActualWidth()) / Real(vp->getActualHeight()));
}
Note that different viewports must have different Z values ( second argument in the addViewport function).

Sound with FMOD

There are many libraries that can be easily integrated with an Ogre3D project. We chose to use FMOD. This is a cool library that can play just about any sound, .wav, .mp3, .ogg, .whatever...

In addition to that I decided to use the Sound Manager available in the wiki. The good thing about it? You don't have to learn a thing about the FMOD library. It encapsulates all the major functions.

First we downloaded the FMOD Ex Programmers API and intalled it. Since we use VC++8 we linked with the fmodex_vc.lib library and added the include files.

After integrating the SoundManager in the project it is necessary to use the following code:

SoundManager *soundMgr = new SoundManager;
soundMgr->Initialize();

int jaguarSound = soundMgr->CreateSound(String("jaguar.wav"));
int music = soundMgr->CreateLoopedSound(String(music.mp3"));
int music2 = soundMgr->CreateStream(String(music.mp3")); //stream example

int jaguarSoundChannel = INVALID_SOUND_CHANNEL;
int musicSoundChannel = INVALID_SOUND_CHANNEL;

soundMgr->PlaySound( jaguarSound, mSceneNode, &jaguarSoundChannel );
soundMgr->PlaySound( music, mSceneNode, &musicSoundChannel );
First you create sounds and streams. Sounds are completely loaded to memory while streams are loaded in small chunks of data and are more suitable for large sounds.

When you play a sound the sound manager will create a sound channel for it. A sound can be played in multiple sound channels at the same time. Sound channels are useful if you want to stop the sound.

soundMgr->StopSound( &musicSoundChannel );

Each Sound Channel is associated with a SceneNode. This means that the farther the Node is from the origin the sound will be lower. The same applies to left and right movements. This is called 3D Sound and only is available to Sounds and not to Streams.



Monday, August 13, 2007

Repast Space: Windows Dynamics

So we have a window that can float over the Object2DGrid and display the objects inside its area.

But this only makes sense if there's a possibility of moving the window over the grid. We'll do that using events - from the keyboard to start with.

Events comprehend a programming paradigm commonly used in interactive programs. Repast provides ways to use event handlers through the registration of adapters, in this case, keyboard adapters.

As an example, we show how to handle events from the directional keys in order to navigate through the space with a display window:

ModelBuilder.java


// The default move values.
int MOVE_Y = 10, MOVE_X = 10;

...

private void moveViewWindow() {
display.setViewWindow(viewX, viewY, width, height);
DisplaySurface surf = model.getDisplaySurface();
surf.updateDisplayDirect();
}

public void buildDisplays() {

DisplaySurface surf = model.getDisplaySurface();

surf.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
switch (evt.getKeyCode()) {
case KeyEvent.VK_DOWN:
if (viewY < space.getY() - MOVE_Y)
viewY += MOVE_Y;
break;

case KeyEvent.VK_UP:
if (viewY > MOVE_Y - 1)
viewY -= MOVE_Y;
break;

case KeyEvent.VK_LEFT:
if (viewX > MOVE_X - 1)
viewX -= MOVE_X;
break;

case KeyEvent.VK_RIGHT:
if (viewX < space.getX() - MOVE_X)
viewX += MOVE_X;
break;

default:

}
moveViewWindow();
}
});

display =
(ShapefileSpaceDisplay)space.getWindowDisplay();
width = display.getWidth();
height = display.getHeight();

surf.addDisplayableProbeable(display, "Window");
surf.display();
}

This will handle the keyboard events, triggered by the directional arrows, thus moving the display window over the space.

Every time the user moves the window, the area covered by it will change and so will the objects to be drawn.

Repast Spaces: Windows

Repast offers a set of space geometries to be used in the simulation. The concept of a space is now required for every simulation, i.e., some simulations may represent only space independent relationships between agents.

Our agents will require information about distances, spaces and relative positions. So we will require a space. Our space, until further notice, will be a grid of objects: Object2DGrid. This grid is actually a double layer grid, representing, at each position, one Object and one Integer value. The integer value can be useful to store information(altitude?) about a certain cell of the space.

There are some issues to be taken into account. The main problem is the size of that grid. It'll be huge! One approach could be the resize of the cells in way that they could fit the screen, but that would make the whole display unusable.

While the final goal is to have a display interface completely independent of the simulation architecture, the development task must have ways of inspecting the whole set of cells, with a useful resolution. So we need a floating window display over this grid.

This window will work as the display return by the space in the getDisplay method:

Space.java:
public Displayable getWindowDisplay() {
int x = INITIAL_X, y = INITIAL_Y;
return new WindowDisplay(Grid, x, y,
width, height, maxX, maxY);
}


x and y will be the origin of this window's initial position. Both width and height variables define the size of the window, maxX and maxY represent the maximum X value and maximum Y coordinate value, respectively.

This window must be able to draw every object placed between the rectangle defined by the upper left point (x, y) and the lower right point (x + width, y + height).


This means that this windows must scan this whole area. Other solution would asking every object if they are inside this particular area, but it's expect that the total amount of object largely exceed the number of cells inside this window. In order to do this scan, concurrency precautions must be taken into account, as explained before.

Next we'll explain how to move the window using (keyboard) events.

Friday, August 10, 2007

Cegui and Ogre

Now that the project is starting to become more complex, I felt that the use of a GUI would help. In Ogre's Wiki it is recommended to use CEGUI. CEGUI is a free library usefull for creating windows and widgets such as buttons, listboxes or textboxes.

Has a guide I used this tutorial available in the wiki here.

First of all, before going to the code, CEGUI has several configuration files, you can see an example in your [OGRE_HOME]/media/gui directory. This is what they do:

.tga - Image File with all the textures of all widgets

.looknfeel - XML file that describes the look of all widgets and their behaviour.

.schema - XML file where all the widgets are listed and all configurations are linked.

.layout - XML file describing the windows that you want to put in one sheet in the Scene.


For now we'll be using the default look and feel, so the only thing that we have to create is a .layout file. Here an example that creates a window with four buttons:

<?xml version="1.0" ?>
<GUILayout>
<Window Type="DefaultWindow" Name="DemoLayout">
<Window Type="TaharezLook/FrameWindow" Name="Main">
<Property Name="UnifiedSize" Value="{{0.35,0},{0.6,0}}" />
<Property Name="UnifiedPosition" Value="{{0.05,0},{0.05,0}}" />

<!-- <Property Name="RelativeMinSize" Value="w:0.2 h:0.2" />
<Property Name="RelativeMaxSize" Value="w:1.0 h:1.0" /> -->

<Property Name="Text" Value="Sound and Gui Test" />
<Property Name="CloseButtonEnabled" Value="False" />

<Window Type="TaharezLook/Button" Name="cmdQuit">
<Property Name="Text" Value="Quit" />
<Property Name="UnifiedPosition" Value="{{0.2,0},{0.8,0}}" />
<Property Name="UnifiedSize" Value="{{0.6,0},{0.07,0}}" />
</Window>
<Window Type="TaharezLook/Button" Name="cmdSound">
<Property Name="UnifiedPosition" Value="{{0.2,0},{0.6,0}}" />
<Property Name="UnifiedSize" Value="{{0.6,0},{0.07,0}}" />
<Property Name="Text" Value="Sound" />
</Window>
<Window Type="TaharezLook/Button" Name="cmdInstantAction">
<Property Name="UnifiedPosition" Value="{{0.2,0},{0.5,0}}" />
<Property Name="UnifiedSize" Value="{{0.6,0},{0.07,0}}" />
<Property Name="Text" Value="InstantAction" />
</Window>
<Window Type="TaharezLook/Button" Name="cmdMusic">
<Property Name="UnifiedPosition" Value="{{0.2,0},{0.7,0}}" />
<Property Name="UnifiedSize" Value="{{0.6,0},{0.07,0}}" />
<Property Name="Text" Value="Music" />
</Window>
</Window>
</Window>
</GUILayout>
Now we have to load this layout to our application:

Initialization :


mGUIRenderer = new CEGUI::OgreCEGUIRenderer(mWindow, Ogre::RENDER_QUEUE_OVERLAY, false, 3000, mSceneMgr);
mGUISystem = new CEGUI::System(mGUIRenderer);
CEGUI::Logger::getSingleton().setLoggingLevel(CEGUI::Informative);
CEGUI::SchemeManager::getSingleton().loadScheme((CEGUI::utf8*)"TaharezLookSkin.scheme");
mGUISystem->setDefaultMouseCursor((CEGUI::utf8*)"TaharezLook", (CEGUI::utf8*)"MouseArrow");

mGUISystem->setDefaultFont((CEGUI::utf8*)"BlueHighway-12");

CEGUI::Window* sheet = CEGUI::WindowManager::getSingleton().loadWindowLayout("myLayout.layout");
mGUISystem->setGUISheet( sheet );

// set the mouse cursor initially in the middle of the screen
mGUISystem->injectMousePosition((float)mWindow->getWidth() / 2.0f, (float)mWindow->getHeight() / 2.0f);

Creating Handler's for the buttons:


CEGUI::Window *win;

CEGUI::Window *m_win = CEGUI::WindowManager::getSingleton().getWindow( "Main" );
win = m_win->getChild("cmdQuit");
win->subscribeEvent( CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber( &GuiScene::handleQuit, this ));
bool GuiScene::handleQuit(const CEGUI::EventArgs& e)
{
this->stop();

return true;
}
Taking care of the IO:

In MouseListener class:

bool GuiScene::mouseMoved(const OIS::MouseEvent &mouseEventRef)
{
mGUISystem->injectMouseMove(mouseEventRef.state.X.rel, mouseEventRef.state.Y.rel);

return true;
}

bool GuiScene::mousePressed(const OIS::MouseEvent &arg, OIS::MouseButtonID id)
{
mGUISystem->injectMouseButtonDown(convertOISMouseButtonToCegui(id));

return true;
}

And that is it, this example is for Ogre 1.4.x and CEGUI 0.5.x for further explanations please look at the practical example. This is the final result:

fig.1 - CEGUI menu

Tuesday, August 7, 2007

Repast and Concurrency

Repast uses a set of threads while executing the simulation model. Whether they are used in the simulation task or in the visualization processes one thing is certain, there are some objects (data structures) that may be accessed at the same time by different threads. This introduces some concurrency issues.

As an example, imagine a Object2DGrid. This grid is used to place the Agents. Lets suppose that the drawing strategy consists in scanning this grid, looking for Objects to draw. If the grid is scanned with no thread safety precautions, many errors will pop! These errors are due to the simultaneous access of that grid.

To face this problem we can use some thread safety techniques. As we're using Java, we can use some constructions offered by the language.

Example:

...
Object2DGrid grid;
...
Drawable d = null;
synchronized (grid) {
for (int y = 0; y < grid.getSizeY(); y++) {
for (int x = 0; x < grid.getSizeX(); x++) {
d = (Drawable)grid.getObjectAt(x,y);
if (d != null)
d.draw(g);
}
}
}

In this example we have the exact situation described above. The whole statement must be executed after the lock on the grid is captured.

Wednesday, July 18, 2007

Portuguese Characters

In the last thread I mencioned that we introduced MovableText. The text was fine, but it didn't suport special portuguese characters like L'ç' L'é' or L'À' . Here's somethings I learn today:

In C++ normal char's take 8 bit's while wide chars take 16 bits.

char:

char c = 'a';

wide char:

wchar_t wc = L'ç';

you have to put an L before the char literal to say that it is a wide char.
Theres also std::wstring for strings of wide chars.

In the MovableText class they use the Ogre::Font class. This class loads a true type font into the ogre system. It supports all types of UTF formats, but by default, it only loads to the memory the characters with unicode between 33 and 166. That's all fine if you're writing English, but if you're writing a language with accents like I am the first 166 characteres are just not enough.

I changed the range to [33, 255] before the Font's loading.

I added this code to MovableText in the setFontName function:
...
mpFont->addCodePointRange( Font::CodePointRange( 33, 255 ));
mpFont->load();
...

and there it is "ÇçáàéèíÍ..."

Tuesday, July 17, 2007

Mesh Exporting, Billboards, Movable Text

After importing my model with the help of an exporter, I started to animate the scene.
The wheels roll nicely and the car bounces a little bit.


fig.1 - Lexi Exporter


There are two more innovations in this scene.
I introduced the billboards which are textures that are always facing the camera.

BillboardSet* bbset = mSceneMgr->createBillboardSet("BBSet",1); bbset->setMaterialName("Examples/Flare"); Billboard* bb = bbset->createBillboard( Vector3( 0,0,0 ) ); FloatRect coords( 0.0, 0.0, 1.0, 1.0 ); bb->setTexcoordRect(coords); billboardNode->attachObject( bbset );

In fig.2 we can see a flare made with a billboard.

fig.2- Animated Car Scene with Flare and Label

We also added the MovableText class to put text on top of objects.

MovableText * msg = new MovableText("fireCarLabel", "Carro dos
bombeiros","Console",12,ColourValue(0.5f,1.0,0.5,1.0f));

Saturday, July 14, 2007

Crash Dummy Car

This is the new model of fire fighting car that will be available throughout the world in the next semester :P


fig.1- Piece of art

So, we need to simulate were all the civil protection car units will go. This will be our test car.

Friday, July 13, 2007

Ogre Visual Studio 2005 port from 2003

In the weekend I felt that my computer was a complete mess. Nothing worked! I want a Mac! sniff Haaaaa! After 2 months of experiments I decided that a Windows reinstall was in order!
To all linux fans ( and I know lot's off them) I only use windows because after 4 days of configurations, I gave up installing Hardware 3D acceleration for OpenGL in my Notebook
(Ati Radeon 9700 Mobile with some weird taiwan tweeks). So...hell... I will be using Windows XP.

I started using Ogre with Visual Studio 2003 (7.1), this time I installed VS 2005 (8.0).
In the beginning nothing worked. To use Ogre3D and VS2005 it is very important for you to install service pack 1 of VS2005.

To make an Ogre Project download the SDK in website here. Download also the AppWizard for Visual Studio 8 here, this will allow you to easily create projects on VS. Finally follow the instruction of the wiki for install SDK and setting up. If you use the wizard you don't have to do most of the things.
fig.1 - Ogre Application Wizard

In this project I usually change some things in the project properties. In the debugging section I change the command and working Directory to the project's bin/Debug directory. The wizard usualy uses the SDK's bin directory.
In the linker Input section I usually add the ws2_32.lib because I need winsockets and winthreads.

Very important, don't forget to copy all the dll's and cfg's in the SDK bin directory to your project bin directory.

First Post: Visualization Component

Hi, after a weird first post months ago(deleted), I decided to follow the steps of André and start writing here on the forum.

I'm Rui Nóbrega and I am the person responsable for the visualization component of the project LifeSaver.

For that means I will be using an open source library called Ogre3D, this is a 3D engine used mainly in computer games. For now the objective is to render a 3D terrain of Guadiana river valley, and present some information on it.

To display the terrain we will be using an Ogre plugin, the Paging Landscape Scene Manager 2 or PLSM2 for short. Theres no official site, but this is a good starting point.

fig.1 - PLSM2 example with Guadiana river valley

For debug purposes I adapted Ogre Console, made some changes for it to work on Ogre 1.4 and to load C++ style class function instead of C function pointers.

There is also a Network component wich will connect to the simulation component made in Repast. This is still in open discussion. The main problem is that the simulation is being done in Java and I'm doing the visualization in C++. For now we are using TCP/IP socket's and threads.
Andre's using the java sockets I'm using winsocket's in C++.

I finally finished reading the Pro Ogre 3D Programming book. It's a nice book, I would recommend for you to learn Ogre from the wiki, feel confortable with it and then read the book to consolidate your knowledge.

Meanwhile the last days were spent learning Adobe Flash CS3 and explaining the portuguese culture to our american teacher Geoff Marslett who came from the University of Texas at Austin.

From now on I will try to make smaller posts.

Tuesday, July 10, 2007

Repast: Organization 2

Repast suggests an architecture to be used while designing a simulation. Basically every simulation is divided, in it's simpler form into a Model Object and an Agent Object.

While this shows how Repast is organized in it's basic structure, does little in aiding the design of a robust architecture.

The way we're organizing our simulations is as follows:
Model Object
ModelBuilder Object
Space Object
Agent Object

The Model must define the parameters of the simulation and works a central point in all the process. So this connects the Agents with the Space and both with the parameters defined by the user. It also specifies the schedules for the different actions of the Agents.

The ModelBuilder encapsulates a set of operations within the Model. The point of this separation is that the set and get of parameters is a quite extensive block of code. We reserve the Model Object to this operations.

The get and set operations works as the Java standard get and set operation. If we have a integer variable named fooBar, it should have the corresponding get and set operations:
public int getFooBar()
public void setFooBar(int i)

Note the capitalized F in the name of the function and uncapitalized f in the name of the variable.

So the model has, besides the get and set operations:
- a setup() function, defining what should be performed (independently of the user set parameters) in order to allow the construction (build) of the Model.
- a begin() function, defining what should be built (dependably of the user set parameters).

These two functions are required by the platform and are attached to the buttons on the interface. This is why one must setup and then initialize every time the simulation is started.

fig.1 - Repast bar

The 8th button is the setup button. It's attached to the setup() function.

The 5th button is the initialize button. It's attached to the begin() function.

Actually, the first time a simulation is played it only needs to be initialized. This gives another perspective of the setup() function. It's supposed to tear down the model. This means it should destroy every instance that is going to be set in the begin() function later on.

We actually make every instance null, after an eventual dispose() operation and call the System.gc(). This forces the garbage collector to clean up and free memory. After this we create the required new instances. Note that the space is not usually destroyed/created here. Here we manage the Agents data structure, the Schedule and the eventual displays. The space has it's own set of operations.

So the begin() function is pretty complex. It involves building all the main components of the model. These are the Space, the Agents, the Schedule and the Displays. This requires four different operations, namely:
buildSpace()
buildAgents()
buildSchedule()
buildDisplay()

The ModelBuilder was thought specifically because of these operations. The begin function looks as something like this:

public void begin() {
builder.buildSpace();
builder.buildAgents();
builder.buildSchedule();
builder.buildDisplays();
}

The everything is set on the builder. This is only for organization purposes. Good practice anyway.

More to follow!

Monday, July 9, 2007

Repast: Organization

Repast is a Agent Based Simulation Platform (Recursive Porous Agent Simulation Toolkit). It was first developed by the University of Chicago. More history and related links can reached starting from it's wikipedia article.

Repast is the Simulation platform we're using to simulate the emergency plan. As far as we're concerned we need something that's well documented and, obviously, significantly tested. Repast fits the description.

It's basic structure is a set of two objects, the Model and the Agent.

The Model holds the simulation itself. It's required by the platform to actually perform any operation.

The Agent represents the simulation agent. As a Agent based environment, this one must be present.

After some weeks studying the platform we came to to conclusion that it is counterproductive to see the simulation in such simple terms.

In the next post we'll present a more robust and useful way to think while working with this (and probably other) platform.

Sunday, July 8, 2007

Multiple Ring Buffer 2

A more realistic MRB was generated with gaps of 250 meters, starting from 500m to 3000m.

fig.1 - MRB for the Auto Rescue Area.

The top purple area is the artificial lake of the Alqueva dam. The red area is the first impact area. The houses and evacuation points can be seen over the green layer. That layer represents the road layer with MRB. In order to know what path to take from one point to another, the MRB layer can be interrogated to find out the buffer where the target point is.

Multiple Ring Buffer

We're using ArcGis to manage our GIS content.

One of our layers is the roads layer. We must be able to ask that layer if some object is near to a target then others, and what should be the best path from it's position to the target's.

To do so we can create a new roads shapefile based on the original one, but with a ring of buffers surrounding each line of the polygon.

The buffers can be created with an arbitrary distance from the main polygon. As an example, a multiple ring buffer was created with 5, 10, 15 and 20 meters from the original polygon.

fig.1 - Original Polygon

fig.2 - Multiple Ring Buffer

In a more realistic situation, the rings may have to be defined with a larger distance from the road. Say between 100 and 1000 meters...

(ArcGis 9.2) To use the Multiple Ring Buffer: Toolbox -> Analysis Tools -> Multiple Ring Buffer

Wednesday, April 11, 2007

Introduction

This blog follows the research/development of the Life Saver Project, hosted at the Interactive Multimedia Group, Computer Science Department, Faculty of Sciences and Technology, New University of Lisbon.

The project aims to provide a way to test an Emergency Plan for a Flood Scenario caused by a dam break. The test case will be the Alqueva dam.

There are two main components to consider: One is the simulation platform, where the georeferenced information will be used in order to test the plan: the other is the interaction/visualization system, where the user should be able to inspect, personify a specific agent and to actually see the plan in action.

As data input we have the Geographic Information System(GIS) as ArcGis shapefiles for the Alqueva area and the emergency plan's description.