title: Using Quaternion in libGDX

text:
# Question
Title: Using Quaternion in libGDX
Can someone give me an explanation about how to use the `Quaternion` class in libGDX to move my camera around a sphere or just set it up, manipulate it, and apply it general? I am trying to acheive orbiting my camera around a sphere without gimbal lock, and I'm not having any luck getting the camera to do anything by using quaternions...

# Answer
I ended up getting this to work. To apply a `Quaternion` to your camera just do this:

```
public void update(boolean updateFrustum)
{
    float aspect = camera.viewportWidth / camera.viewportHeight;
    camera.projection.setToProjection(Math.abs(camera.near), Math.abs(camera.far), camera.fieldOfView, aspect);
    camera.view.setToLookAt(camera.position, tmp.set(camera.position).add(camera.direction), camera.up);

    // This is all you need to do!
    // the rotate() method takes in a Quaternion
    // It needs to be after the call to setToLookAt()
    camera.view.rotate(rotation);

    camera.combined.set(camera.projection);
    Matrix4.mul(camera.combined.val, camera.view.val);

    if (updateFrustum)
    {
        camera.invProjectionView.set(camera.combined);
        Matrix4.inv(camera.invProjectionView.val);
        camera.frustum.update(camera.invProjectionView);
    }
}

```

This is exactly the same as the update() method in the `PerspectiveCamera` class except for the part about adding the rotation quaternion.
> 0 votes

---
Tags: java, android, opengl-es, libgdx, quaternion
---


title: Flixel level ceases to show on screen

text:
# Question
Title: Flixel level ceases to show on screen
I was following along with the EZPlatformer flixel tutorial(with some of my own modifications), and suddenly find that my level is not appearing on screen. I am unable to detect any changes I could have made to cause this. My code in the overload of the create function looks like this:

```
override public function create():void
        {
            FlxG.bgColor=0xfffaaaaaa;
            level = new FlxTilemap();
            level.loadMap(FlxTilemap.arrayToCSV(data1,40),FlxTilemap.ImgAuto,0,0,FlxTilemap.AUTO);
            add(level);

            //add a player to the game
            player = new FlxSprite(FlxG.width/2 - 5);
            player.makeGraphic(10,12,0xffaa1111);
            player.maxVelocity.x=80;
            player.maxVelocity.y=200;
            player.acceleration.y=200;
            player.drag.x=player.maxVelocity.x*4;
            add(player);

            //add exits to the game
            forwardExit = new FlxSprite(35*9+1,25*8);
            forwardExit.makeGraphic(10,35,FlxG.WHITE);
            add(forwardExit);

            //array for coins
            coins=new FlxGroup();
        }

```

and my array that I am converting to a level is a class level variable declared as follows:

```
public var data1:Array= new Array(
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
            1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
            );

```

Can you please tell me what is causing the error and how to fix it? Thank you

# Answer
> 0 votes
I believe the issue was I was compiling it in debug, but not launching it in debug. I added this line:

`forceDebugger = true;`

And it resolved the issue.

However, I believe that adding this line, calling the FlxPreloader may have also fixed it:

`[Frame(factoryClass="Preloader")]`

---
Tags: actionscript-3, tilemap, platformer, flixel
---


title: Logic For camera Movement

text:
# Question
Title: Logic For camera Movement
Every time I move the hero on my screen I increment a screenOffsetX and a screenOffsetY. These add 1 if you move right, -1 if left to the sceenOffsetX. Add the screenOffestY +=1 if down, -=1 if up.

I also have a variable for the first time through drawing called drawingForTheFirstTime.

The problem is that I have a level of size 40x40 array. I am drawing a camera view of 20x20. I shift the camera fine as long as I am not near the edges of the map. When I try to go into the upper left of the map, I lose track of the hero.

I dont want the camera to move if the hero is close to the edge of the map. I want him to move independantly of the camera. Otherwise he stays at the same position on the screen while the map moves underneath him. I think it is only my if logic that is broken.

```
if(!(screenOffsetX != 0 || screenOffestY != 0) && !drawingForTheFirstTime)
{
    return false;
}
else
{
    //move camera
}

```

# Answer
> 4 votes
I'm a beginner too, but I just tackled this problem in my own game, so hopefully you will find this helpful:

First off: you have screenOffsetY spelled as screenOffestY, with the e and s reversed. So I'm not sure if that was intentional or not.

Secondly: Since there is only limited source code provided to base my answer on, I'm going to have to generalize it a bit.

In my own personal experience (I'm working with C++ and SDL too for my game), in order to use the scrolling camera effectively, I'm needing to enact *constraints* on the camera's movements.

The camera moves left If and Only If (IFF), the x-coordinate of the camera is greater than 0. The camera moves right IFF the x-coordinate of the camera, is less than the width of the level/background/screen minus the width of the camera-frame.

Similarly, the camera moves up iFF the y-coordinate of the camera is greater than 0, and the camera only moves down IFF the y-coordinate of the camera is less than the height of the level/background/screen minus the height of the camera-frame.

Obviously you'll need to use your wisdom to apply this to your own particular need, and to figure out if you want to move your camera relative to your screen, your background, your level, or whatever else you want.

Below is the actual code that I'm using to keep my camera within the level bounds. I'm doing my camera relative to my level background which is contiguous, so this may be different from what you need, but hopefully it may help get you on the right path. :3

```
void Camera::updateCamera(int x, int y)
{
    //centers camera on provided x/y coords
    gameCamera.x = x - gameCamera.w / 2;
    gameCamera.y = y - gameCamera.h /2;

    //keep camera in bounds
    if (levelWidth != 0 && levelHeight != 0)
        {
            if (gameCamera.x < 0) gameCamera.x = 0;
            if (gameCamera.y < 0) gameCamera.y = 0;
            if (gameCamera.x > levelWidth - gameCamera.w)
                gameCamera.x = levelWidth - gameCamera.w;
            if (gameCamera.y > levelHeight - gameCamera.h)
                gameCamera.y = levelHeight - gameCamera.h;
        }
}

```

EDIT: included alternate camera algorithm below which automatically centers, and keeps itself in bounds in relation to a surface(likely the level) that you pass to it. We pass the rect by const, since you should be passing the rectangle by reference since its an object (otherwise the program will create a copy of the object every time this method runs), and we don't want our code to have the privilege of being able to alter the original rect. Note: It's irrelevant that nothing in our code tries to change anything in the rect, but it's simply good programming practice to ensure that our code doesn't even have PERMISSION to change it.

```
void Camera::updateCamera(const SDL_Rect *object)
{
    //centers camera on provided x/y coords
    gameCamera.x = (object->x + (object->w / 2)) - (gameCamera.w / 2);
    gameCamera.y = (object->y + (object->h / 2)) - (gameCamera.h /2);

    //keep camera in bounds
    if (levelWidth != 0 && levelHeight != 0)
        {
            if (gameCamera.x < 0) gameCamera.x = 0;
            if (gameCamera.y < 0) gameCamera.y = 0;
            if (gameCamera.x > levelWidth - gameCamera.w)
                gameCamera.x = levelWidth - gameCamera.w;
            if (gameCamera.y > levelHeight - gameCamera.h)
                gameCamera.y = levelHeight - gameCamera.h;
        }
}

```

Hope this helps!~ ^-^

---
Tags: c++, sdl, logic
---


title: OpenGL ModelView matrix

text:
# Question
Title: OpenGL ModelView matrix
Hello I am trying to understand matrix operations behind OpenGL and I have some questions.

1- When we first create a simple window using glut and opengl, we use such a command below to draw a simple triangle.

```
glBegin(GL_TRIANGLE);
glVertex3f(0.25, 0.25, 0.0); // coordinate 1
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0); // coordinate 3
glEnd();

```

Does this drawing take plece in object coordinate sytem or at other coordinate sytems ?

Assume that, I applied a transformation using glTranslate(), so this translation manipulates the modelview matrix. Now if I apply the command above again

```
glBegin(GL_TRIANGLE);
glVertex3f(0.25, 0.25, 0.0); // coordinate 1
glVertex3f(0.75, 0.25, 0.0);
glVertex3f(0.75, 0.75, 0.0); // coordinate 3
glEnd();

```

Is this drawing still done in object space coordinates and transformed to eye space using modelview matrix ?

***edit:***

at first when you use command glvertex(0,0,0) , you draw a point at (0,0,0) in both object, world and eye coordinates it is (0,0,0). of course this is done after modelview matrix is cleared using gloadidentity().

now apply the command gltranslate(2,0,0) , and again use command glvertex(1,0,0), now you draw a point at (3,0,0) . this is good but which coordinate system (3,0,0) is represented in ? do you draw in eye coordinates (3,0,0) ?

***Is my thought below true ?***

I think that glvertex(1,0,0) draws a point in object coordinate (1,0,0) , and since model view 4x4 matrix now is not an identity but has a "2" at the first row and fourt column because we applied gltranslate(). if we multiply our new modelview matrix with (1,0,0) in obj. coordinates, now we have (3,0,0) in eye coordinates .

# Answer
> 1 votes
I'm assuming you've set up your viewport and the projection matrix. Also i'm assuming that eye space is camera space and that object space is model space.

The model-view matrix represents the combined transformations you're applying to a set of vertices. A camera is just another transformation applied to your model. Whether you consider your model being in camera space or world space depends on whether a particular transformation represents moving an object in world space or moving the whole world to be drawn in respect to the camera position.

In your first example you aren't applying any transformations, so you're drawing in model space. Now in the second example, it depends what that translation represents. Does it represent the camera moving, or the object moving in world space? It all depends, but it's definitely not being drawn in model space anymore, since you moved it.

> Is this drawing still done in object space coordinates and transformed to eye space using modelview matrix ?

You can't first draw something and then transform it. A 3D world doesn't exist inside of a graphic's card. OpenGL, especially the old one you're using, is like a state machine. You set the state (matrices, light, etc.), submit input (vertices, normals, etc.) and receive output (an image in the frame buffer).

> now apply the command gltranslate(2,0,0) , and again use command glvertex(1,0,0), now you draw a point at (3,0,0) . this is good but which coordinate system (3,0,0) is represented in ? do you draw in eye coordinates (3,0,0) ?

Technically speaking, all drawing is done in eye coordinate space since that's what you end up seeing in the end, so the answer is yes. As i said, the whole concept of spaces comes from the separation of the stages of transformation. A translation by itself doesn't say much of anything.

> I think that glvertex(1,0,0) draws a point in object coordinate (1,0,0) , and since model view 4x4 matrix now is not an identity but has a "2" at the first row and fourt column because we applied gltranslate(). if we multiply our new modelview matrix with (1,0,0) in obj. coordinates, now we have (3,0,0) in eye coordinates.

You take an object's position, transform it from model to camera space using the model-view matrix. Yes, what you said is true.

---
Tags: opengl, camera
---


title: Working Qt controls in a 3d environment

text:
# Question
Title: Working Qt controls in a 3d environment
I need some advice from a Qt expert.

**The background:** I have a 3D engine (ogre3d) working in concert with Qt. The 3D Content is displayed in a widget (using a custom OS window in the client area). I'm able to overlay arbitrary Qt widgets onto the 3d world using the widget render() method and a shared bitmap. This makes a great "heads up display". I can use the standard Qt style sheets and animation using this technique.

**My goal** I'd like to go a step further and allow the user to move these rendered widgets using the mouse. I'd like some advice on the best way to implement this.

**Possible solutions:**

* The widgets in the HUD are not part of the inheritance chain. I render them manually. They don't get events though. I could add them to the inheritance chain so they get events in the usual way. Then I would need to change them to render to my shared bitmap instead of to the operating system. I looked at this once but couldn't find enough information to implement it.
* Capture mouse events in the 3D display widget and EMIT them to child controls. I basically create my own event handling chain.

Any suggestions on how to implement this?

I'm also considering switching to Qt5. I'm not sure how that might affect this decision.

# Answer
So far both solutions seem ok and none of them present any major drawback.

I guess the solution is the one you implent the quickest .

Now ...

**if you choose a)**

