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.