* You need to create a render target
* Push this as the current render target
* draw your hud in this render target
* pop it leaving you ogre window as the main render target
* draw everything else here

then ..and this is the tricky part

either

* get the pixels from the render target create a qimage and draw it

or

* create a custom material that uses for the texture you render target's color buffer and draw a full screen quad with this material

in any case you should check tutorials  ,  ,

**If you choose b)**

you already figured out what to do ....

in your mouse mousePress , Released , Moved events from your qtglwindow just emit some events and whatever widgets is active or intersecting the mouse should respond to the event .
> 1 votes

---
Tags: ogre, qt
---


title: Go to fullscreen and back in directX

text:
# Question
Title: Go to fullscreen and back in directX
I'm now learning how to use directX (10 - 11), and i use materials from SDK samples, http://www.rastertek.com/ and http://takinginitiative.net/category/graphics-programming/directx-10-tutorials. But i find it suprising that none has explainded the transition between fullscreen and windowed. I also seached with google, in GameDevelopment and StackOverflow, but no result.

What i'm asking is explanation or full exaples for both Window and DirectX "classes".

Thanks for help.

# Answer
You can do this using the normal Windows API function `ChangeDisplaySettings` http://msdn.microsoft.com/en-us/library/windows/desktop/dd183411(v=vs.85).aspx
> -1 votes

# Answer
It actually turned out even simpler, I just recreated the DirectX device (or reset it) using new presentation parameters (windowed = false).
> 1 votes

---
Tags: c++, directx
---


title: Matrix Rotation with three Angles

text:
# Question
Title: Matrix Rotation with three Angles
I want to rotate a form with three given angles fo each of the three axis. But the GLM `rotation` function takes only one angle and a vector as arguments.

How can I convert between both formats?

# Answer
> 4 votes
GLM's rotation function uses Euler's rotation theorem, which implies that any rotation or sequence of rotations of a rigid body in a three-dimensional space is equivalent to a pure rotation about a single fixed axis.

However consecutive calls to GLMs rotate function just multiply the rotation so rotating a rigid body by Yaw, Pitch, Roll is as simple as this:

```
glRotateF(yaw, 0, 1, 0);
glRotateF(pitch, 1, 0, 0);
glRotateF(roll, 0, 0, 1);

```

Edit: please also read this article where they explain the differences and how you can go from Euler angles to Quaternions to Axis Angle :)

# Answer
> 1 votes
The angles used to build a rotation for each of the three axes are known as Tait-Bryan angles (often confused with Euler angles).

Wikipedia has all the formulas you need to convert Euler or Tait-Bryan angles into a rotation matrix.

Here is some code to build a rotation matrix from three Tait-Bryan angles and the order of the rotations:

```
/* i, j and k are the integers 0, 1 and 2 in any order.
 * For instance passing 1, 2, 0 will first rotate around
 * Y, then Z, then X.
 * Make sure to convert from degrees to radians if necessary. */
mat3 tait_brian_to_matrix(float a, float b, float c,
                          int i, int j, int k)
{
    mat3 ret;

    float s0 = sin(a), c0 = cos(a);
    float s1 = sin(b), c1 = cos(b);
    float s2 = sin(c), c2 = cos(c);

    ret[i][i] =   c1 * c2;
    ret[k][k] =   c0 * c1;

    if ((2 + i - j) % 3)
    {
        ret[j][i] = - c1 * s2;
        ret[k][i] =   s1;

        ret[i][j] =   c0 * s2 + s0 * s1 * c2;
        ret[j][j] =   c0 * c2 - s0 * s1 * s2;
        ret[k][j] = - s0 * c1;

        ret[i][k] =   s0 * s2 - c0 * s1 * c2;
        ret[j][k] =   s0 * c2 + c0 * s1 * s2;
    }
    else
    {
        ret[j][i] =   c1 * s2;
        ret[k][i] = - s1;

        ret[i][j] = - c0 * s2 + s0 * s1 * c2;
        ret[j][j] =   c0 * c2 + s0 * s1 * s2;
        ret[k][j] =   s0 * c1;

        ret[i][k] =   s0 * s2 + c0 * s1 * c2;
        ret[j][k] = - s0 * c2 + c0 * s1 * s2;
    }
    return ret;
}

```

---
Tags: matrix, rotation, linear-algebra, angles, glm
---


# Question
Title: Game development for multiple Microsoft platforms
I intend to develop games for Microsoft's Windows Store, however, I'm confused between their platforms, so please clarify those questions:

* Is there any technology (XNA, DirectX), so a game can be distributed to Xbox360, Windows Store, Windows Phone?
* What are the differences between Xbox360 and Windows?
* What is a good approach for 2D games?
* Does a Windows Store game work for Windows Phone just by recompiling it?
* Are the Windows Store and Windows Phone store separated?

# Answer
> 6 votes
I will try to answer your questions to the best of my ability:

**1.** XNA allows you to develop games for those platforms.

MonoGame allows you to create games for the standard platforms as well as iOS, Android, Apple Mac, Linux and Windows 8.

> Since XNA games are written for the runtime, they can run on any platform that supports the XNA Framework with minimal or no modification.

Source: Wikipedia page on XNA

Not sure what you mean by that but Microsoft owns Xbox and Xbox360.

---

**2.** I am assuming you meant to ask `"What is the best platform for 2d games?"`. It is entirely up to you. Because of the hardware limitation on Windows phones, 2D games are pretty popular on the store (Also because of the touch screen, easier controls). It all depends on what you want (to make it for) and your target audience.

---

**3.** See quote from Question 1. As for the windows/phone store, I am not sure because I have not used them.

Hope this helps you!

# Answer
> 3 votes
If I understand you right, then, no, there is *generally* no single *Microsoft* technology that will allow you to cover all described platforms.

For Xbox360 your option is Microsoft XNA, DirectX development only allowed for certified studio developers and can't be considered an option for most of small development teams.

For Windows Phone you can also use Microsoft XNA which will run both on Windows Phone 7.x and Windows Phone 8 devices.

For Windows Store you can't use XNA, you need to either use DirectX or HTML5 based games.

However, you can use MonoGame to develop games for all of that platforms. While it's arguably considered pretty buggy, for a simple 2D games it's a pretty safe choice. The advantage is that you can use almost any XNA related sources and examples to learn MonoGame (since it's actually independent copy of a XNA platfrom).

# Answer
> 2 votes
Try using game engines such as the :

Unity (http://unity3d.com) (Battlestar Galactica)

Unreal engine. (http://UDK.com) (Mass Effect, Tera)

CryEngine www.mycryengine.com/ (Far Cry)

.

Both are multi platform game engines which come with a complete compiler and an advanced toolset. With these you do not have to worry about writing scripts for a particular OS. If you make an app for Iphone, it will have a different touchscreen UI (user interface) from the same app distributed for a PC with a mouse controller.

When it comes to unity you also have access to a large library of complete game objects that are ready to be implemented in your game.

And remember one important thing - Don't write engines that are already written. Because unless you want to join some large company and help developing a game engine you will have no chance to create an UP-TO-DATE GAME ENGINE, most likely you will end up with something compared to quake engine. But you will learn a lot.

# Answer
> 1 votes
XNA may be a good choice, if you want 2D and want to dev for Windows Phone and Xbox360. However if you goal is the microsoft store for Windows, then it may not be the best. However if you want to use XNA, you could post it on Steam Greenlight or something simaler. Some games made with XNA have become pretty big so It is a capable engine. Terreria , Magika, and Bastion are supposedly xna.

If the windows store thing needs DirectX/HTML Then something Like unity3d May be a great option. Unity doesnt have to be 3D if you dont want it to be. Ive seen some neat plug-ins for 2D games, and you might not even need them I havent really looked into it. Orthello is probably worth a look. : https://www.assetstore.unity3d.com/#/content/1014

---
Tags: xna, directx, cross-platform, microsoft, appstore
---


# Question
Title: What can go wrong with this technique/game architecture?
So this is something kind of new, as I've never saw anywhere, but maybe already exists:

The game is divided in 3 pieces: the actual game logic (game), the visual part (view) and something that link the game to the view. Nothing new until now.

Now this is a board game, therefore there are no physic involved, so I do like this:

Here is what happens when I roll the dices:

* game calculates the dices
* controller listen the dices rolled event and report to the view\*
* game move the player from A to B
* controller listen and report to the view\*

This happens instantly until this point. \*: the controller run the method "rollDices" on the view, and the view queue the action for when it can. Then the view queue the "movePlayer" action too.

So after the 4 steps showed before the view actually starts to update itself, making the animation for the dices that takes 5 seconds and moving the player, which takes another 3 seconds.

If you roll the dices while the view is still animating the game acts normally, as is not coupled in any way to the view. So the view will also queue the next dices and player move. When the game needs some player interaction such as a confirmation or so, it will wait for it.

What do you think? is this bad/can have flaws or is not scalable?

My objective is to decouple entirely the game logic from the view.

thanks for your oppinion

# Answer
> 2 votes
I've used a very similar architecture for a non-real-time game before, with great success. I had a simple action list (the queue variety) that was filled mostly with animations but also with game state commands ("wait for player to select valid move" or whatnot). I hence feel that it's an entirely reasonable architecture.

One of my particular goals was allowing the UI to play out pre-recorded games with almost no extra logic from games that were being played actively; events were fed into the view layer and it played them. This also let us easily build a local AI option to smoke test the game, which was invaluable (as it has been on every game I've worked on that had it, turn-based or real-time).

You will likely need to add more advanced scheduling to your animation queue at some point. e.g., "play these two animations now and wait for both of them to finish," or even "play these two sequences of animations, and wait for both to finish." You'll also want separate animation queues for disconnected parts of the game UI, like menus UI vs the actual game board.

The tricky part comes down to animations that are in direct response to user interaction. Say you want to have a game object moved by the player by dragging it to a desired location (in your case, say, to move a piece on the board). These kinds of animations don't fit quite as well into a queue pattern, since they are not "fire and forget" but rather are constantly updated and modified as the player interacts with the pieces. I solved this by having two different animation managers: the queue for system-driven state-change animations, and then a simpler layered animation system targeted specifically at drag-n-drop, hover effects, selection effects, etc.

Another interesting note is that you can well have a mixture of both types of animations in some cases. Say you have a long system-driven animation, like dice rolling and pieces moving in your example, but you don't want the game board to become completely non-interactive while the animations play (because that makes your game look and feel like a 1990's relic, and users expect iOS-like smoothness and interactivity these days). I solved this by having the animations in the queue control an object's "natural" transform/state, and the interaction animations controlling "actual" transform/state information (and if there are no interaction animations on an object, then the actual transform is equal to the natural one). A few specialized tweaks were needed to make it feel and look really good, but it worked quite well even without those.

While I assume you're working in 2D, I did this all in 3D, and it worked equally well there. The animations and interaction code are slightly more complex but the architecture to manage and schedule them can all be the same.

# Answer
> 0 votes
You might want to check out the MVC-pattern:

http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

---
Tags: architecture
---


title: Event Based Render / Update Loop

text:
# Question
Title: Event Based Render / Update Loop
I'm working on a few game dev tools which use OpenGL or DirectX to render 3D models (viewing).

Consider your favorite 3D modeling software package (Softimage, Maya, 3DS Max, modo, etc.). Note that the 3D viewport does not sit in a constant render loop pegged at max FPS. It remains idle (0 FPS) until some action is taking place in the viewport such as moving the viewport camera from side to side using the mouse or pressing play for animation. If the viewport is idle, there is no drain on the CPU / GPU. I'd like to use this technique in a couple of tools I'm working on and possibly within the game.

**Is there a generally accepted programming technique with OpenGL and/or DirectX (via C++) that will achieve this?**

One solution would be to do a standard render loop and check for input 1000s of times per second, but that seems inefficient and hard to manage as you add more and more "events" which would trigger a updated render.

Please let me know if the question is unclear. If I knew how to describe it perfectly I could probably just search google.

# Answer
> 2 votes
The answer to this question has absolutely nothing to do with OpenGL or DirectX. It is entirely dependent on how you implement your event loop in your window system code.

The OS's windowing system API is built around the concept of an event loop. Whenever the user does something, like press a key or move the mouse, an event is sent from the windowing system to the application.

Typical applications, including 3DS Max, use an event loop something like this pseudo code:

```
while (WaitForMessage())
{
  ProcessMessage();
  UpdateState();
}

```

If there are no messages from the windowing system (because the user is not interacting with the application), then WaitForMessage will block (put the application to sleep) until a new message arrives. Hence the application is not using any CPU/GPU Time.

Typical games are full of animations and game logic that is happening whether the player is actively pressing keys or moving the mouse. It would be pretty silly if the AI-controlled enemies only moved while the user was moving the mouse. They use an event loop something like this pseudo code:

```
while (IsPlaying())
{
  if (PeekMessage())
    ProcessMessage();
  UpdateState();
}

```

Hence they are constantly running in a loop as fast as possible. This event loop is *mandatory*, so even games that are doing all input by polling the OS must still have that event loop, since applications are required to respond to and process messages from the windowing system. Otherwise the system will consider your app hung/nonresponsive, and might kill it. Also, there are other special system messages an app must handle that aren't related to user interaction.

That loop is somewhere in the app. If you're using something like GLUT or certain other toolkits, the loop might be hidden away from you. Those toolkits are generally not meant for games or "serious" apps, and I recommend avoiding them and either using native code (e.g. the Win32 API on Windows, X11 on UNIX/Linux systems, etc.) or using more capable wrapper library (SDL being a good example of one).

Note that this is a bit more complex with actual graphics code, since you can use the "sync to v-blank" option to only render as fast as the monitor can display new images. A game using this can still easily achieve well under 100% system utilization, assuming it can update and draw an entire frame much quicker than the monitor's native frame time. More complex 3D apps can struggle to maintain the native 60Hz (for typical monitors) and so will continue to consume near 100% of the processing time.

Things get a bit more complex when you want to have animations in your app, but don't want it to waste resources. Typically, normal desktop applications will use a built-in timer system in the windowing system. These timers will send messages to the application when they fire. So if you have an animation that needs to play at 15 frames per second, you would create a timer in the windowing system set to fire every 1/15th of a second. That first message loop would then receive a timer message every 1/15th of a second, allowing you to update the animation state. When the animation is complete, you would disable the timer so that your application doesn't keep receiving unnecessary timer messages (and hence it can sleep at 0% CPU utilization until the user interacts with it again).

This timer approach can be a little bit hairier. If you have multiple animations, you don't want to create multiple timers in the windowing system; in fact, some windowing systems only allow a single timer or a small number of timers. You'll want to have your own animation manager in your application that can be driven by a single timer message, and which can easily know if there are no pending animations and hence that the timer is unnecessary.

For games, the timer approach is generally not suitable. Windowing system timers are driven by the OS's low-precision timer features, generally, which work well enough for low-framerate animations (like most UI animations) but are not precise enough for the framerates that games want to run at (30 at a minimum, 60+ ideally). This is why games use the loop above.

If you want to make your apps behave like 3DS Max, just use the first kind of event loop.

If you want to make a game that doesn't use 100% CPU/GPU time unnecessarily, do two things. First, use sync to v-blank if your game is capable of rendering a consistent 30+ FPS. That way your app will only update as fast as is necessary. Second, when your game is in a state where there is no animation or AI updates or networking to deal with (say, in the pause screen in a single-player game), simply switch your update loop. You can do it with something like this pseudo code:

```
while (IsPlaying())
{
   if (IsPaused() && WaitForMessage())
     ProcessMessage();
   else if (IsNotPaused() && PeekMessage())
     ProcessMessage();
   UpdateState();
}

```

Be careful with things like your time delta with code like this. When you come out of the pause state your time delta will be quite large since UpdateState() was not called at all during the pause state. You may want to skip doing any time-dependent updates on the first frame after unpausing, or simply cap your time delta at some reasonable time (1/15th of a second or so). And of course, always fix your timestep!

# Answer
> 1 votes
The basic way to do this is just call `repaint()` when a region of the window is invalidated.

You would trigger a repaint whenever the user performs a GUI action that requires the viewport to be re-rendered.

An *old* way to write a game in a C# native window (*which you don't do now! you use XNA!*) is to basically call `invalidate` at the end of each paint event. This makes for a pretty continuous (but not ideally performing) "game loop".

The GUI and 3D rendering representation generally run *on the same thread*, so there are no threading issues. Data processing jobs (such as rendering) can be performed on separate worker threads, and they report back to the main thread when they are done.

# Answer
> 0 votes
There are 2 ways of doing it. One is called 'polling' that is where you check for events continuously in a loop. The other is where you specify a function to fire when an event happens and is refereed to as a 'callback'.

Most Windowing/widget systems will have some kind of callback system in place where you define a function that executes whenever an event like a mouse is clicked, a key pressed, a window is resized, etc... rather than polling it yourself.

If you are designing your own 3D Max grabbing a widget system like Qt would be a good idea (It refers to them as Signals and Slots rather than callbacks though).

All the main windowsing systems, Qt, GLFW, GLUT, SFML, also have callback sytems. (SDL might not, but it does have a function to wait for events that you might be able to setup in it's own thread to simulate the same thing, but I'm not sure how threadsafe SDL is so tread carefully, the wiki page says it needs to be the same thread that set the video mode). DirectX (or rather XInput/DirectInput will probably also have a callback system).

Otherwise if your looking at doing it yourself it will probably be specific to the platform that you are running on. At the real low level there are things called interrupts which are done on the hardware level, basically the processor puts your program to sleep until it receives a hardware interrupt but it's unlikely you will need to bother with anything that low level (even if your on an embedded device like a console/phone there is probably a library for that).

The main issue with callbacks would be ensuring that your program is threadsafe. You might receive a callback at the same time your already half way through updating the screen.

---
Tags: opengl, directx, rendering
---


# Question
Title: Is this an appropriate use of abstraction in my game engine?
I have been stuck in the design phase on my new game for a few weeks now because I keep finding new parts of the game engine that I could make more modular and neat. I did, however, run into a problem recently where I found that a seemingly logical modularization lead to some (what I thought to be) bad practices. Let me explain:

## The Situation

I am writing a game that has a series of physics objects, called `Bead`'s that move around within the closed walls of the screen. Now, The Bead object contains all the necessary information that a Bead needs, however I recently removed the velocity and location information out and into a `PhysicsObject` class, as I figured if I ever wanted to introduce more shapes, I could reuse this code (a good practice, right?).

I then moved another part of the `Bead` out of the `Bead` class: the region bounding the drawn bitmap. This would allow me to create other regions in on the board that could react to touch input from the user (considering it is an Android game). I made this an interface (since you can only extend from one class at a time in Java), called `Boundable`, and had the `Bead` class inherit the traits from that class.

Note that one of the main reasons I pulled out this information because I wanted the `Board` object to also inherit these traits (because their bounding information is very similar) that would allow me to bound the screen and work with object collision in a much more object-oriented manner.

## The Problem

Since the interface contains information related to the bounds of an object, and since it must be an interface, then the access modifiers must be public either public, static or final, and I would prefer them to be protected. I don't want the location information of the objects in my game to be publicly available as it could permit some malicious program the ability to change the values. Am I correct in this assumption? Am I just going about this in the completely wrong way? Perhaps being too picky? Please let me know if you need any additional clarification.

Any help would be greatly appreciated.

---

Here is the code for those of you that would prefer to see what I'm doing first hand:

## Boundable.java

```
public interface Boundable{

    //I would like these values to be protected.
    public float left;
    public float right;
    public float top;
    public float bottom;

    public boolean contains(float x, float y){}
}

```

## UML Diagram

You may find a UML diagram of the setup I currently have, here.

# Answer
In java those variables get converted to "public static final" variables, so it will not work as intended. You can only have the public access modifier in interfaces, you also do not need to explicitly write public as it is assumed.

```
// It is good practice to start interfaces with an I
public interface IBoundable
{
    float getLeft();
    float getRight();
    float getTop();
    float getBottom();

    boolean contains(float x, float y) { }
}

```

Having your interface like this forces that implementer to have public get method, but they can hide the set method.

```
public class Bead implements IBoundable
{
    private float left;

    public float getLeft() { return left; }
    protected float setLeft(float left) { this.left = left; }

...
}

```

Please also note that you can only extend from one class (like you said), but you can implement more than one interface.
> 0 votes

---
Tags: java, android, interface
---


# Question
Title: Procedurally generating terrain in dead time before buffer swap
I'm using OpenGL/C++ in Windows, and my main loop looks like this: GLboolean done = GL\_FALSE; auto\_ptr l\_world(new World); l\_world-\>Init();

```
while (!done) {
    if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
        if (msg.message==WM_QUIT) {
            done = GL_TRUE;
        } else {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    } else {
        if (!world->Iteration() || keys[VK_ESCAPE]) {
            done = GL_TRUE;
        } else {
            LocalContext.SwapBuff();
        }
    }
}

```

where Iteration() is:

```
GLboolean World::Iteration() {
    DrawAll();
    MoveAll();
    CheckForCollisions();

    return GL_TRUE;
}

```

I've implemented the diamond-square algorithm to procedurally generate terrain, which I'm currently doing in World::Init(). Vertices, indices and textures are stored in buffers to be drawn every frame.

That's fine for a small area, but I want to make it much bigger if possible. To do that I'd like to generate on-the-fly as the camera moves, which would be done at the end of the iteration, after the drawing, moving and collision detection but before the buffer swap. It could be split over several frames, but I'd like to get as much done in a single frame as possible.

As I understand it, with vsync enabled SwapBuffers will block until the end of frame, so any time between the SwapBuffers call and the end of frame will be wasted. So that's my question: is there a way to tell how much time remains until the end of the frame, so I can keep generating terrain until the last possible instant but still maintain a consistent frame rate?

I've not found anything too helpful on the OpenGL Synchronisation page. I wondered if Triple Buffering might be the answer - if the other back buffer contains a completed frame, keep generating; if it's empty then SwapBuffers. It's not a great solution as it would make triple buffering mandatory, and how would you detect if one of the back buffers was free? Any better suggestions?

# Answer
There is no such mechanism in OpenGL, unfortunately. On the other hand, with the multitasking systems we use, there's hardly any way to know what's going on anyway - it might be that your virus scanner just decides to start downloading updates at some point, and that messes up your timing and there's nothing you can do about it.. =)

It wasn't long ago when you couldn't even depend on the refresh rate on PCs. Currently the standard seems to be 60Hz, but even that may be changing with the 110Hz, 120Hz and 144Hz displays out there today.

So it's best to separate game logic from rendering (so rendering framerate may change while the game logic / physics will run at a stable rate), and do any terrain generation / preloading stuff on a separate thread.

If you're working on a platform where you have absolute control (or close to it), such as a game console, the situation is different.
> 1 votes

---
Tags: c++, opengl, procedural-generation, vsync
---


title: Forward Compatibility of Save Files

text:
# Question
Title: Forward Compatibility of Save Files
My game is driven by a scripting language, and the user can save at almost anytime in the middle of the script, so the instruction number of the script engine must be saved. The problem is that the game state breaks when the script is changed. If the script is `A B C D E` and the player saved at C (the 3rd), and then the script is changed into `X Y Z A B C D E`, then the player will load at Z. I think my game will be updated infrequently even after release.

I think breaking the script into sections and autosaving in each new section. (in case of incompatibility: restart at autosave) However, are there any other ways to make save files forward-compatible? I want to hear some examples of especially RPGs with DLCs and patches.

# Answer
1. Include a version number at the top of your save file. Increment the version number whenever you make a change to the format, and add code to your engine to allow it to read "old" versions and make any necessary revisions to the loaded data. Of course you will have to decide what kinds of revisions are appropriate. In a case like your example, where new items are added, you'll have to supply some default state for the new items, since old saves will have no state for them.
2. When saving the state of characters, items, quests and the like, refer to them by some sort of "name" - not just by their index in an array or something like that. This allows you to add new content to the game and old saves will not be broken by changing the order of things.

Note that by "name" I don't necessarily mean a string. You could use a string, but you could also use a hash value, or an integer ID number, as long as it's something assigned to the item once and for all, that will never change - i.e., *not* its address in memory or index in an array or anything like that.
> 6 votes

---
Tags: savegame
---


# Question
Title: How to linearly blend between multiple points, deviating from a default point?
I have a set of 3D points that I need to "blend" between. Lets say I have points `[A,B,C]` and I have the amount I want to blend each as `[0.5, 0.2, 0.8]`, how can I blend between these points with the amount I need? I asked this previously and got an answer.

But, when all values are `0`, I need to return to a `Default` point, so all blending must take effect as if deviating from the `Default`.

How do I calculate this? I'm sure its not just a weighted barycenter anymore?

# Answer
Calculate the relative offset from Default to each point and add them on top of Default with the given weights. This means that you can't divide by the sum of the weights unlike in the previous answer you got.

```
deltaA = A - Default;
deltaB = B - Default;
deltaC = C - Default;
point = Default + deltaA * weightA + deltaB * weightB + deltaC * weightC;

```
> 1 votes

---
Tags: 3d, animation, geometry, blending, tweening
---


title: Prince of Persia - Original code

text:
# Question
Title: Prince of Persia - Original code
Any way to run original Prince of Persia code?
The code is hosted here.

Or if it is out of possible what is the best incarnation of this game ? PC/Amiga or whatever porting ?

# Answer
According to the readme, it's written in 6502 assembly language. That means it is programmed especially for the MOS Technology 6502 CPU which was used by Apple II computers and their various clones.

When you get an emulator for the Apple II and an assembler which runs in it, you might be able to compile and run it.
> 5 votes

---
Tags: emulation
---


title: logic behind a single player game

text:
# Question
Title: logic behind a single player game
i would like to code a single player game where at each turn a player has to write a letter on a grid. In response the computer would write a letter and so on. As soon as a word is created as a result of writing a letter, the player gets as many points as the no of letters in the word. how would i code it.

# Answer
> 1 votes
That’s a pretty easy almost-infinite loop. The main loop is something very common in game programming.

In Pseudo code:

```
playerTurn = 1 // playerTurn = 1 means its players turn, = 0 means computers turn

somebodyWon = False

while somebodyWon = False:
    if playerTurn:
        askPlayerForInput()
    else:
        writeInputFromComputerArtificialIntelligence()
    somebodyWon = checkIfSomebodyHasWonByUsingADictionary()

```

As you see, you need several components here:

* Main class where you handle this loop
* Some input for the player to input a letter (e.g. `scanf()` in C or `StreamReader` in Java)
* Some easy artificial intelligence for the computer (he could search for words in his dictionary and add one letter for some real word he sees in the dictionary). Ideally, the computer should only know a subset of all real words. This could depend on the difficulty of your game (e.g. on **very easy** it knows 10% of all words, on **very hard** it knows 90% of all words)
* A check for the input word against a list of winner words: Just take the word player + computer have already created and search in a dictionary (list of all real words) for it. If it is there, somebody has won.

---
Tags: game-design
---


# Question
Title: How do I get a Model to add a name to it's Texture(s) in the XNA Content Pipeline
I know that a texture's name is not preserved when it's loaded in. I also know that you can give it a name. For example:

```
Texture2D texture = content.Load<Texture2D>("MyTexture");
texture.Name = "MyTexture"; //Or whatever else you want to call it

```

However, what about when you load a model? It automatically loads in the right texture for each ModelMeshPart, and drops the Name (no idea why though). This is fine, right up until the point where you actually want to identify which texture that ModelMeshPart is using. I found someone else having the same problem here. Shawn Hargreaves gave this solution:

> If you need access to this data at runtime, you will need to extend the pipeline to store it somewhere else. For instance you could use a custom processor to store texture filenames in the ModelMeshPart.Tag property

I figured that was easy enough. Yeah...feel free to point and laugh. I got as far as creating a custom proccessor class and inheriting the standard ModelProcessor before I realised that I didn't know exactly where the ModelMeshPart's texture was stored and I've spent the past few days trying to find out.

I just want to preserve each part's texture name so that I can do something like

```
Model model = content.Load<Model>("MyModel");
BasicEffect effect = (BasicEffect)model.Meshes[0].MeshParts[0].Effect;
string texName = effect.Texture.Name;

```

Also Merry Christmas.

EDIT

For the record, I'm importing a .x model.

# Answer
> 3 votes
The best approach in my opinion is to store all texture references in the `ModelMeshPart.Tag` property like Shawn Hargreaves suggested. If you do it this way, you can decide which texture names you need in your game.

In order to achieve this, you need a custom model processor. The filename for each texture referenced in the `MeshPart` is stored in `MeshPart.Material.Textures`. So a simple approach to just save all texture filenames for later use would look like this:

```
using System.Collections.Generic;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

namespace ModelTextureNameExtension
{
    [ContentProcessor(DisplayName = "Model with texture names")]
    public class ModelTextureNameProcessor : ModelProcessor
    {
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            ModelContent modelContent = base.Process(input, context);

            StoreTextureFilenameInTag(modelContent);

            return modelContent;
        }

        private void StoreTextureFilenameInTag(ModelContent modelContent)
        {
            Dictionary<string, string> textureDictionary = new Dictionary<string, string>();

            foreach (var mesh in modelContent.Meshes)
            {
                foreach (var meshPart in mesh.MeshParts)
                {
                    foreach (var textureEntry in meshPart.Material.Textures)
                    {
                        textureDictionary.Add(textureEntry.Key, textureEntry.Value.Filename);
                    }

                    meshPart.Tag = textureDictionary;
                }
            }
        }
    }
}

```

When you import a model with this processor, you can access the extracted data in your game like this:

```
Model model = Content.Load<Model>("Models/MyModel");

foreach (var mesh in model.Meshes)
{
    foreach (var meshPart in mesh.MeshParts)
    {
        Dictionary<string, string> textureDictionary = meshPart.Tag as Dictionary<string, string>;

        // Use the filename of the texture you need
    }
}

```

Please note that the number of referenced textures strongly depends on the model you import. You can adjust the content processor to your needs if you know which texture you exactly need.

`textureEntry.Value.Name` is always (at least when I tried to use it) `null`, so you need to fetch the texture name from the file name. You could also use the name of the material in the mode file which is stored in `MeshPart.Material.Name`.

---
Tags: xna, c#, textures, models, xna-content-pipeline
---


# Question
Title: How to simulate a spinning helicopter rotor visual effect programatically?
I decided to display an animation that conveys to the viewer that a narrow flat surface is spinning really fast(such as an helicopter's rotor blade). Does anyone have any experience in implementing this effect and could provide an implementation? Please remember a rotor on video looks different than it does in real life. I need to make the rotor look like it does in real life and not on video.

# Answer
The way I've always done it is simply to create a pre-blurred version of the texture, something like this image, map it on a circle, and draw it using alpha blending. Make the circle spin pretty fast and you're done.
> 5 votes

---
Tags: graphics, graphic-effects
---


title: SFML - Completely Unlimit Framerate

text:
# Question
Title: SFML - Completely Unlimit Framerate
I am trying to completely unlimit the SFML framerate, so that as many frames will be displayed as possible. The reason for this is I want to loop through one section of code which calculates positions of objects in a physics simulation, and update the screen after perhaps 100 iterations.

I have done:

```
window.SetFramerateLimit(0);
window.UseVerticalSync(false);

```

The SFML documentation says this should set the frame rate to "infinity", but I still think it's stuck at about 60-ish...

Does anyone know how I can get more performance out of this?

Also once unlimited, I need to be able to do the equivalent of this in SFML, from SDL:

SDL.Delay(1000);

Is there a way of doing this? The SDL Delay is good because it frees CPU time for other processes. Any help would be greatly appreciated, especially as it's Christmas and you probably have better things to do! (I don't I'm a student.)

# Answer
Those values you set are set to that by default you shouldn't have to explicitly write that. Anyway why you are stuck at 60 is probably because your driver still has vertical sync enabled. The driver can choose to override any application, you should be able to change this in the drivers control panel.

And equivalent to SDL.Delay(1000) in SFML would be: sf::sleep(sf::seconds(1)) if you are using SFML 2.0-RC or sf::Sleep(1) if you are using the obsolete 1.6
> 2 votes

---
Tags: c++, performance, sfml
---


title: 2D graphics scaling

text:
# Question
Title: 2D graphics scaling
I've been wondering how to achieve some kind of zooming behavior with 2D graphics. I'm pretty sure that this is not right term, but let me try to explain my thoughts.

Let's start by defining that we are using here tileset with 16x16 tiles. That would something like this:

When we're looking these graphics here, all the tiles look pretty small. Now, when we load this tileset to RPG Maker 2K and look at it in game, it looks something like this:

Like you can see, the image is more zoomed and tiles look a lot more bigger than in a real tileset. How do you think this kind of effect is done in code and how I can do it?

# Answer
> 3 votes
The term you're looking for is *scaling*, not zooming.

If you search scaling algorithms, you'll find a very large number of them. Different scaling algorithms have different qualities and are optimized for different purposes. Some are designed to scale up low-quality bitmaps while making them look smooth and pretty, often used when trying to play games made for old resolutions like 320x200 at newer monitor resolution sizes like 1920x1080.

Your graphics hardware has several simpler scaling algorithms naturally built in. If you try to render a 16x16 texture to a square that is 64x64 in size, OpenGL/Direct3D will just do the right thing. They'll also handle uneven sizes. The same is going to be true of whatever other low-level 2D graphics API you might be using.

The simplest approach is to just change your sample rate. Say you have a 16x16 bitmap that you want to scale up to 32x32. That is a 2x increase in dimension, so you would "sample" the source bitmap twice in each dimension (for a total for four samples). Example:

```
Source = 1 2
         3 4
Destination =
         1 1 2 2
         1 1 2 2
         3 3 4 4
         3 3 4 4

```

Notice how for the first row in the source, we wrote out each element twice in the destination. Likewise, for each row in the source, we wrote out two rows in the destination. 2x scale factor.

In code, that might look something like following (in one dimension; should be simple enough for you to expand to two dimensions):

```
scale = in_width / out_width;
for (dx = 0, sx = 0; dx < out_width; ++dx, sx += scale)
{
   output[dx] = input[sx];
}

```

Note that scale is the reciprocal of the scale factor. That is, a 2x scale would actually be 1/2 in the code above. The terminology can be a little ambiguous and confusing, unfortunately.

The algorithm will handle scaling up and down, to even or uneven sizes. If you expand it to two dimensions properly, it'll even handle scaling to different aspect ratios (e.g., changing a square input bitmap to a rectangular output). The results won't be great, but they'll work. I wouldn't use that code in production, but if you want to get your feet wet with some basic bitmap manipulation code, it's as good a starting point as any.

There are much more robust and efficient ways to write that, but I'd guess those might be a bit beyond your current skill level.

If you are interested in higher quality scaling algorithms, or more optimized scaling algorithms, take a look at the excellent WikiPedia Image Scaling article, which covers most of them and has either explanations of the algorithms or links to pages with explanations.

---
Tags: 2d, graphics
---


title: XNA 4.0 - Transparent 3D model

text:
# Question
Title: XNA 4.0 - Transparent 3D model
I have a little problem with my 3D model (.fbx) rendered in XNA, look at screenshot.

Screenshot:

It should be a lego brick, which was modelated in Blender, then exported to .fbx and added to XNA project. My problem is transparency, I tried so much with depthbuffer, z-buffer etc., but nothing helped. Here's my code:

```
namespace Using3DModels
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;

    float myModelRotation;
    Vector3 myModelPosition;
    /// <summary>
    /// Stores the model that we are going to draw.
    /// </summary>
    private Model model;

    /// <summary>
    /// Stores the world matrix for the model, which transforms the
    /// model to be in the correct position, scale, and rotation
    /// in the game world.
    /// </summary>
    private Matrix world = Matrix.CreateTranslation(new Vector3(6, 4, 0));

    /// <summary>
    /// Stores the view matrix for the model, which gets the model
    /// in the right place, relative to the camera.
    /// </summary>
    private Matrix view = Matrix.CreateLookAt(new Vector3(30, 25, -10), new Vector3(5, 5, 0), Vector3.UnitY);

    /// <summary>
    /// Stores the projection matrix, which gets the model projected
    /// onto the screen in the correct way.  Essentially, this defines the
    /// properties of the camera you are using.
    /// </summary>
    private Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45), 800f / 480f, 0.1f, 100f);

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
        graphics.PreferMultiSampling = true;
    }

    /// <summary>
    /// Allows the game to perform any initialization it needs to before starting to run.
    /// This is where it can query for any required services and load any non-graphic
    /// related content.  Calling base.Initialize will enumerate through any components
    /// and initialize them as well.
    /// </summary>
    protected override void Initialize()
    {
        base.Initialize();
    }

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);

        model = Content.Load<Model>("lego6");

        myModelPosition = Vector3.Zero;
        myModelRotation = MathHelper.ToRadians(45f);
    }

    /// <summary>
    /// UnloadContent will be called once per game and is the place to unload
    /// all content.
    /// </summary>
    protected override void UnloadContent()
    {
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        myModelRotation += MathHelper.ToRadians(1f);

        base.Update(gameTime);
    }

    /// <summary>
    /// This is called when the game should draw itself.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.BlendState = BlendState.Opaque;
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;
        GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

        GraphicsDevice.Clear(Color.DarkGray);

        DrawModel(model, world, view, projection);

        base.Draw(gameTime);
    }

    /// <summary>
    /// Does the work of drawing a model, given specific world, view, and projection
    /// matrices.
    /// </summary>
    /// <param name="model">The model to draw</param>
    /// <param name="world">The transformation matrix to get the model in the right place in the world.</param>
    /// <param name="view">The transformation matrix to get the model in the right place, relative to the camera.</param>
    /// <param name="projection">The transformation matrix to project the model's points onto the screen correctly.</param>
    private void DrawModel(Model model, Matrix world, Matrix view, Matrix projection)
    {
        GraphicsDevice.DepthStencilState = DepthStencilState.Default;

        Matrix[] transforms = new Matrix[model.Bones.Count];
        model.CopyAbsoluteBoneTransformsTo(transforms);

        foreach (ModelMesh mesh in model.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(myModelRotation) * Matrix.CreateTranslation(myModelPosition);
                effect.View = view;
                effect.Projection = projection;

            }

            mesh.Draw();
        }
    }

}
}

```

# Answer
This looks like a culling issue, like Trevor Powell pointed out. A simple way to test if it really is a problem related to culling is to turn it off like this:

```
RasterizerState rasterizerState = new RasterizerState();
rasterizerState.CullMode = CullMode.None;
GraphicsDevice.RasterizerState = rasterizerState;

```

Please note that disabling culling is not the best idea (except for some corner cases where you want to achieve some special effect) for a shipping product, because it also draws triangles not facing the camera and thus slowing down the drawing.
> 4 votes

---
Tags: xna, 3d, transparency
---


# Question
Title: Java creating new Sprites coding problem
So I'm trying to load various different types of grass Sprites from the same spritesheet. However, the code looks really ugly. The thing is I have

```
public static Sprite grassi = new Sprite(16,i-1,0,SpriteSheet.tiles);

```

Now I was wondering is there a way to put this into a for loop. As I currently, have this mess below

```
public static Sprite grass1 = new Sprite(16,0,0,SpriteSheet.tiles);
public static Sprite grass2 = new Sprite(16,1,0,SpriteSheet.tiles);
public static Sprite grass3 = new Sprite(16,2,0,SpriteSheet.tiles);
public static Sprite grass4 = new Sprite(16,3,0,SpriteSheet.tiles);
public static Sprite grass5 = new Sprite(16,4,0,SpriteSheet.tiles);
public static Sprite grass6 = new Sprite(16,5,0,SpriteSheet.tiles);
public static Sprite grass7 = new Sprite(16,6,0,SpriteSheet.tiles);
public static Sprite grass8 = new Sprite(16,7,0,SpriteSheet.tiles);
public static Sprite grass9 = new Sprite(16,8,0,SpriteSheet.tiles);
public static Sprite grass10 = new Sprite(16,9,0,SpriteSheet.tiles);
public static Sprite grass11 = new Sprite(16,10,0,SpriteSheet.tiles);
public static Sprite grass12= new Sprite(16,11,0,SpriteSheet.tiles);
public static Sprite grass13 = new Sprite(16,12,0,SpriteSheet.tiles);
public static Sprite grass14 = new Sprite(16,13,0,SpriteSheet.tiles);
public static Sprite grass15 = new Sprite(16,14,0,SpriteSheet.tiles);
public static Sprite grass16 = new Sprite(16,15,0,SpriteSheet.tiles);

```

This works, but it destroys the code as it's a big mess. I also have 16x16 SpriteSheet and don't want to do this for every sprite.

# Answer
> 0 votes
A decent option for sprite lookup is the combination of a HashMap with enums. You have an enum to define the type and the HashMap holds the lists of different types. For example:

```
public enum SpriteType {
    Grass,
    Dirt,
    Rock;
}

HashMap<SpriteType, ArrayList<Sprite>> spritesByType =
    new HashMap<SpriteType, ArrayList<Sprite>>();

```

Then for adding all your sprites you can do something like this:

```
for(SpriteType st : SpriteType.Values()) {
    int spriteCount = getSpriteCountForType(st);
    int spriteColumn = getSpriteColumnForType(st);
    spritesByType.put(st, new ArrayList<Sprite>());
    for(int i = 0; i < spriteCount; i++) {
        spritesByType.get(st).add(new Sprite(spriteColumn,i,0,SpriteSheet.tiles));
    }
}

```

Then accessing is easy too:

```
randomGrassSprite =
   spritesByType.get(Grass).get(RandomInt(getSpriteCountForType(Grass)));

```

---
Tags: java
---


title: Texture-Mapping in Blender/XNA

text:
# Question
Title: Texture-Mapping in Blender/XNA
I have a simple Blender-Model (just a few faces). I want to add 2 Textures. (a special face should get Texture 1, the other faces Texture 2). This model I want to use in XNA.

The first Texture should be replaceable at Runtime by Code (the new image is generated based on user input).

So how do I best solve this: Using UV-Maps or Normal-based Maps in Blender? How can I access the Blender UV-Mapping in XNA? Or do I completely perform the Texturing in XNA (using Code or shaders)? And how (I´m new to this)?

# Answer
> 1 votes
Blender can only export UV Maps for skinning Models in XNA. So i created in Blender a Model with 2 Materials containing a Texture (by UV maps). I exported the Model using the built-in FBX-Exporter.

In XNA the default-processor can load the FBX file. In XNA the Textures of the model can be accessed and changed by loading (or generating) a Texture2D-Object. This object can easily replace the default skin:

```
Texture2D bg = Content.Load<Texture2D> ("bgimage");
((BasicEffect)myModel.Meshes[0].Effects[1]).Texture = bg;

```

---
Tags: xna, c#, blender
---


# Question
Title: How to find a game server in the LAN network with IPv6 technology?
Back in the IPv4 days, people simply used broadcast packets check if there are any server available in the network as described in this answer. But in the IPv6 protocol they've dropped broadcast support. There is still multicast support available but how can/should I use it?

# Answer
> 7 votes
With broadcast the client sends a message to everybody on the network and all the servers reply. With multicast you define a multicast group address and all the servers subscribe to it. The client then sends a message to the group, the servers that have subscribed receive it and reply.

Multicast is for when one sender wants to send to a group of receivers, like when a game client wants to send to a (potential) group of servers. Multicast addresses are special addresses where the system knows to treat them differently. The receiver tells the system that it wants to receive messages sent to a particular group, and the sender sends a message to the group address. On a LAN this just works. Across LANs you need multicast routing which isn't implemented on mostnetworks. But broadcast wouldn't work across LANs either.

Using multicast makes sure that only the systems on the network that care about getting the message will receive it.

How you implement this depends on the programming language etc.

The structure of an IPv6 multicast address is as follows:

* It always starts with the first 8 bits of the address set to 1, which means that the first two characters of the address will be `ff`;
* The 3rd character (bits 9 to 12) in the address specifies flags. In your case you probably want a fixed multicast address for your application. In that case the 3rd character will be a `0` which indicates a permanently assigned multicast address;
* The 4th character (bits 13 to 16) determine the scope of the address. You will very probably Use the value `2` for link-local (LAN) scope.

Together this means that you'll use an address starting with `ff02:`.

Multicast addresses are assigned by IANA. RFC3307 defines how to do it (the criteria is Expert Review, so it's not necessary to write an RFC on what you are doing or anything like that). In this answer I'll use the multicast address `ff02::db8:aa:bb`, which is in the block reserved for documentation.

You don't have to have root access to use multicast. The following Python3.3 examples can be run with a normal user account:

The server (listening on the multicast address):

```
#!/usr/bin/env python3.3
import socket
import struct

if_idx = socket.if_nametoindex('en0')
addr = 'ff02::db8:aa:bb'
port = 42424
group = socket.inet_pton(socket.AF_INET6, addr) + struct.pack("I", if_idx)

sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_JOIN_GROUP, group)
sock.bind(('::', port))

while True:
  msg, sender = sock.recvfrom(1024)
  print('Received "%s" from "%s"' % (str(msg, 'UTF-8'), sender))
  sock.sendto(bytes('Received %d bytes from you' % len(msg), 'UTF-8'), sender)

```

And the client (sending to the multicast group and listening for the replies):

```
#!/usr/bin/env python3.3
import socket

if_idx = socket.if_nametoindex('en0')
addr = 'ff02::db8:aa:bb'
port = 42424

sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, if_idx)

sock.sendto(bytes('Hello there!', 'UTF-8'), (addr, port))
while True:
  # You probably wait a certain time for replies, not indefinitely like this example
  msg, sender = sock.recvfrom(1024)
  print('Received "%s" from "%s"' % (str(msg, 'UTF-8'), sender))

```

I used Python 3.3 because older versions don't have `socket.if_nametoindex`, but everything else should also work in Python 2.

PS: using an existing library or framework for service discovery as suggested in another answer is a good idea. It will use multicast under the hood but save you from having to design and implement your own protocol.

# Answer
> 4 votes
There are protocols for service discovery which modern applications should use instead of broadcast or home-spun multicast solutions, whether you're on IPv4 or IPv6.

Apple pushes mDNS/DNS-SD and Microsoft pushes UPnP. Both accomplish the same goals for simple service discovery, while UPnP offers many additional features.

There are freely available libraries for both of those APIs for a multiple platforms. The relevant OSes include native support. Linux offers support via semi-standard system components installed by default on most distros.

Note that UPnP can also be used for firewall configuration and hence may be the better choice for games that plan on having Internet play, although you can't rely on or require UPnP firewall control since many users don't have compatible routers or turn the feature off out of paranoia.

---
Tags: networking
---


# Question
Title: searching for "university kind"  free online course about OPENGL
I know there are a lot of free university courses, but I'm trying to find one about OpenGL. Do you know where can I find one, online?

# Answer
I'm not familiar with the website, but there appears to be free courses on Connexions:

http://cnx.org/content/expanded\_browse\_authors?letter=P&author=professorpayne

Personally, I learned a lot from NeHe:

http://nehe.gamedev.net/

Edit: Actually, don't use NeHe. Most of what it teaches you has been deprecated. I'm not sure there is a free university course for modern OpenGL, but this list of resources is fantastic.
> 4 votes

# Answer
I think you should learn 3 things, to work with OpenGL:

* basic Linear Algebra and 3D geometry (vector spaces, linear transformations, normals ...)
* triangle meshes and how they work, how to store them into "buffers"
* general programming and general math skills to use in shader programming

Try google for that. When you learn it, then you can start to use OpenGL or DirectX or anything you want. It will be very simple for you.

BTW I really doubt that some university is going to "teach OpenGL". Maybe you can find courses about "hardware accelerated rasterization", which may cover different ideas and techniques, but definitly not "teach OpenGL".
> 7 votes

# Answer
I've very recently come across Programming for Games / Graphics for Games / Game Techniques from Newcastle Uni. There's a series of course PDFs, source code for their framework, etc. All done using modern OpenGL (3.4) and written as clean and tidy code.

It's one of the best public game related OGL resources I've found yet.
> 3 votes

# Answer
Udacity are launching an Interactive Rendering course. I'm guessing it's WebGL though. Not sure it's it's in JavaScript or has some Python bindings.
> 1 votes

---
Tags: opengl
---


title: How to make racer map?

text:
# Question
Title: How to make racer map?
Hi everyone does 3D racer games use heightmap to build tracks or programmers just use easier solution ? I need to build only track space(road) without fill all hectares with trinagels and more important i need to raise smooth ascents on this tracks

i aksing for some tips not for completle solution of course.

# Answer
> 3 votes
Well typically the map is modeled in 3D with everything included, and perhaps a spline of the race track. For things like grassy parts that slow down the car/whatever, you can look at the materials under the car to decide how to affect physics. I can't see heightmaps being used for racing games. Shawn Hargreaves (who was on the XNA team) also worked on Moto GP. Here are two articles on how some of the design was done in that game:

(for all of his articles on MotoGP: http://www.shawnhargreaves.com/blogindex.html#MotoGP)

---
Tags: xna, c#, 3d
---


# Question
Title: Distinguishing between multiple objects with the same name in a text based adventure game/interactive fiction
I'm in the middle of writing my own parser in Python. I've managed to make some simple commands, with simple prints to make sure they work. Since I intend there to be combat, I needed to write a command for attacking something. I just completed that.

My issue is: What should I do to allow the player to choose which of a given enemy they attack? It is fairly simple when they are different types of enemies (e.g. a goblin and a troglodyte), but how should I distinguish between two of the same type (e.g two troglodytes)?

Suggestions I have had so far: Give each of them a significant feature (color, height, relative direction) but that only so far; name each of them (so you attack "bob" or "steve"); or the one I have been favoring the most, give them each a number (so there would be troglodyte1, troglodyte2 etc.)-this might break some immersion, though.

# Answer
> 5 votes
You have what I feel are two distinct problems. One is a design problem: how to deal with multiple distinct objects that have no distinct visualizable characteristics. The second problem is a technical problem, which is how to make it easy to identify individual objects out of a group via commands.

**Technical Solution**

Back in my MUD programming days, I just added syntax for specifying ordinals. Most MUDs do the same, albeit most only support a terse syntax.

For example, you can parse out the following words from an enemy or item argument to a command: first, second, other, third, fourth, fifth, etc.

You can usually stop around "third" to "fifth" depending on how common those sizes of groups are in your game. I used "other" as a synonym for "second".

You'll also want a way to just enter in the ordinal with digits, so you don't need a huge dictionary (or all the crazy logic to deal with English ordinals, at least). Parsing "1st", "2nd", "3rd", etc. is pretty easy. There's only a few special rules for those ("11th", "12th" and "13th") and the rest all follow a simple pattern. Going this route, make the suffixes optional.

The result is that you can type in phrases like:

```
attack third goblin
pet other wolf
get 4th sword

```

You can even parse out and throw away a leading "the" if you want to please the 0.02% of your players who feel a need to type out full English sentences. (It's a neat feature to demo, but really, nobody who plays these games is interested in typing that much, and these days you'll be lucky if half your players can spell "fourth" correctly much less use proper grammar.)

Typical MUDs and text adventures use a terser method of specifying ordinals, usually with some special punctuation. For example, you might have to put a period or a colon or some such followed or preceded by a number, e.g. ".5", giving you syntax like one of the following:

```
kill .5 goblin
kill :5 goblin
kill 5:goblin

```

Note that this solution works even when you have distinct names. Maybe you have a "large ornery goblin" and a "small timid goblin." The player doesn't want to type all that out. The player will be happiest if you support partial matches. The player still wants to easily identify both goblins when typing, though. Ordinals are one way the player can do that, assuming there is a clear ordering to the goblins.

**Design Solution**

Don't have non-distinct items and creatures or, if you do, have them implicitly act as a whole. You listed that as an option to solving the problem. It really is a good one, but only if you can do it completely.

Consider the case where you have five goblins in your typical MUD-like environments (interconnected "rooms"). The player enters the room and sees:

```
[Cavern Entrance]
There are five goblins (hostile) here.
Exits to the north and south.

```

The player wants to attack first, so he types:

```
attack goblin

```

The player attacks the first goblin (first by implication of not specifying another, which is just whichever goblin is arbitrarily first in the list of enemy game objects you have. The player does some damage to the goblin. Then the player sees:

```
A goblin flees north.

```

The player looks around again, and sees:

```
[Cavern Entrance]
There are four goblins (hostile) here.
Exits to the north and south.

```

A goblin fled. The problem is, which goblin was it? The one that the player injured? One of the other goblins? The player doesn't know. Let's say it was the injured goblin for this example.

The player continues fighting:

```
attack goblin

```

The player attacks the goblin that is now the first goblin (but was previously the second goblin). A few moments later, the player sees:

```
A goblin enters from the north.

```

The goblin that fled got its courage back and returned. Likely, it is added to the end of a list of some kind in the game code, so it is now the fifth goblin. If the player looks again, he sees:

```
[Cavern Entrance]
There are five goblins (hostile) here.
Exits to the north and south.

```

Again, the player attacks. Only, the player has no idea which goblin he's attacking. Is it the injured one? A different one? How does he tell that one of the goblins is injured? How can he target that goblin? We know that the injured one is the fifth goblin, but without some way of visualizing that, the player can't know it for sure. And you probably want to avoid overly verbose output like:

```
[Cavern Entrance]
There are five goblins (hostile) here.
The second goblin is injured.
The third goblin is injured.
The fourth goblin has a nasty rash.
The fifth goblin looks longingly at the second
  goblin, but the second goblin is out of his league.
Exits to the north and south.

```

That's where the design decision comes in.

One option is to treat all game objects of the same type grouped together as a single entity. Hence, you do not have five individual goblins with individual health values. You have a group of five goblins with a single shared health value. Whenever that health value is reduced below zero, the number of goblins is decremented by one and the health is incremented by the per-goblin health value.

Example: Say goblins have 12 health, and there are 5 goblins. You have a single goblin object that has a count of 5 and a health of 12. The player does 20 damage to the group. Health is now -8. One goblin is subtracted from the count (there are now 4 goblins), and the health is incremented by 12 (health is now 4). If the player does 4 more damage, another goblin will be killed.

Combining and splitting groups is a little wonky in this case, but it can be fudged. When a second group of goblins shows up, take the sum of their counts and the minimum of their health. When some number of goblins should flee, their count is subjected by the number that don't flee, and a new group object with that count is created with full health (the original group should also leave the room as part of this operation so that they don't automatically merge back together).

This of course changes the dynamics of the game a bit. The player can no longer decide to weaken all the goblins and then finish them all in one area attack. He is implicitly always attacking the weakest goblin. This small trade-off in flexibility gives you a much more obvious, clean, understandable, and approachable UI for a text game, however. It's up to your design constraints to decide if the trade-off is appropriate.

There are other variations of this approach you could use as well. Anything that statistically approximates a group of individuals with some broad group numbers works fine. Strategy games like Heroes of Might & Magic or Warlords do something like this. Rather than dealing with individual units, the player has "stacks" of units, which are treated as a single entity.

# Answer
> 3 votes
Instead of distinguishing them by different names or colors you could give the player a variety of commands with the power to distinguish.

For example, if **"five goblins attack you"**, you could invent either numbered or named commands like \- "attack first goblin" or \- "attach goblin 1"

This approach is almost like you already suggested, but instead of naming or presenting a long boring to read list of enemies, you just tell the player the amount and the player decides how he likes to interact/type.

Also, you could have a database of random names to choose from, if you really want to distinguish uniquely between enemies.

# Answer
> 1 votes
The way classic text adventure games of the Infocom style solved this problem was, indeed, by making sure that every distinct object did indeed have a name that allowed it to be uniquely identified.

A detail to note is that, in Infocom-style parsers, one could refer to an object by any combination of words in its name. So, if the player came across a `red chrysanthemum`, a `red circular amulet` and a `green triangular amulet`, typing either:

```
> get red amulet

```

or just:

```
> get circular

```

would allow the player to take the red circular amulet, while typing:

```
> get red

```

would (if both objects were indeed present) produce a clarification request like:

```
Which do you mean: the red chrysanthemum or the red circular amulet?

```

Also, objects might well have synonyms that were not part of their display name, so, for example, typing:

```
> get red flower

```

would very likely also work for picking up the red chrysanthemum. Indeed, players would (and, indeed, still do) very much expect any well written game to understand such natural synonyms. Similarly, an amulet might also match the word `pendant`, especially if it was described as being or resembling one anywhere in the game, and the circular amulet might also be described as `round`.

Indeed, this parsing style is still very much in use in modern interactive fiction. For example, you might want to take a look at how the parser recognizes objects in Inform 7, a special-purpose language designed for writing this kind of games.

---

Ps. Roguelike games, which typically have a lot more objects, generally solve the same problem in a different way: they let you pick the object you want from a menu. Some of them, to deal with the potential issue of apparently identical objects that nonetheless are different somehow, also allow the player to name individual objects, or even entire classes of objects, so that one might see e.g.

```
What do you want to light [p-r]?
 p - a lamp
 q - a lamp called "magic"
 r - a lamp called "magic" named "this one's probably cursed"

```

# Answer
> 1 votes
It looks like most of the territory has been covered for major methodologies, but I thought it might be a good thought exercise to step through how you might want to conceptualize this decision anyways, and stretch myself to cover some methods I haven't seen.

# Perspective and Quantification methods

Several of the solutions involve working around this question by using names or features to identify the monsters. In order to address the purest version of this question, we'll assume you are confronted by N identical goblins.

They are inevitably arrayed in some spatial arrangement and you will end up with a few ways to describe their arrangement in relation to you:

### Top Down Perspective

1. They may be described with yourself as dead-center on a compass. This allows for the richest spatial arrangement but let's imagine all 5 goblins are in a line due north from you--"north" alone is not sufficient for distinguishing their arrangement.

### First-person Perspective

1. They may be described in an informal version of the above (left, front, right, back). This has similar limitations, but this is relative to your orientation at any given moment. This may also be restricted to what you can "see" (you'd need to have some form of magical vision to target something behind you.)

### Quantification

Both of these cases allow for indicating spatial arrangement but do nothing for clarifying between multiples in the same relative space. We can add some concept of closeness which could be either applied on its own or in order to augment one of the above conceptions.

1. They may be *described* based on their closeness to you in verbal form. Near to far. This has obvious quantification limitations, but given a spatial arrangement we realize that the relevance of goblins beyond the "nearest" are only relevant if you have some sort of ranged method of hitting them (or some method of running past any number of intervening goblins to attack the last.) This method of distinction is most compatible with the "stack" methodology suggested by others.
2. They may be *quantified* based on their closeness to you. The first goblin is the closest, and the Nth goblin is the furthest. This alone is probably the most common method of distinction in use.

### Other

1. You might be able to use some sort of newfangled client or technology to require the player to click on the name to attack.

# Naming and Description methods

There are a number of approaches here, and they all involve sidestepping the need for resolving the text medium's weakness at these forms of reference:

1. assure the monsters are unique in the design phase and need no distinguishing
2. generate random, locally unique properties for distinguishing them
3. generate semi-random names (probably with algorithms tailored to race/class)
4. generate unique random indicators as meta-data for targeting (one or two alpha characters).

# More radical solutions

All of the various solutions thus far are predicated on the assumption the task of targeting other objects with actions is that of the player. If we are suspicious of this assumption some new possibilities open up to us:

1. It might instead be the case that your game is set in a realm where creatures dictate action; mobiles will decide whether they attack or interact with the player and the player takes on a purely reactionary role within the world.
2. Mobiles in your world might engage with you based on actions you take. To give an example, a guard may refuse to engage in hostilities with you until you try to sneak or push past him at which point he engages you in combat. Rather than trying something like "ask spy about village", you might instead "ask about village" and allow all present mobiles a chance to respond.
3. We might design a slow, deliberative game in which the player is presented with ALL options in some sort of alpha-numeric selection mode. (i.e., select option 1 to go west; you go west; what would you like to do: 1 - go west, 2 - go east, 3 - attack the ugly goblin, 4 - talk to the ugly goblin...)
4. We might design an even more deliberative version of the same concept in which the player is making branched decisions in a choose-your-own-adventure sort of style. The player might be confronted with a choice between one of two skills, and rather than having points and agency to train the other later on, the skill they didn't choose might never be presented again.

# Deciding: mechanics, tedium and immersion

A useful discussion to have with yourself is probably: what sort of pace and scale do we want our game to have? You could ask questions about verbosity and linguistic purity, but I feel like these are values which must ultimately be in harmony with your primary decision about how your game will play. If your game will involve occasional combat with a sparse collection of NPCs I suspect it's very viable for you to have a descriptive selection system. If your game is a hack-and-slash where players kill hundreds of mobiles an hour, making them have to read and re-type properties frequently is going to either be tedious, or get shifted off onto triggers.

Part of the discussion surrounding this decision seems to be predicated on the idea that "get amulet 2" or "get 2nd amulet" is somehow breaking immersion with the intrusion metadata; I'd argue contrarily that being asked by the game's parser whether I meant the red amulet or the green amulet is a far more egregious attack on my suspension of disbelief than the former--it subverts my agency, reminds me of the ever-present role of the parser, and speaks with a disembodied voice. We live in a world where spatial decisions make sense. You don't stand before a police line-up and select the guy with beat-up Levi's, black hair and a porn-stache; you identify the suspect within space based on these very properties--but then you select an appropriate number along a logical scale from left to right to communicate quickly and clearly.

# Conclusion

Only two of the answers proposed actually resolve the root question: *How does the game disambiguate between references to like objects if/when they occur?* One of these is to demand clarification from the player after the request, and the other is to assume a logical spatial arrangement of some sort and assume the player doesn't need to clarify the ambiguity. There's a time and place for both of these, but there's a big difference between the two--and I think it probably behooves most text games to answer this question in the parser rather than by attempting to contrive a game in which two identical items will never be present and need referring to.

I'm obviously a fan of a numeric reference, but I think you can also combine a variety of the various ideas that have cropped up to sculpt the feel of your game. You can also leave these decisions up to the player, and provide them with the ability to choose between a parser that responds to ambiguous requests with a question, and a parser that executes ambiguous requests with an assumption. You can, for that matter, give players the option of generating a meta-data indicator for each item which they may use to refer to it.

---
Tags: text-based, interactive-fiction
---