# Question
Title: Can I use one set of images to represent multiple sprites in Java?
I've got a game that has 3 basic sprites, at the moment I'm loading 8 images into each sprite for animating. Each character class has a sprite object. if I've got 10 characters on screen at once then that's 80 images loaded in to memory. Can I make a central sprite class that only holds 8 images for each of the 3 sprites, then get the character objects to request the relevant images from the central sprite class, thereby massively reducing the memory required for the images?

# Answer
> 2 votes
You can and you probably should. I believe that in Java (as in C#) objects are going to be passed by reference, so you should get this behavior by default without doing any extra work.

Code like this:

```
Sprite spr = Sprite.LoadFromFile("c:\sprite.s");

Character c1 = new Character(spr, x1, y1);
Character c2 = new Character(spr, x2, y2);
Character c3 = new Character(spr, x3, y3);

```

Should give you three `Character` objects all referencing the same Sprite object.

A quick search shows that I stand corrected. Java is in fact pass-by-value; however, since java has "pointers" the result in the code above should remain the same. Java passes the pointer to the sprite by value; but they will all still "reference" the same sprite.

---
Tags: java, graphics, image
---


# Question
Title: vector rotations for branches of a 3d tree
I'm attempting to create a 3d tree procedurally. I'm hoping that someone can check my vector rotation maths, as I'm a bit confused.

I'm using an l-system (a recursive algorithm for generating branches).

The trunk of the tree is the root node. It's orientation is aligned to the y axis.

In the next iteration of the tree (e.g. the first branches), I might create a branch that is oriented say by +10 degrees in the X axis and a similar amount in the Z axis, relative to the trunk.

I know that I should keep a rotation matrix at each branch, so that it can be applied to child branches, along with any modifications to the child branch.

My questions then:

for the trunk, the rotation matrix - is that just the identity matrix * initial orientation vector ?

for the first branch (and subsequent branches) - I'll "inherit" the rotation matrix of the parent branch, and apply x and z rotations to that also.

e.g.

```
using glm::normalize;
using glm::rotateX;
using glm::vec4;
using glm::mat4;
using glm::rotate;

vec4 vYAxis     = vec4(0.0f, 1.0f, 0.0f, 0.0f);
vec4 vInitial   = normalize( rotateX( vYAxis, 10.0f ) );

mat4 mRotation  = mat4(1.0);

// trunk rotation matrix = identity * initial orientation vector
mRotation *= vInitial;

// first branch = parent rotation matrix * this branches rotations
mRotation *= rotate( 10.0f, 1.0f, 0.0f, 0.0f );     // x rotation
mRotation *= rotate( 10.0f, 0.0f, 0.0f, 1.0f );     // z rotation

```

Are my maths and approach correct, or am I completely wrong?

Finally, I'm using the glm library with OpenGL / C++ for this. Is the order of x rotation and z rotation important?

# Answer
> 0 votes
From what I can see your approach is good, and your math seems alright as well. I would compile the code and see what the result is to make sure though.

---
Tags: c++, opengl, vector, rotation, glm
---


# Question
Title: I made a game in XNA - how can I share it with my friends?
I've just finished programming a charming (albeit bare-bones) XNA version of arcade classic Tempest.

Hooray!

Given that this was a homework assignment, I'd like to be able to share it with my professor and my friends/classmates to solicit feedback.

(And let's be honest - if I have a question about how to add in an additional feature, it might be nice to be able to share it with folks on this site as well.)

Is there a better way of sharing an XNA game than by shuttling the visual studio - produced executable around? Some way to host it on a website would be ideal.

# Answer
> 7 votes
ClickOnce is pretty much perfect for hosting it on a website, you'll get auto-update and dependencies installer for free. There's a few gotchas but, it seems to work ok to me.

MSDN Link

# Answer
> 3 votes
Neither of those will work for Xbox 360 version of it, you have to upload it to creators club to share it or distribute the built XNA package.

# Answer
> 2 votes
You could upload the executable to google docs and share it with them from there, depending on the size.

# Answer
> 1 votes
I'd use ClickOnce as mentioned by Oskar - It works a treat. For really simple hosting and small scale distribution, I would get dropbox and drop it into your public folder and bit.ly it. then all you need to do is pass the shortened bit.ly link around to your friends/teacher etc.

---
Tags: xna
---


# Question
Title: library or stock code for mouse and key navigating around a terrain
My game is a classic RTS where the user can move around the landscape by moving the mouse to the edge of the screen or using keys. Eventually I'd want to think about multi-touch alternatives too.

Is there a library for this, or a simple tutorial that shows clearly how best to do it?

# Answer
> 3 votes
I don't think there is a library, but as for how to do it, it depends on whether the game is 3d or 2d. For 3d, you should check if the mouse position is touching one of the edges of the screen and then change the position of the camera, or world matrix if you dont use one. Something like this:

```
public int tolerance = 1;
public int speed = 5;
private Camera camera;

public void CheckCameraMoves(int mouseX, int mouseY, int screenWidth, int screenHeight)
{
    if (mouseX < tolerance)
    {
        camera.X -= speed;
    }
    else if (mouseX > screenWidth - tolerance)
    {
        camera.X += speed;
    }
    if (mouseY < tolerance)
    {
        camera.Y -= speed;
    }
    else if (mouseY > screenHeight - tolerance)
    {
        camera.Y += speed;
    }
}

```

You could also make it nicer looking by smoothing the speed out like this:

```
    if (mouseX < tolerance)
    {
        camera.X -= (int)(speed * (tolerance-mouseX)/tolerance);
    }
    else if (mouseX > screenWidth - tolerance)
    {
        camera.X += (int)(speed * (mouseX-screenWidth+tolerance)/tolerance);
    }
    if (mouseY < tolerance)
    {
        camera.Y -= (int)(speed * (tolerance-mouseY)/tolerance);
    }
    else if (mouseY > screenHeight - tolerance)
    {
        (int)(speed * (mouseX-screenWidth+tolerance)/tolerance);
    }

```

This way as the mouse gets closer to the edge of the screen it starts to accelerate towards the speed given.

---
Tags: input
---


# Question
Title: UDK : UTWeap_RocketLauncher gift CreateInventory: Any idea why this does not work properly?
I am giving the player an instanced class of UTWeap\_RocketLauncher in an instance of UTGame.

```
PlayerPawn.CreateInventory(class'FobikRocketLauncher',false); // Does not work
PlayerPawn.CreateInventory(class'FobikLinkGun',false); // Works

```

Even if I give the original class (eg. UTWeap\_RocketLauncher) it does not actually show up. However if I do a "GiveWeapons" cheat, I get it just fine. It also works if I had code it into the map. - But UTWeap\_LinkGun works fine either way.

Any ideas? It shows the default ammo amount, and the icon on the HUD.

# Answer
> 2 votes
By the `GiveWeapons` cheat, I'm guessing you mean the `AllWeapons` cheat?

`AllWeapons` gives the player the `UTGameContent.UTWeap_RocketLauncher_Content` weapon, which is a subclass of `UTGame.UTWeap_RocketLauncher` that references all the rocket launcher art assets.

So, you'll need to either make `FobikRocketLauncher` "extend" `UTWeap_RocketLauncher_Content` or copy all the art asset references in `UTWeap_RocketLauncher_Content` into `FobikRocketLauncher`.

And the reason the Link Gun works is that it has no such subclass -- `UTGame.UTWeap_LinkGun` has all the link gun art asset references in it.

---
Tags: udk
---


title: Model won't render in my XNA game

text:
# Question
Title: Model won't render in my XNA game
I am trying to create a simple 3D game but things aren't working out as they should. For instance, the mode will not display. I created a class that does the rendering so I think that is where the problem lies.

P.S I am using models from the MSDN website so I know the models are compatible with XNA.

Code:

```
    class ModelRenderer
    {
        private float aspectratio;
        private Model model;
        private Vector3 camerapos;
        private Vector3 modelpos;
        private Matrix rotationy;
        float radiansy = 0;
        public ModelRenderer(Model m, float AspectRatio, Vector3 initial_pos, Vector3 initialcamerapos)
        {
            model = m;
            if (model.Meshes.Count == 0)
            {
                throw new Exception("Invalid model because it contains zero meshes!");
            }
            modelpos = initial_pos;
            camerapos = initialcamerapos;
            aspectratio = AspectRatio;
            return;
        }
        public Vector3 CameraPosition
        {
            set
            {
                camerapos = value;
            }
            get
            {
                return camerapos;
            }

        }
        public Vector3 ModelPosition
        {
            set
            {
                modelpos = value;
            }
            get
            {
                return modelpos;
            }
        }
        public void RotateY(float radians)
        {
            radiansy += radians;
            rotationy = Matrix.CreateRotationY(radiansy);
        }

        public float AspectRatio
        {
            set
            {
                aspectratio = value;
            }
            get
            {
                return aspectratio;
            }
        }
        public void Draw()
        {

            Matrix world = Matrix.CreateTranslation(modelpos) * rotationy;
            Matrix view = Matrix.CreateLookAt(this.CameraPosition, this.ModelPosition, Vector3.Up);
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1.0f, 10000f);
            model.Draw(world, view, projection);
        }
    }

```

If you need more code just make a comment.

# Answer
Okay I finally solved it. I noticed that I was drawing the model before calling `spriteBatch.End()`. So I drew the model after I called `spriteBatch.End()`.
> 1 votes

# Answer
You're combining your model's rotation & translation backwards when setting your world. Your camera is looking at ModelPosition but ModelPosition has been rotated out of view by rotationy.

edit - More accurately explained, the camera is looking at a point in space called 'ModelPosition'. But the model is not located at 'ModelPosition' because it has been rotated away by rotationy. But when you combine those two matrices the other way around, you rotate 'world' first, it will simply rotate in place at the origin, then you combine the translation to send the rotated matrix right to 'ModelPosition' where the camera is looking for it.

Try:

```
Matrix world = rotationy * Matrix.CreateTranslation(modelpos);

```
> 1 votes

# Answer
Model.Draw is an XNA function so we can rule that out as the problem and more likely it's in one of the matrix arguments you're passing. Try pointing the camera at the origin and centering the model by setting the world matrix to Matrix.Identity. Then you can start from there to see if your model is still rendering or not.

If you still don't see anything, it could be several things, either face culling is in the wrong direction, AspectRatio being zero, or a bad depth setup in your viewport (less likely).
> 0 votes

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


# Question
Title: How to attach turrets to tiles in a tile based game
I am a flash developer, and I am building a Tower Defense game. The world is being built through tiles, and I have gotten that accomplished easily. I have also gotten level changes and enemy spawning down as well. However, I wish the player to be able to spawn turrets, and have those turrets be on specific tiles, based upon where the player placed it. Here is my code:

```
stop();

colOffset = 50;
rowOffset = 50;
guns = [];
placed = true;
dead = 0;
spawned = 0;
level = 1;
interval = 350 / level;
amount = level * 20;
counter = 0;
numCol = 14;
numRow = 10;
tiles = [];
k = 0;
create = false;
tileName = new Array("road","grass","end", "start");
board = new Array(
    new Array(1,1,1,1,3,1,1,1,1,1,2,1,1,1),
    new Array(1,1,1,0,0,1,1,1,1,1,0,1,1,1),
    new Array(1,1,1,0,1,1,1,1,1,1,0,0,1,1),
    new Array(1,1,1,0,0,0,1,1,1,1,1,0,1,1),
    new Array(1,1,1,0,1,0,0,0,1,1,1,0,0,1),
    new Array(1,1,1,0,1,1,1,0,0,1,1,1,0,1),
    new Array(1,1,0,0,1,1,1,1,0,1,1,0,0,1),
    new Array(1,1,0,1,1,1,1,1,0,1,0,0,1,1),
    new Array(1,1,0,0,0,0,0,0,0,1,0,1,1,1),
    new Array(1,1,1,1,1,1,1,1,0,0,0,1,1,1)

    );

buildBoard();
function buildBoard(){
        for ( col = 0; col < numCol; col++){
            for ( row = 0; row < numRow; row++){
                  _root.attachMovie("tile", "tile_" + col + "_" + row, _root.getNextHighestDepth());
                    theTile = eval("tile_" + col + "_" + row);
               theTile._x = (col * 50);
                 theTile._y = (row * 50);

                 theTile.row = row;
                 theTile.col = col;

                 tileType = board[row][col];

                theTile.gotoAndStop(tileName[tileType]);
                tiles.push(theTile);

                }

    }

}

init();

function init(){
    onEnterFrame = function(){
        counter += 1;
    if ( spawned < amount && counter > 50){
    min= _root.attachMovie("minion","minion",_root.getNextHighestDepth());
    min._x = tile_4_0._x + 25;
    min._y = tile_4_0._y + 25;
    min.health = 100;
    choose = Math.round(Math.random());
    if ( choose == 0 ){
    min.waypointX = [ tile_4_1._x +25, tile_3_1._x + 25, tile_3_2._x + 25, tile_3_6._x + 25, tile_2_6._x + 25, tile_2_8._x + 25, tile_8_8._x + 25, tile_8_9._x + 25, tile_10_9._x + 25, tile_10_7._x + 25, tile_11_7._x + 25, tile_11_6._x + 25, tile_12_6._x + 25, tile_12_4._x + 25, tile_11_4._x + 25, tile_11_2._x + 25, tile_10_2._x + 25, tile_10_0._x + 25];
    min.waypointY = [ tile_4_1._y +25, tile_3_1._y + 25, tile_3_2._y + 25, tile_3_6._y + 25, tile_2_6._y + 25, tile_2_8._y + 25, tile_8_8._y + 25, tile_8_9._y + 25, tile_10_9._y + 25, tile_10_7._y + 25, tile_11_7._y + 25, tile_11_6._y + 25, tile_12_6._y + 25, tile_12_4._y + 25, tile_11_4._y + 25, tile_11_2._y + 25, tile_10_2._y + 25, tile_10_0._y + 25];
    }
    else if ( choose == 1 ){
        min.waypointX = [ tile_4_1._x +25, tile_3_1._x + 25, tile_3_2._x + 25, tile_3_3._x + 25, tile_5_3._x + 25, tile_5_4._x + 25, tile_7_4._x + 25, tile_7_5._x + 25, tile_8_5._x + 25, tile_8_8._x + 25, tile_8_9._x + 25, tile_10_9._x + 25, tile_10_7._x + 25, tile_11_7._x + 25, tile_11_6._x + 25, tile_12_6._x + 25, tile_12_4._x + 25, tile_11_4._x + 25, tile_11_2._x + 25, tile_10_2._x + 25, tile_10_0._x + 25 ];
        min.waypointY = [ tile_4_1._y +25, tile_3_1._y + 25, tile_3_2._y + 25, tile_3_3._y + 25, tile_5_3._y + 25, tile_5_4._y + 25, tile_7_4._y + 25, tile_7_5._y + 25, tile_8_5._y + 25, tile_8_8._y + 25, tile_8_9._y + 25, tile_10_9._y + 25, tile_10_7._y + 25, tile_11_7._y + 25, tile_11_6._y + 25, tile_12_6._y + 25, tile_12_4._y + 25, tile_11_4._y + 25, tile_11_2._y + 25, tile_10_2._y + 25, tile_10_0._y + 25 ];

    }
    min.i = 0;

    counter = 0;
    spawned += 1;

    min.onEnterFrame = function(){
        dx = this.waypointX[this.i] - this._x;
        dy = this.waypointY[this.i] - this._y;
        radians = Math.atan2(dy,dx);
        degrees = radians * 180 / Math.PI;
        xspeed = Math.cos(radians);
        yspeed = Math.sin(radians);

        this._x += xspeed;
        this._y += yspeed;

        if( this._x == this.waypointX[this.i] && this._y == this.waypointY[this.i]){
            this.i++;
        }
        if ( this._x == tile_10_0._x + 25 && this._y == tile_10_0._y + 25){
            this.removeMovieClip();
            dead += 1;

        }

    }

    }
    if ( dead >= amount ){

        dead = 0;
        level += 1;
        amount = level * 20;
        spawned = 0;

    }
}
btnM.onRelease = function(){
    create = true;
}

}

game.onEnterFrame = function(){

}

```

It is possible for me however to complete this task, but only once. I am able to make the turret, drag it over to a tile, and have it attach itself to the tile. No problem. The issue is, I cannot do these multiple times. Please Help.

# Answer
> 3 votes
It seems you save the world in a two dimensional array. Why not save the turret positions in another two dim array the same size? When you draw the level you iterate over both arrays and draw the contents of the arrays in the right order, ie the level first and then the turret.

# Answer
> 0 votes
Use bitwise operators and store numbers created using bitwise OR (operator |) in your array. This technique is called "flags".

For example, let's define the following hexadecimal numbers:

* road = 0x0001
* grass = 0x0002
* end = 0x0004
* start = 0x0008
* free = 0x0100
* turret = 0x0200
* snipertower = 0x0400
* howitzer = 0x0800

Then, to create an empty grass tile, you need to store number (grass | free) in your array "board" at the position of the tile. If you want to create road tile with sniper tower, store (road | snipertower) in your array.

If you want to retrieve type of the tile and the object on it, you need to use bitwise AND operator (&). It will give a number if bits of compared numbers match, and 0 if bits of compared numbers don't match. For example, if you want to know, do you have howitzer on your tile, you need to AND the tile (stored in array) with number "howitzer" (0x0800). If you have howitzer on the tile, you'll get a number, and if you don't, you'll get 0. To get do you have grass on your tile, you need to AND the tile with "grass" (0x0002 or 0x02, doesn't matter), and, as I said before, if you have grass on your tile, you'll get some number, and if you don't, you'll get 0.

Code example (written in JavaScript, I don't know ActionScript):

```
var board = new Array(
    new Array(0x0108, 0x0101, 0x0101, 0x0101), //road from start
    new Array(0x0102, 0x0102, 0x0102, 0x0101), //grass with already spawned snipers @ x3
    new Array(0x0101, 0x0101, 0x0101, 0x0101), //just road
    new Array(0x0104, 0x0102, 0x0102, 0x0102)); //end at x1
function getTypeOfBlock(x,y)
{
    var tile = board[y][x]; //optimization
    if (tile & 0x08) //is start?
        return 'start';
    else if (tile & 0x04) //is end?
        return 'end';
    else if (tile & 0x02) //is grass?
        return 'grass';
    else
        return 'road';
}
function buildTurret(x,y)
{
    if (!board[y][x] & 0x0100) //check is the tile free - gives 0 (false) if it's occupied
        return; //don't do anything
    board[y][x] | 0x0200; //build turret at position
}

```

Warnings:

* All byte values must be 1 or power of 2.
* Never OR or AND with number 0, it will give 0.
* You can't have more than 8 hex. digits in 32-bit flag (integer) or 16 digits in 64-bit flag.

---
Tags: tower-defense
---


title: Translating an object along its heading

text:
# Question
Title: Translating an object along its heading
**Solved! I was not applying the transformations in the proper order.**

I am working on a simulation that requires me to have several objects moving around in 3D space (text output of their current position on the grid and heading is fine, I do not need graphics), and I am having some trouble getting objects to move along their relative headings.

I have a basic understanding of vectors and matrices. I am using a vector to represent their position, and I am also using Euler Angles. I can translate one of my entities with a matrix along whatever axis, and I can alter their heading.

For example, if I have an entity at (order is XYZ) 1, 1, 1, with a heading of 0, I can apply a translation matrix to get them to talk to 1, 1, 2 fine. However, if I change their heading to 270, they still walk to 1, 1, 3, instead of 2, 1, 2 as I desire.

I have a feeling that my problem lies in not translating my matrix from world space to object space, but I am not sure how to go about that. How can I do this?

Addition: I am using 3D vectors to represent their current position and their heading (using the three euler angles).

For now, all I want to do is have an entity walk in a square, reporting their current position at each step. So, assuming it starts at 10, 10, 10 I want it to walk as follows:

```
10,10,10 -> 10, 10, 15
10, 10, 15 -> 5, 10, 15
5, 10, 15 -> 5, 10, 10
5, 10, 10 -> 10, 10, 10

```

My 1 Z unit translation matrix is as follows:

```
[1 0 0 0]
[0 1 0 0]
[0 0 1 1]
[0 0 0 1]

```

My rotation matrix is as follows:

```
[0 0 1 0]
[0 1 0 0]
[-1 0 0 0]
[0 0 0 1]

```

# Answer
> 1 votes
If you have a rotation matrix that represents the current rotation of your object, the 3rd row/column represents a vector pointing in the direction the object is facing (heading). So translating the position by a factor of the 3rd row/column will move the position in a direction you are heading (local space forward direction).

```
//assuming row major matrix & Y up system:
position += -3drRowVector * distanceToMove;

```

if you are using a Z up system and/or a column Major matrix, this would need adjustment but the principle is the same.

---
Tags: 3d, matrix
---


# Question
Title: Rotate player to face direction it's moving in 3D space
I'm making a 3D game in XNA4.0. How do I rotate a model to face the direction that the user is pressing. I assume I need to set its look at to the direction being pressed, but can't figure out how to do that.

Cheers.

# Answer
> 1 votes
You can get the world matrix with Matrix.CreateWorld(Position, Direction, Up);

Direction is the forward vector of your model...

http://msdn.microsoft.com/en-us/library/bb975261.aspx

---
Tags: c#, xna-4.0, models
---


# Question
Title: Why are big files better than small files for consoles?
Why do console game developers use large files to store game data instead of small files like on PC? Less streams in memory? Need to access file tree many times? Other reason?

# Answer
> 39 votes
Having a single big file has a few benefits for performance, regardless of platform. Many PC games use big files too.

* You can manually cache the offset of each file within the big file, to avoid the need to read file system directory entries (which can involve multiple seeks per file opened if you miss the cache).
* You get full control of the order of the data within the file, so you can arrange it to minimize the need for slow seeks.
* Data compression is generally more effective on a single big file, than on individual files.

Note that avoiding seeks is very effective at speeding up load times. A typical hard drive might have a 10ms seek time, and a 100MB/s transfer rate. Let's say you need to load 100 shader files with a total size of 1MB. If you have to do a seek for each one it would take one second to load them all. With a single seek you're looking at 20ms to load all of them.

Of course not all consoles have hard drives, and optical drives have even worse seek performance, so those shaders might take 5 or more seconds to load off a DVD when seeking. Also consoles have much less memory for use as cache than a PC does, so they tend to load data more often.

# Answer
> 6 votes
Apart from very good answer given by Adam I would also like to point out some other important factors:

1. *The fewer files you have the easier is the deployment of your application.* This is especially true if you want to deploy your application on mobile platforms, like iOS, Android or Windows Phone. Even if in case of Windows Phone you still can have as many files as you want, since XAP-files, used for deployment, are just a zip archive, it is
2. *Having all your assets in one single files ensures that they are all downloaded/read "in piece"*. Many gamers will excuse you a noticeable delay for downloading assets or unpacking them before the game starts, but they will be non-indulgent as long they face even subtle pauses during the game. Of course you can pre-cache your resources in RAM, but loading them "in piece" is still easier for this purpose than loading them on per-file basis.

---
Tags: optimization, console, file
---


# Question
Title: Using heavyweight ORM implementation for light based games
I'm just about to engulf myself in an MVC-based/Component architecture in C#, using MySQL's connector/Net for the data storage, and probably some NHibernate/FluentNHibernate Object-relational-mapping to map out the data structure. The goal is to build a scalable 2D RPG.

Then I think about it...and I can't help but think this seems a little "heavy weight" for a 2D RPG, especially one which, while I plan to incorporate a lot of functionality and entertaining gameplay, may be ported to something like Windows Phone or Android in the future.

Yet, on the other hand even a 2-Dimensional RPG can become very complicated, and therefore must incorporate a lot of functionality. While this can be accomplished with text/XML/JSON for data storage, is there a better way? *Is* something such as Object-Relational-Mapping useful in such an application?

So, what do you think? Would you say that there is a place for such technologies? I don't know what to think...

# Answer
If you think a 2D RPG is so complicated that you not only need a database, but also a ORM to simplify the interfacing to that database, then I'd suggest you probably haven't yet studied the game mechanics yet. Do bear in mind that we had Zelda in the cartridge era where you might have had 256 bytes of battery-backed RAM to save the current state of the game and only a few KB of RAM to store the state of the game world during runtime. How much more complex than Zelda is your game going to be?

OK, here's another example: Have you played World of Warcraft? This is a pretty complex game with 10 playable classes and hundreds of spells just for the players. Mobs and bosses have their own spells/abilities and many items also have their own effects. And yet underneath everything combat related resolves down to a small number of attributes (health, mana, energy, etc.), cooldown timers and a system of buffs/debuffs. Inventory items are just a type for the item and a quantity. Quests have an identifying number, the player keeps a record of quests completed and their quest log just tracks the id of the quest and optionally a counter of how many kills (or whatever) they've performed towards its completion.

You can store all that stuff in a database of course (and WoW does in fact), but for a single player game there's little enough data that you can afford to store the current state of the game in memory and just serialize it out to a file whenever it needs to be saved. Data that doesn't change can either be coded into the executable itself or deserialized from files as needed. Because structurally it's all very regular it shouldn't take long even if you were writing the serialization/deserialization functions by hand.

Oh, and personally I think ORMs are like 10,000 spoons when all you need is a knife. They either get in the way because the way SQL databases work just isn't a very good fit for the representation of that data as objects, especially when it comes to the update/delete side of things. Or, as I assume the case is with you, you only use them to give persistence to your objects, in which case carrying around the weight if a SQL database, even one as small as SQLite is a waste and the extra complexity of the ORM's API compared to just using plain old objects in memory and saving them to a plain old file isn't justified.
> 12 votes

---
Tags: component-based, databases, xml, mvc
---


title: Simplest way to generate a random path

text:
# Question
Title: Simplest way to generate a random path
What's the simplest way to generate a random "path" for a level in a game? I don't know what search terms I should use to read more. I've looked into maze generation but thats not quite right.

The end result should look like this:

# Answer
> 3 votes
As long as you don't want to go "back", meaning that your path goes only into a single direction (let's assume it is going downwards on your image), you can use the following C# code to easily generate those paths:

```
[Flags]
public enum Direction
{
  Down=1,
  Left=2,
  Right=4
}

public class Path : List<Direction> {}

public Direction GetNewDirection(Direction allowed, Random rnd)
{
  Direction newd;
  int maxd = Enum.GetValues(typeof(Direction)).Length;
  int[] vals = (int[])Enum.GetValues(typeof(Direction));
  do
  {
  var t = rnd.Next(0,maxd);
   newd = (Direction) vals[t];
  }
  while ((newd & allowed) == 0);
  return newd;
}

public Path GenerateRandomPath(int startx, int starty, int endx, int endy, double prob)
{
   Path newpath = new Path();
   Random rnd = new Random();

   int curx = startx; int cury = starty; Direction curd = Direction.Right;
   Direction newd = curd;

   while (!(curx == endx && cury == endy))
   {
     if (rnd.NextDouble() <= prob) // let's generate a turn
     {

       do
       {
        if (curx == endx) newd = GetNewDirection(Direction.Left | Direction.Down, rnd);
        else if (cury == endy) newd = Direction.Right;
        else if (curx <= 0) newd =  GetNewDirection(Direction.Right | Direction.Down, rnd);
        else newd =  GetNewDirection(Direction.Right | Direction.Down | Direction.Left, rnd);

       }
       while ( (newd | curd) == (Direction.Left | Direction.Right)); // excluding going back

       newpath.Add(newd);
       curd = newd;
       switch(newd)
       {
        case Direction.Left:
          curx--;
          break;
        case Direction.Right:
          curx++;
          break;
          case Direction.Down:
          cury++;
          break;
       }
     }

   }

   return newpath;
}

```

You can generate the path by calling it:

```
var mynewpath = GenerateRandomPath(0,0,10,10,0.3);

```

Here the first four parameters are start and end coordinates of your field (determining the dimensions) and the last parameter is the curving probability. Hope it helps...

---
Tags: random
---


title: matrix 4x4 position data

text:
# Question
Title: matrix 4x4 position data
I understand that a 4x4 matrix holds rotation and position data.

The rotation data is held in the 3x3 sub-matrix at the top left of the matrix.

The position data is held in the last column of the matrix.

e.g.

```
glm::vec3 vParentPos(
    mParent[3][0],
    mParent[3][1],
    mParent[3][2]
);

```

My question is - am I accessing the parent matrix correctly in the example above? I know that opengl uses a different matrix ordering that directx, (row order instead of column order or something), so, should the mParent be accessed as follows instead?

```
glm::vec3 vParentPos(
    mParent[0][3],
    mParent[1][3],
    mParent[2][3]
);

```

thanks!

# Answer
> 5 votes
Your first method is the correct one. According to the OpenGL FAQ:

> The translation components occupy the 13th, 14th, and 15th elements of the 16-element matrix

It can also be seen in the glm source code (from `matrix_transform.inl`):

```
inline detail::tmat4x4<T> translate
/*...*/
{
    detail::tmat4x4<T> Result(m);
    Result[3] = m[0] * v[0] + m[1] * v[1] + m[2] * v[2] + m[3];
    return Result;
}

```

You can see only `Result[3]` is affected. This is called column-major storage, but note that OpenGL can be set up in order to use row-major instead (see the OpenGL FAQ on this).

---
Tags: opengl, matrix, glm
---


title: Inaccurate 3D model collision using XNA

text:
# Question
Title: Inaccurate 3D model collision using XNA
I am creating a classic game in 3D that deals with asteriods and you have to shoot them and avoid being hit from them. I can generate the asteroids just fine and the ship can shoot bullets just fine. But the asteroids always hit the ship even if it doesn't look they are even close. I know 2D collision very well but not 3D so can someone please shed some light to my problem? Thanks in advance.

Code for `ModelRenderer`:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace _3D_Asteroids
{
    class ModelRenderer
    {
        private float aspectratio;
        private Model model;
        private Vector3 camerapos;
        private Vector3 modelpos;
        private Matrix rotationy;
        float radiansy = 0;
        private bool isalive;

        public ModelRenderer(Model m, float AspectRatio, Vector3 initial_pos, Vector3 initialcamerapos)
        {
            isalive = true;
            model = m;
            if (model.Meshes.Count == 0)
            {
                throw new Exception("Invalid model because it contains zero meshes!");
            }
            modelpos = initial_pos;
            camerapos = initialcamerapos;
            aspectratio = AspectRatio;
            return;
        }
        public float RadiusOfSphere
        {

            get
            {
                return model.Meshes[0].BoundingSphere.Radius;
            }
        }
        public BoundingBox BoxBounds
        {
            get
            {

                return BoundingBox.CreateFromSphere(model.Meshes[0].BoundingSphere);
            }
        }

        public BoundingSphere SphereBounds
        {

            get
            {

                return model.Meshes[0].BoundingSphere;
            }
        }
        public Vector3 CameraPosition
        {
            set
            {
                camerapos = value;
            }
            get
            {
                return camerapos;
            }

        }
        public bool IsAlive
        {
            get
            {
                return isalive;
            }
        }
        public Vector3 ModelPosition
        {
            set
            {
                modelpos = value;
            }
            get
            {
                return modelpos;
            }
        }
        public void RotateY(float radians)
        {
            radiansy += radians;
            rotationy = Matrix.CreateRotationY(radiansy);
        }
        public Matrix RotationY
        {
            set
            {
                rotationy = value;
            }
            get
            {
                return rotationy;
            }
        }
        public float AspectRatio
        {
            set
            {
                aspectratio = value;
            }
            get
            {
                return aspectratio;
            }
        }
        public void Kill()
        {
            isalive = false;
        }
        public void Draw(float scale)
        {
            Matrix world;
            if (rotationy == new Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
            {
                world = Matrix.CreateScale(scale) * Matrix.CreateTranslation(modelpos);
            }
            else
            {
                world = rotationy * Matrix.CreateScale(scale) * Matrix.CreateTranslation(modelpos);
            }
            Matrix view = Matrix.CreateLookAt(camerapos, Vector3.Zero, Vector3.Up);
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1f, 100000f);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;

                }
                mesh.Draw();
            }
        }
        public void Draw()
        {
            Matrix world;
            if (rotationy == new Matrix(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))
            {
                world = Matrix.CreateTranslation(modelpos);
            }
            else
            {
                world = rotationy * Matrix.CreateTranslation(modelpos);
            }
            Matrix view = Matrix.CreateLookAt(camerapos, Vector3.Zero, Vector3.Up);
            Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f), this.AspectRatio, 1f, 100000f);

            foreach (ModelMesh mesh in model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.World = world;
                    effect.View = view;
                    effect.Projection = projection;

                }
                mesh.Draw();
            }
        }
    }

```

Code for `Game1`:

```
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace _3D_Asteroids
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        int score = 0, lives = 5;
        SpriteBatch spriteBatch;
        GameState gstate = GameState.OnMenuScreen;
        Menu menu = new Menu(Color.Yellow, Color.White);
        SpriteFont font;
        Texture2D background;
        ModelRenderer ship;
        Model b, a;
        List<ModelRenderer> bullets = new List<ModelRenderer>();
        List<ModelRenderer> asteriods = new List<ModelRenderer>();
        float time = 0.0f;
        int framecount = 0;
        SoundEffect effect;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferWidth = 1280;
            graphics.PreferredBackBufferHeight = 796;
            graphics.ApplyChanges();
            Content.RootDirectory = "Content";

        }

        /// <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()
        {
            // TODO: Add your initialization logic here

            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);
            font = Content.Load<SpriteFont>("Fonts\\Lucida Console");
            background = Content.Load<Texture2D>("Textures\\B1_stars");
            Model p1 = Content.Load<Model>("Models\\p1_wedge");
            b = Content.Load<Model>("Models\\pea_proj");
            a = Content.Load<Model>("Models\\asteroid1");
            effect = Content.Load<SoundEffect>("Audio\\tx0_fire1");
            ship = new ModelRenderer(p1, GraphicsDevice.Viewport.AspectRatio, new Vector3(0, 0, 0), new Vector3(0, 0, 9000));
        }

        /// <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)
        {

            KeyboardState state = Keyboard.GetState(PlayerIndex.One);
            switch (gstate)
            {
                case GameState.OnMenuScreen:
                {
                    if (state.IsKeyDown(Keys.Enter))
                    {
                        switch (menu.SelectedChoice)
                        {
                            case MenuChoices.Play:
                            {
                                gstate = GameState.GameStarted;
                                break;
                            }
                            case MenuChoices.Exit:
                            {
                                this.Exit();
                                break;
                            }
                        }

                    }
                    if (state.IsKeyDown(Keys.Down))
                    {
                        menu.MoveSelectedMenuChoiceDown(gameTime);
                    }
                    else if(state.IsKeyDown(Keys.Up))
                    {
                        menu.MoveSelectedMenuChoiceUp(gameTime);
                    }
                    else
                    {
                        menu.KeysReleased();
                    }

                    break;
                }
                case GameState.GameStarted:
                {
                    foreach (ModelRenderer bullet in bullets)
                    {
                        if (bullet.ModelPosition.X < (ship.ModelPosition.X + 4000) && bullet.ModelPosition.Z < (ship.ModelPosition.X + 4000) && bullet.ModelPosition.X > (ship.ModelPosition.Z - 4000) && bullet.ModelPosition.Z > (ship.ModelPosition.Z - 4000))
                        {
                            bullet.ModelPosition += (bullet.RotationY.Forward * 120);
                        }
                        else if (collidedwithasteriod(bullet))
                        {
                            bullet.Kill();
                        }
                        else
                        {

                            bullet.Kill();
                        }

                    }
                    foreach (ModelRenderer asteroid in asteriods)
                    {
                        if (ship.SphereBounds.Intersects(asteroid.BoxBounds))
                        {
                            lives -= 1;
                            asteroid.Kill(); // This always hits no matter where the ship goes.
                        }
                        else
                        {
                            asteroid.ModelPosition -= (asteroid.RotationY.Forward * 50);
                        }
                    }
                    for (int index = 0; index < asteriods.Count; index++)
                    {
                        if (asteriods[index].IsAlive == false)
                        {
                            asteriods.RemoveAt(index);
                        }
                    }
                    for (int index = 0; index < bullets.Count; index++)
                    {
                        if (bullets[index].IsAlive == false)
                        {
                            bullets.RemoveAt(index);
                        }

                    }
                    if (state.IsKeyDown(Keys.Left))
                    {
                        ship.RotateY(0.1f);
                        if (state.IsKeyDown(Keys.Space))
                        {
                            if (time < 17)
                            {
                                firebullet();
                                //effect.Play();
                            }
                        }
                        else
                        {
                            time = 0;
                        }
                    }
                    else if (state.IsKeyDown(Keys.Right))
                    {
                        ship.RotateY(-0.1f);
                        if (state.IsKeyDown(Keys.Space))
                        {
                            if (time < 17)
                            {
                                firebullet();
                                //effect.Play();
                            }
                        }
                        else
                        {
                            time = 0;
                        }
                    }
                    else if (state.IsKeyDown(Keys.Up))
                    {
                        ship.ModelPosition += (ship.RotationY.Forward * 50);
                        if (state.IsKeyDown(Keys.Space))
                        {
                            if (time < 17)
                            {
                                firebullet();
                                //effect.Play();
                            }
                        }
                        else
                        {
                            time = 0;
                        }
                    }
                    else if (state.IsKeyDown(Keys.Space))
                    {
                        time += gameTime.ElapsedGameTime.Milliseconds;
                        if (time < 17)
                        {
                            firebullet();
                            //effect.Play();
                        }
                    }

                    else
                    {
                        time = 0.0f;
                    }
                    if ((framecount % 60) == 0)
                    {
                        createasteroid();
                        framecount = 0;
                    }
                    framecount++;
                    break;
                }
            }

            base.Update(gameTime);
        }
        void firebullet()
        {
            if (bullets.Count < 3)
            {
                ModelRenderer bullet = new ModelRenderer(b, GraphicsDevice.Viewport.AspectRatio, ship.ModelPosition, new Vector3(0, 0, 9000));
                bullet.RotationY = ship.RotationY;
                bullets.Add(bullet);
            }

        }
        void createasteroid()
        {
            if (asteriods.Count < 2)
            {
                Random random = new Random();
                float z = random.Next(-13000, -11000);
                float x = random.Next(-9000, -8000);
                Random random2 = new Random();
                int degrees = random.Next(0, 45);
                float radians = MathHelper.ToRadians(degrees);
                ModelRenderer asteroid = new ModelRenderer(a, GraphicsDevice.Viewport.AspectRatio, new Vector3(x, 0, z), new Vector3(0,0, 9000));
                asteroid.RotateY(radians);
                asteriods.Add(asteroid);
            }
        }
        /// <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.Clear(Color.CornflowerBlue);

            switch (gstate)
            {
                case GameState.OnMenuScreen:
                {
                    spriteBatch.Begin();
                    spriteBatch.Draw(background, Vector2.Zero, Color.White);
                    menu.DrawMenu(ref spriteBatch, font, new Vector2(GraphicsDevice.Viewport.Width / 2, GraphicsDevice.Viewport.Height / 2) - new Vector2(50f), 100f);
                    spriteBatch.End();
                    break;
                }
                case GameState.GameStarted:
                {
                    spriteBatch.Begin();
                    spriteBatch.Draw(background, Vector2.Zero, Color.White);
                    spriteBatch.DrawString(font, "Score: " + score.ToString() + "\nLives: " + lives.ToString(), Vector2.Zero, Color.White);
                    spriteBatch.End();
                    ship.Draw();
                    foreach (ModelRenderer bullet in bullets)
                    {
                        bullet.Draw();
                    }
                    foreach (ModelRenderer asteroid in asteriods)
                    {
                        asteroid.Draw(0.1f);
                    }
                    break;
                }
            }

            base.Draw(gameTime);
        }
        bool collidedwithasteriod(ModelRenderer bullet)
        {
            foreach (ModelRenderer asteroid in asteriods)
            {
                if (bullet.SphereBounds.Intersects(asteroid.BoxBounds))
                {
                    score += 10;
                    asteroid.Kill();
                    return true;
                }
            }
            return false;
        }
    }
}

}

```

# Answer
In your ModelRenderer class, you have a property that gets the mesh's bounding sphere, 'SphereBounds'. But each frame you have to update the object to reflect the current position of the ship or asteroid.

When you load a model into the game, it is usually situated at the world origin. Since you never update the spheres, both the asteroid & ship spheres are still at the world origin registering collision frame after frame.

It isn't enough just to updated a field or variable that reflects a new model position each frame. You also have to update the sphere's center by the same amount each frame. It's like a the beginning of the game, the asteroid & the ship went flying off but left their spheres at the world origin.
> 5 votes

---
Tags: xna, c#, 3d, collision-detection, xna-4.0
---


title: XNA Easy Storage XBOX 360 High Scores

text:
# Question
Title: XNA Easy Storage XBOX 360 High Scores
To followup from a previous query - I need some help with the implementation of easystorage high scores, which is bringing up some errors on the xbox.

I get the prompt screen, a savedevice is selected and a file are all created! However the file remains empty, (I've tried prepopulating but still get errors).

The full portions of the scoring code can be found here: http://pastebin.com/74v897Yt

The current issue in particular is in **LoadHighScores() - "There is an error in XML document (0, 0)." under line data = (HighScoreData)serializer.Deserialize(stream);**

I'm not sure whether this line is correct either: **HighScoreData data = new HighScoreData();**

public static HighScoreData LoadHighScores(string container, string filename) { HighScoreData data = new HighScoreData();

```
        if (Global.SaveDevice.FileExists(container, filename))
                {
                    Global.SaveDevice.Load(container, filename, stream =>
                            {
                                File.Open(Global.fileName_options, FileMode.OpenOrCreate,
                                         FileAccess.Read);
                                try
                            {
                                            // Read the data from the file
                                        XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                                        data = (HighScoreData)serializer.Deserialize(stream);
                            }
                              finally
                             {
                                    // Close the file

                                stream.Close();
                             //   stream.Dispose();

                             }

                            });

                }

        return (data);
    }

```

I call: PromptMe(); when the Start button is pressed at the beginning.

I call: if (Global.SaveDevice.IsReady){entries = LoadHighScores(HighScoresContainer, HighScoresFilename);} during the menu screen to try and display the highscore screen.

I call: SaveHighScore(); when game ends.

I've tried altering the struct code to a class but still no luck. Any help greatly appreciated.

# Answer
You have modified the SaveHighScores from the original source to open *or* create the XML file instead of always overwriting it, which leads to interesting errors when loading.

Say you play your game, save high scores, and the resulting XML file is 100 bytes in length. You then play again and overwrite the high scores, but this time the XML content is only 99 bytes in length (for whatever reason the data is shorter, smaller score, etc). Using open or create the serializer will write out 99 bytes, leaving that 1 last junk byte from the first save at the end of the XML file. This leads to XML parse errors the next time you try and load the scores, just like you are seeing. If you manually inspect the file contents when debugging my guess is you will see junk trailing your XML from this exact scenario.

You will have to delete the file and change the SaveHighScores method back to always create instead of open or create. This will ensure that the old file is always deleted prior to saving, avoiding this issue.
> 1 votes

# Answer
dadoo Games hit the nail right on the head. Your problem is that you may be saving a smaller file into a larger one, causing many problems and headaches as you do so.

I second deleting your current save before you make a new one, so that you always have a fresh file. Doing so will save you many, many headaches and, while not the best method, it is certainly the easiest.

If you're worried about ending up with corrupted saves, you could always make a copy of your current save before deleting it. That way if it gets corrupted in any way, you can fall back on the older one.

So, the long and short of it when saving:

1. (Optional) Back up your current save.
2. Delete current save.
3. Create a new save with your current data.
4. (Optional) Check what saved against what you have on hand, to check if it saved correctly.

Doing so will ensure that the data you save will A.) Never crash due to having junk bytes and B.) You always correctly save your data. A bit of extra work with my optional steps, but it helps in keeping users happier if it corrupts (as they don't lose everything) and it helps prevent corruption by checking if it saved correctly immediately afterwards.
> 1 votes

---
Tags: xna, storage, xbox
---


# Question
Title: Axis-Aligned Bounding Boxes vs Bounding Ellipse
Why is it that most, if not all collision detection algorithms today require each body to have an AABB for the use in the broad phase only?

**It seems to me like simply placing a circle at the body's centroid, and extending the radius to where the circle encompasses the entire body would be optimal.** This would not need to be updated after the body rotates and broad overlap-calculation would be faster to. Correct?

**Bonus:**
Would a bounding ellipse be practical for broad phase calculations also, since it would better represent long, skinny shapes? Or would it require extensive calculations, defeating the purpose of broad-phase?

# Answer
> It seems to me like simply placing a circle at the body's centroid, and extending the radius to where the circle encompasses the entire body would be optimal.

Would be optimal for what? It all depends on what you're trying to accomplish.

The bounding sphere will generally have a larger volume than the axis-aligned bounding box. Which means that more things will touch each other. So, while the bounding sphere is faster to test against other bounding spheres, you'll get more positive results.

Which means if you're doing this for frustum culling, for example, then you'll have more objects actually on display than you otherwise might.

It's possible that one might be faster in some specific cases than the other, depending on what your fine-grained collision detection scheme is and what your world is like. And it depends on what other schemes you have in play (binning of objects, etc). But it's *certainly* not something you can say is true in all cases.

> Would a bounding ellipse be practical for broad phase calculations also, since it would better represent long, skinny shapes?

No. Ellipses require far too many computations for intersection tests. You may as well use an AABB.
> 2 votes

# Answer
Answering your questions in order:

1. AABBs are used an accurate, low cost collision test which fits most models without a high set up cost.
2. Whilst it can not be denied Bounding spheres can be a great pre-cursor to further collision tests, they are by no means the holy grail. In almost all cases except for a mostly spherical object, the bounding sphere will almost always cover more area (ie sub-optimal) than a bounding box.

Some good reading material: http://www.gamedev.net/topic/216295-bounding-box-or-bounding-sphere/

For tight bounding spheres, have a look at: http://en.wikipedia.org/wiki/Smallest\_circle\_problem
> 1 votes

---
Tags: 2d, collision-detection, physics
---


# Question
Title: Frame Buffer Objects vs calling TexCoord2f?
I'm learning the basics of OpenGL with lwjgl currently, and following a guide I've got textured quads that can move around a scene.

I've been reading about Frame Buffer Objects, and I'm not really clear on their purpose and their benefit.

My understanding is that I'll create a FBO with the texture I'd like, load the FBO, draw a quad, then unload the FBO. What would the technique I'm currently doing for texture management be called, and how does it differ from using FBOs?

What are the benefits to using FBOs? How does it fit into the grand rendering scheme of things?

# Answer
FBOs aren't useful to simply apply static textures to a model. For static textures, you would initialize them using `glTexImage2D` during startup and then use the textures while rendering your model. This is presumably what you're doing now.

Framebuffer objects are used when you want to have a texture that is not just a static image loaded from a file, but something generated dynamically by the GPU. They allow you to capture an image rendered by the GPU, and then later use that image as a texture for further rendering. This functionality is also called "render-to-texture" and is commonly used for advanced rendering techniques.

One example of using FBOs would be for rendering the reflection in a body of water such as a lake or ocean. You'd create a texture object to hold the reflected image and attach it to an FBO; then each frame, before rendering the main scene, you'd bind the FBO and render the reflection; all the rendering output will go to the texture instead of the screen. Then you can unbind the FBO and render the scene as usual, using the texture in the water shader to produce the reflection. This way the reflection will update dynamically as the camera and other objects move around.

Other examples where you'd use FBOs include shadow mapping, post-processing, deferred shading, and many other advanced rendering techniques. You can read all about these (and the details of the reflection technique I just described) on the Web. FBOs are a key part of advanced OpenGL usage, so they're well worth spending some time with - but probably not until you've gotten a grasp on more basic OpenGL usage first.
> 3 votes

---
Tags: opengl, lwjgl
---


# Question
Title: Checking validation of entries in a Sudoku game written in Java
I'm building a simple Sudoku game in Java which is based on a matrix (an array\[9\]\[9\]) and I need to validate my board state according to these rules:

* all rows have 1-9 digits
* all columns have 1-9 digits.
* each 3x3 grid has 1-9 digits.

This function should be efficient as possible for example if first case is not valid I believe there's no need to check other cases and so on (correct me if I'm wrong).

When I tried doing this I had a conflict. Should I do one large for loop and inside check columns and row (in two other loops) or should I do each test separately and verify every case by it's own?

(Please don't suggest too advanced solutions with other class/object helpers.)

This is what I thought about:

Main validating function (which I want pretty clean):

```
public boolean testBoard() {

        boolean isBoardValid = false;

        if (validRows())
        {
            if (validColumns())
            {
                if (validCube())
                {
                    isBoardValid = true;
                }
            }
        }
        return isBoardValid;
}

```

Different methods to do the specific test such as:

```
private boolean validRows() {
        int rowsDigitsCount = 0;

        for (int num = 1; num <= 9; num++) {
            boolean foundDigit = false;

            for (int row = 0; (row < board.length) && (!foundDigit); row++) {
                for (int col = 0; col < board[row].length; col++) {
                    if (board[row][col] == num) {
                        rowsDigitsCount++;
                        foundDigit = true;
                        break;
                    }
                }
            }
        }

        return rowsDigitsCount == 9 ? true : false;
    }

```

I don't know if I should keep doing tests separately because it looks like I'm duplicating my code.

# Answer
For purposes of this kind of checking, represent the content of each cell as a bitmask with only one of the nine possible bits set. Then OR ('`|`', not '`||`') together the contents of each row/column/block. If the result has all 9 bits set, you have a winner.

If you really don't want any other data structures, compute the bitmask on the fly as

```
1 << digit

```

where digit is between 0 and 9.

A winner is equal to 0x3fe, or 1022.
> 4 votes

# Answer
It is best done with propositional logic. You make the 9x9 grid a 9x9x9 boolean cube, where each element in the third dimension is simple a boolean corresponding to each possible digit.

So if '1' was in a square, the bool corresponding to 1 for that square would be true, while the others would be false.

Representing Sudoku in this way means you can easily verify a solution as being valid/invalid with propositional logic. And you will also be well placed to *solve* sudoku, instead of simply verifying a solution as correct/incorrect.

See this paper for more info: http://my-svn.assembla.com/svn/disenosudoku/docs/a-sat-based-sudoku-solver.pdf
> 1 votes

# Answer
I've written similar, but in C#. Without exact syntax for your java, I too basically have arrays... both 9x9 and 16x16 solutions. I created one function to return a string of all "Solved" values in a given row, another for "Solved" in a given column, and another for all in a given "Block" (3x3 or 4x4).

I would then have a master string "123456789" (or 0-9A-F for 4x4) and strip out every character returned from the cross-hairs. If only one number left, solved.

Sorry, I mis-understood... you are looking for a VALIDATION OF A COMPLETED BOARD... not trying to SOLVE a board. You were on a good approach, but here's a pseudo/code as I don't do Java, but C#/C++ are close, so you'll have to improvise...

```
private boolean validRows()
{
   string baselineChars;
   for (int row = 0; row < board.length); row++)
   {
      // prepare simple list of numbers we KNOW we should have
      baselineChars = "123456789";

      // now check all columns on the given row...
      for (int col = 0; col < board.length; col++)
         // IMPROVISE HERE...
         if( theValue at board[row][col] Still Exists in BaselineChars string)
            // strip so it will fail if the number already accounted for next round
            baselineChars = StripOutTheNumberYouJustFound;
         else
            // number no longer exists via already found, get out completely.
            return false;

    }
    // if still here after all 9 rows, we're good
    return true;
}

```

Likewise for column, but swap it col/row for loops.

For checking the "blocks" (3x3), it will be in a similar format

```
private boolean validBlocks()
{
   int squareSize = 3;
   string baselineChars;
   // BR = BlockRow, BC = BlockCol
   for (int BR = 0; BR < squareSize; BR++)
      for( int BC = 0; BC < squareSize); BC++ )
      {
         baselineChars = "123456789";
         // IBR = InnerBlockRow, IBC = InnerBlockCol
         for( IBR = 0; IBR < squareSize); IBR++ )
            for( IBC = 0; IBC < squareSize); IBC++ )
                // IMPROVISE HERE...
                if( the value at...
                    board[BR * squareSize + IBR][BC * squareSize + IBC]
                    is found in baselineChars )
                   // Strip it like that of rows and cols
                   baselineChars = StripOutTheNumberYouJustFound;
                else
                   // number no longer exists via already found, get out completely.
                   return false;

      }
      // if still here after all 9 rows, we're good
      return true;
}

```
> 1 votes

# Answer
If you read Dr Pete Norvig's ***excellent*** sudoku solver you can understand how to solve sudoku whilst at the same time seeing how the experts do their validation, testing and reasoning.

Mentioning sudoku and unit testing in the same sentence is a classic ROTFL for those of us who fetched the popcorn when this happened: http://devgrind.com/2007/04/25/how-to-not-solve-a-sudoku/

More good reading on the TDD for design tangent I'm touching on is the more recent ***excellent*** talk by Rick Hickey about complexity.
> 1 votes

# Answer
Take the elements of each row, each column, and each subbox and put them in a set or dictionary. Then verify that each set/dictionary has exactly nine elements (meaning that it has no duplicates).
> 0 votes

---
Tags: java, validation
---


# Question
Title: What is the primary use of Vertex Buffer Objects?
From what I've read, it seems VBOs are purely for performance.

I'm working on a very rudimentary learning project in lwjgl and I'm just trying to figure out what more advanced features of the library I should be delving into, and what their use is.

My understanding is that VBOs allow a person to keep vertexes in VRAM while they aren't currently being drawn in a scene. In my case, I'm just drawing quads and performance probably isn't a concern at all, but I'm trying to piece together what's happening under the hood. If I'm drawing quads directly, I'm drawing from the CPU memory, correct? Also, if I'm not doing any checks for visibility, does that mean I'm rendering absolutely everything in the "scene", regardless of whether its in view? Are VBOs a way to store objects and only render what's needed?

# Answer
> 10 votes
**Pedantic note:** There is no such thing in OpenGL as a "Vertex Buffer Object." There are simply Buffer Objects. A buffer object is simply a linear array of GPU memory that you can allocate, fill with data, read from, and use in a variety of ways. One of the things you can *do* with buffer objects is store vertex data in them and use them as source arrays for rendering. But they have quite a few other uses as well.

Buffer objects are not a way to avoid frustum culling or other scene-graph-style constructs. When used for vertex data, buffer objects simply store vertex data. Without them, your `glDrawElements/Arrays/etc` calls will pull data from arrays stored in CPU member buffers. When using buffer objects for rendering, the arrays are pulled instead from buffer object contents.

Where your vertex data comes from is the *only difference* between rendering with buffer objects and rendering without them. So no frustum culling. No scene-graph management. Nothing. It's just about where your vertex data is stored.

# Answer
> 2 votes
OpenGL array buffers (= what we call VBO) serve one single purpose: **Keep your geometry data inside GPU memory not client memory, so that you won't need to re-send it every frame.**

As simple as that :-)

---
Tags: opengl, java, lwjgl
---


title: AS3: limit objects to stage width?

text:
# Question
Title: AS3: limit objects to stage width?
I want to limit the creation of objects acording to the stage width.

My method is the following:

```
for (var i:int = 0; i<7; i++){

```

If I put something like this, it won't work

```
for (var i:int = 0; i<(stage.width); i++){

```

What I'm doing wrong?

**Full code:**

```
    [SWF(width = 350, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// make a heavy circle
sim.addCircle({x:3, y:3, radius:0.4, density:1});
// create a few platforms

// make 26 dominoes
for (var i:int = 0; i<7; i++){
//End
     sim.addCircle({x:1 + i * 1.5, y:18, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:17, radius:0.1, density:0});
     sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0});

//Mid end

      sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0});

}
sim.start();
sim.mouseDrag();

```

# Answer
The property you want to use is `stage.stageWidth`.

**Update:** If your code throws an error, it could be that `stage` is not available **or** not *yet* available. In Flash CS5, the stage property should always be available. In "pure" Actionscript or Flex projects (using Flex Builder or FlashDevelop), you should make sure that your class inherits from a flash class that has the `stage` property and you'll also have to wait for `stage` to be available. A save way to make sure `stage` is available, is listening to the `ADDED_TO_STAGE` event. Eg. something like this:

```
public function Constructor()
{
    super();
    addEventListener(Event.ADDED_TO_STAGE, onInit)
}

private function onInit(evt:Event):void
{
    removeEventListener(evt.type, onInit);

    // stage should be accessible here. Initialize your code here!
}

```
> 2 votes

---
Tags: actionscript-3, box2d
---


title: AS3: StageWidth for BOX2D?

text:
# Question
Title: AS3: StageWidth for BOX2D?
I know BOX2D uses meters, and AS3 uses pixels.

I'm trying to create objects which are limited to the stageWidth.

If I do this variable:

```
for (var i:int = 0; i<(stage.stageWidth); i++){...}

```

The animation will freeze, and this output appears:

```
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Box2D.Collision::b2BroadPhase/CreateProxy()
at Box2D.Collision.Shapes::b2Shape/CreateProxy()
at Box2D.Dynamics::b2Body/CreateShape()
at com.actionsnippet.qbox.objects::CircleObject/build()
at com.actionsnippet.qbox::QuickObject/init()
at com.actionsnippet.qbox::QuickObject()
at com.actionsnippet.qbox.objects::CircleObject()
at com.actionsnippet.qbox::QuickBox2D/create()
at com.actionsnippet.qbox::QuickBox2D/addCircle()
at BOX2D_Test_Tutorial_fla::MainTimeline/frame1()

```

Does anyone know how to fix this?

Full Code:

```
    [SWF(width = 350, height = 600, frameRate = 60)]
import com.actionsnippet.qbox.*;
var sim:QuickBox2D = new QuickBox2D(this);
sim.createStageWalls();
// make a heavy circle
sim.addCircle({x:3, y:3, radius:0.4, density:1});
// create a few platforms

// make pins
for (var i:int = 0; i<(stage.stageWidth); i++){
//End
     sim.addCircle({x:1 + i * 1.5, y:18, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:17, radius:0.1, density:0});
     sim.addCircle({x:1 + i * 1.5, y:16, radius:0.1, density:0});
     sim.addCircle({x:2 + i * 1.5, y:15, radius:0.1, density:0});

//Mid end

      sim.addCircle({x:0 + i * 2, y:14, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:13, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:12, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:11, radius:0.1, density:0});
      sim.addCircle({x:0 + i * 2, y:10, radius:0.1, density:0});

}
sim.start();
sim.mouseDrag();

```

# Answer
> 0 votes
You are surpassing the limit of bodies in Box2D, at 3150 circles I can't imagine why you would need so many, is there a logic error or will you divide this number by something?

Edit:

If you want to evenly space objects across the stage you can do this:

```
var meterWidth = stage.stageWidth/meter;// meter can be 30 or whatever your scale is

// Adds the distance between each object to i on each iteration and stops at the width
for (var i = 0; i < meterWidth; i += meterWidth/numberOfObjects)
{
    sim.addCircle({x:i, y:18, radius:0.1, density:0});// i is the x coordinate
}

```

Edit:

For anyone interested, the maximum body count in Box2D can be changed in b2Settings.

---
Tags: actionscript-3, box2d
---


# Question
Title: Display crosshair that is diplaying where the ship is aiming at
I am creating a 3D asteroids game. I got the bullets, asteroids, and ship all done. They work perfectly. Now I want a crosshair to display where the ship is pointing at. The crosshair will be a 2D sprite.

# Answer
> 1 votes
You could fire an invisible infinite speed bullet from you ship during every frame, and if it hits an asteroid (or the edge of the viewport/frustum), draw your cross-hair sprite at that point. The advantage of this is that you can use your already existing bullet firing, collision detection, and hit effect code, so you should have practically zero overhead effort.

If you use this approach and your collision detection code cannot handle overshooting bullets, you either have to adjust that code or use a special method to handle that bullet, although you should probably do the former.

You didn't specify, but if by "3D game" you mean a first person perspective, then you can simply draw that sprite in the middle of the screen or at the position of your mouse pointer.

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


title: View Frustum Alternative

text:
# Question
Title: View Frustum Alternative
I am working on a simulation project that requires me to have entities walking around in a 3D world. I have all that working, matrix transformations, etc. I'm at the point where I need what is essentially a view frustum, so I can give each entity a visible area. However, when looking over the calculations required to do it, it seems like a perspective frustum is only required to be able to project it onto a 2D screen. Is there another, easier to code solution, that would function better, such as an orthogonal perspective? Could I just define a shape mathematically and test wether the coordinates of the objects are inside or out? I am not really a 3D coder (and I am doing this all from scratch, not using an engine or anything), so I would like the simplest solution possible for my needs.

Thank you!

# Answer
> 3 votes
You could use a cone instead of a frustum; it would be a simpler point-in-volume check. You'd construct the vector from the entity's eye point (the apex of the cone) to the point to be tested, then normalize it and dot-product with the entity's view direction (another normalized vector). Then test if the dot product is \> cos(0.5 * the entity's FOV). That cos factor can be precomputed and stored if the cone widths don't change.

This doesn't give you the ability to have separate vertical and horizontal FOVs, though, in case you care about that.

As for seeing through walls, that is a harder problem. In general, you'll need to do a raycast from the entity's eye point to the point being tested and see if it hits any scene geometry along the way; storing the geometry in a BSP tree can be helpful for speeding this up. Tracing rays against a scene is a large topic that you can find a lot of information about on the Web.

# Answer
> 0 votes
If you combine a view matrix & a projection matrix (which you can do for each entity, like if it were a FPS), the component values in the resulting matrix can be used to create 6 planes (a vector4 representing each plane) representing the boundaries of the frustum. Then these planes can be used to test if other objects are on one side of the plane or not. When an object is behind all six planes, it is inside that frustum.

If you use Xna, this comes built in. If not, reflect Xna to see the principle/code behind and port it to whatever language/platform you're using.

---
Tags: 3d, frustum
---


# Question
Title: Deserialize inherited classes into the same list in XNA
I am writing a Gui for a game (for what else ...). Therefor I wrote a class GuiElement which has some serializeable fields. From this class I deflect a Class "Button" which has one serializeable field more. Furthermore, I have a Class GuiWindow, which is as well deflected from "GuiElement". An Object of this Class has a Field "HandledElements" of the type "List". To know the layout of the Menues, I use XML-Files, which look like that (for example):

```
<?xml version="1.0" encoding="utf-8" ?>
<XnaContent xmlns:Generic="System.Collections.Generic">
 <Asset Type="System.Collections.Generic.List[GUI.GuiWindow]">
  <Item>
   <Position>0 0</Position>
   <AlternativeImagePath></AlternativeImagePath>
   <IsActive>true</IsActive>
   <Name>MainMenu</Name>
   <HandledElements>
    <Item>
      <Position>100 100</Position>
      <AlternativeImagePath></AlternativeImagePath>
      <IsActive>true</IsActive>
      <Name>Optionen</Name>
      <Caption>Optionen</Caption>
    </Item>
   </HandledElements>
 </Item>

  <Item>
   <Position>0 0</Position>
   <AlternativeImagePath></AlternativeImagePath>
   <IsActive>false</IsActive>
   <Name>Options</Name>
   <HandledElements>
   </HandledElements>
  </Item>
 </Asset>
</XnaContent>

```

As you can see, the first window has in its "HandledElements" List an Item with the Field . This is a field which only a Button has. The Problem is now: I can't deserialize this XML file, because GuiElement does not have this Field, it only has the few fields above. I thought it would know automatically which Class to use,but it doesn't. Do I really have to give my windows a list for each child class of GuiElement? Or can I do another workaround?

# Answer
Using the technique described in this answer here you can easily discover the solution:

Simply put a `Type="GUI.Whatever"` as an attribute on each `<Item>` element.
> 3 votes

---
Tags: xna, c#, xml, serialization
---


# Question
Title: What is a good way to test demand for a new game platform?
I'm working on a game platform that turns your iPhone, android or iPad into a steering wheel, for racing games (like need for speed and dirt 3) and flight simulators for example.

I'd love to figure out smart ways to figure out whether gamers would like something like this.

I originally asked this question over on the gaming SE and it was for getflypad.com. A lot of the tech is built and most of it is doable - the question here is how to *test demand* and know whether gamers actually want this.

# Answer
Well, your total potential market is a cross section of:

* Racing Game Fans (with current PC racing games)
* iPad+iPod Owners

If I was you, I'd try and dig up some sales figures from some modern or recent racing games. Those might be hard to come by, but you might be able to scrape some data from the number of active TrackMania 2 players (or similar such online games). Actually, "active" players might be a more realistic market for your product than mere owners of racing games.

You also need to keep in mind you're competing in the racing wheel market, which may generally have better responsiveness and offer a better overall experience for the player (it's car racing after all, not hand waving). But for a couple dollars as an iOS app, you may still be able to drive a decent amount of impulse "lets give this a try" purchases.

As for ascertaining actual demand for something, you Google it. Look for people asking for the exact app you're asking for "let me play my PC racing games with my iPad as the controller". Now yes, you stand a very good chance of finding nothing, which may actually mean there is no demand. However, that's not to say nobody will want it once they know it exists. It could be something they don't yet know they want.
> 2 votes

# Answer
You could create a website that advertises your theoretical product and pay for some advertising on Google, etc. to generate some traffic to it. Explain that the product is coming soon, and provide a way to sign up for a newsletter.

You can watch trends in traffic (repeat hits, how many first time visitors stick around to read your content, etc.), which should give you some idea of whether there is any interest. Your newsletter subscriptions will not only give you an idea of what kind of interest there is, but also help you have a stronger release.

Rob Walling talks a bit more about this in his book, Start Small, Stay Small.
> 0 votes

---
Tags: control, playtesting
---


# Question
Title: Problems in exporting terrain from autodesk 3ds
i am trying to make small counter strike sort of game and for the terrain part i have exported the terrain in 3ds format from Autodesk 3ds-max and imported the same in opengl using lib3ds. Its working fine but with few problems:

* The terrain is mainly made up of some cubical boxes with texture on them and placed on a big flat surface with boundary wall. In opengl i have enabled anti aliasing but still there is too much aliasing on the boundaries (visible when rotating the camera).
* I have tiled the floor with some image but in opengl it is just the single image stretched over the complete surface.
* I have exported animated model (Skelton+mesh+material+animation) from 3ds and used cal3d library for reading the same. Model has a gun also which is not appearing in opengl and it too has too much of aliasing problem.

I have googled around but couldn't find any relevant solutions.

Thanks in advance

# Answer
For your antialiasing problem, could it be your hardware settings?

For your tiled texture, instead of using tiling options in max, use the uvw unwrap modifier and scale that face to cover multiple tiles in the Edit box.

As for the last part, you need to provide more information about the problem, screenshots, exporter options, and anything else.
> 1 votes

---
Tags: opengl, animation, models, 3dsmax, antialiasing
---


title: 3D models overlapping each other

text:
# Question
Title: 3D models overlapping each other
I have a problem at the moment when I draw some models to teach me more about 3D game programming. The models at the moment overlaps each other from some angles witch makes sense since the game at the moment draws from left to right, line after line.

However my question is: Is there any easy escape from this issue or is there any way that you could draw the in-game world from the players position?

I would really appreciate if someone could give me some answers on this.

# Answer
> 4 votes
Without seeing any screenshots, I'm pretty sure you have depth testing disabled, so the last drawn model is the one that appears on top of the others, even if it is the furthest in the scene. To fix this, set `GraphicsDevice.DepthStencilState = DepthStencilState.Default` before drawing your models.

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


# Question
Title: Could I be going crazy with Event Handlers? Am I going the "wrong way" with my design?
I guess I've decided that I really like event handlers. I may be suffering a bit from analysis paralysis, but I'm concerned about making my design unwieldy or running into some other unforeseen consequence to my design decisions.

My game engine currently does basic sprite-based rendering with a panning overhead camera. My design looks a bit like this:

# SceneHandler

Contains a list of classes that implement the SceneListener interface (currently only Sprites). Calls render() once per tick, and sends onCameraUpdate(); messages to SceneListeners.

# InputHandler

Polls the input once per tick, and sends a simple "onKeyPressed" message to InputListeners. I have a Camera InputListener which holds a SceneHandler instance and triggers updateCamera(); events based on what the input is.

# AgentHandler

Calls default actions on any Agents (AI) once per tick, and will check a stack for any new events that are registered, dispatching them to specific Agents as needed.

So I have basic sprite objects that can move around a scene and use rudimentary steering behaviors to travel. I've gotten onto collision detection, and this is where I'm not sure the direction my design is going is good. Is it a good practice to have many, small event handlers? I imagine going the way I am that I'd have to implement some kind of CollisionHandler.

Would I be better off with a more consolidated EntityHandler which handles AI, collision updates, and other entity interactions in one class? Or will I be fine just implementing many different event handling subsystems which pass messages to each other based on what kind of event it is? Should I write an EntityHandler which is simply responsible for coordinating all these sub event handlers?

I realize in some cases, such as my InputHandler and SceneHandler, those are very specific types of events. A large portion of my game code won't care about input, and a large portion won't care about updates that happen purely in the rendering of the scene. Thus I feel my isolation of those systems is justified. However, I'm asking this question specifically approaching game logic type events.

# Answer
Event based design mostly involves implementing the **Reactor** design pattern.

Before starting to design components you should give a look to the limitations of such pattern (you may find a plenty information about this).

The first and foremost of the problems is that the handlers have to **return quickly**, as every one that did some serius work on GUI based frameworks and javascript based applications knows well.

When you develop every application with a *decent complexity* you will, sooner or later, face some **handler** that does a complex job **that requires time**.

In these cases you can distinguish two situations (not necessarily mutually exclusive):

Complex **event-related** responsibilities and complex **event-unrelated** responsibilities.

**Complex event-related responsibilities:**

In the first case you **merged too many responsibilities into a single component handler**: too much actions are taken in response to an event or there are running synchronizations for example.

In this case the solution is to **split the handler into different handlers** (in different objects if necessary) and let an handle to fire events instead of call directly the handling code. This will let you to allow an higher priority event to be managed before since your primary handler has returned after appending events to the event queue.

Another solution is to **let an external entity to fire events** and let the others to subscribe if interested in (the timing event is the most trivial example you can generalize).

**Complex event-unrelated responsibilities:**

The second case happens when there is an **intrinsic complexity** in the action to take after an event: you have to compute a fibonacci number after an event for example.

Here the **Reactor pattern basically fails**, worth little to split the fibonacci generation algorithm into little chunks that fire events upon termination in order to trigger the next step.

Here the solution is to mix a **threaded design to the reactor**, the good news is that if the complexity is intrinsic (so you are reading the right section) it is very likely that it is possible to start and independent thread that does the work and that needs to know little or nothing about the rest of the Reactor-related components.

To handle this kind of situations, I found useful to adopt a **job queue** over a **flexible thread pool**.

When an handler needs to start a long action, it **encapsulates** that action **into a job unit** to be put into the job queue. This encapsulated action needs to have a **mean to trigger events** into the reactor thread. The job queue manager may run into its own thread or in the reactor thread and react to the "newJob" event.

The job queue manager does the follow:

* it allocates a job unit to a thread from the flexible thread pool using its shedule algorithm if the pool is able to provide one thread ( there is a free thread or a new thread creation is allowed)
* listen the pool itself to see if a job unit finished so a thread can be recovered to execute one more pending unit, if any.

Using the event firing mechanism a job unit may trigger events to notify the completition, the update state, warnings, errors or whenever is needed. The flexible thread pool ensures a good use of resources while avoids dead thread to hang the whole system; the job queue allows you to choose which kind of priority assign to different kind of actions since you know that they will requre a consistent amount of computational resource.
> 22 votes

# Answer
In most situations using events over other options can often improve speed and decentralization. I think if you can use lots of events you should go for it.
> 1 votes

---
Tags: 2d, architecture, events
---


# Question
Title: What should I keep in mind when making 2D games for multiple resolutions?
I'm making a 2D (Android) game. Android devices vary quite a lot in screen resolution; what do I need to keep in mind when making my game?

* Do I need to keep big versions of all images and scale down depending on the resolution (doesn't that waste space)?
* Do bitmap fonts scale well or do I need to use something else?
* Anything else I'm forgetting?

# Answer
> 26 votes
I'm the developer of an extremely portable mobile game that runs on everything from PCs, to TVs, to even the Black & White Amazon Kindle (Smiles HD - http://smileshd.com \- More devices and platforms than you see there).

The best way I've found to support any device is to pick a base resolution, then scale up (or down) to the current screen. If you want to cheat, you can fit to the new screen resolution, but ideally you should keep the same aspect ratio. Fitting a game made for a 4:3 display looks hideous on a 16:9, but fitting a 16:9 on to a 16:10, nobody might notice. You'll note I refer to screens by aspect ratio and not the dimensions, which is especially helpful way to think in this era of totally random LCD sizes.

To make artwork that suits any screen while maintaining the aspect ratio, create backgrounds that are larger than most typical screens will ever see. This is similar to the concept title-safe areas with Television.

http://en.wikipedia.org/wiki/Safe\_area

Generated backgrounds work really great for this. Tiled patterns, checkerboards, fractal shapes, etc. You just need generate a little bit more to fit a new screen.

Also, creating static images larger than what your typical user will see. Wider than widescreen (16:9), and squarer than standard def (4:3). Again back to title-safe areas, fit your important information in to a safe area, scale up a bit so your safe area touches one of the edges of your screen, and leave some run-off for devices that are just a little bigger.

A variation I'm working with today is creating "title safe" 3D objects. Since they're 3D, composed entirely of vertices, making them larger than the screen takes up practically no more memory than if they were to fit. Just as the density of pixels goes up, you may want some higher detail textures available. If not, oh well, it's a little blurry.

User interfaces, I like to fit the main UI within a perfect square in the middle of the screen. The corners and the middle edges also make really good places to put things; You should calculate their coordinates as such (relative the corner or the middle edges).

http://www.smileshd.com/press/iPad/png/UI01.png

If you really want to get fancy, you can support both Tall and Wide orientations. Some devices do report their screen resolutions as taller than wide (iPhone for example), so you may have to do something for those devices anyways, even if it's simply rotating all of your coordinates.

A User Interface that adapts to both tall and wide screens can be a pretty impressive sight.

Wide: http://www.smileshd.com/press/iPad/jpg/SmilesHD01.jpg

Tall: http://www.smileshd.com/press/iPad/jpg/SmilesHD02.jpg

On the plus side, design wise, you only really need to consider Tall and Wide, instead of Portrait+Reverse Portrait+Landscape+Reverse Landscape. When you pick the positions of things on the screen, consider having a more appropriate alternative position for the other orientation.

> Do I need to keep big versions of all images and scale down depending on the resolution (doesn't that waste space)?

Well you can either "waste space" and support a wider variety of devices with a single build, or "waste your time" and have to make MANY builds and resize artwork for many devices.

Best case, you should create your artwork at higher resolution than the final size would be on a 1080p Television (1920x1080). 2048x2048 should be a common size in your source artwork. Either that, or consider using Vector artwork tools like Flash and Adobe Illustrator.

I'd strongly recommend creating an automated process for resizing your artwork. Most mobile devices today, tablets included, do not exceed resolutions greater than 720p (1280x720)... at least, not by much. Come next year though, we just don't know if that will be true anymore (iPad 3?).

Either way, for best performance, you should get used to the idea of source artwork and source assets. You can then perform a process that optimizes the data for whatever device(s) you are targeting.

> Do bitmap fonts scale well or do I need to use something else?

They scale well if you're using a good filtering. If you're making your 2D game with 3D hardware (OpenGL ES), then I must strongly recommend that you use Linear Filtering combined with MipMapping (i.e. a set of scaled down images). You can get perceptively perfect results with this, and it's often faster to use mipmaps than not to.

http://en.wikipedia.org/wiki/Mipmapping

Anyways, I hope that helps. Best of luck with your project.

# Answer
> 2 votes
In general, every texture you make should be either 256x256, or 512x512. If you are also targeting pads (Galaxy Tab, Honecomb, iPad), then 512x512 will not fill the entire screen, so you might want to include larger versions of those art assets which need to fill the screen. Apple includes a native "@2x" image suffix to handle this case.

The simple solution, which I've used myself, is to simply create your game for a 320x480 screen (iPhone). Let this double naturally for iPhone 2 (640 x 960), and then the only other case you really have to handle differently is the fact that some Android devices have a taller screen - so just put a buffer on the top and bottom (in portrait mode).

In short - build your game for one neutral screen size, and then cover the exceptions, based upon

# Answer
> 1 votes
It's best to keep the working copies of any assets you have. If you're developing an image in photoshop, for example, save the original psd file. Any time you need a different res image, you can open it up and export the new image with minimal quality loss.

Rather than build for one screen size or another, I would *strongly* suggest you build for a variety from the beginning. You're not only talking about different pixel densities, you're also talking about different aspect ratios. 16x9 and 16x10 can yield a very different visual experience. So make sure you test new changes on a variety of different screen shapes and sizes.

In my experience, bitmap fonts do not scale well at all. It may depend a lot on the style of font you use, but in general, resampling the font bitmap yields very poor results. Bitmap fonts work best when your texture sampling is not set to multisampling (GL\_NEAREST, and without mipmaps) and it is rendered such that it maps pixel-for-pixel to the screen. You may want to consider using a series of renderings of the same font at different sizes and ensure that the font always appears at scale == 1 in your game; this will allow you some limited options when choosing a font size to use in a particular scenario.

# Answer
> 1 votes
Android provides some help for this...

You can specify "alternate resources" for items like your graphics.
Take a look at "Providing Alternate Resources" section at this link: http://developer.android.com/guide/topics/resources/providing-resources.html You should be able to find examples in the SDK examples or via Google.

Also, Google provides an Android Emulator that you get with the SDK. You can define several virtual devices with different configurations to test your code. Here is a link to more info: http://developer.android.com/guide/developing/devices/emulator.html

Good Luck amb

# Answer
> 0 votes
Besides the technical aspects (addressed by Mr Strange) be careful when designing a game with variable screen size. Just as an example, imagine playing streets of rage in a landscape-like screen and then in a portrait screen.

---
Tags: android, resolution
---


# Question
Title: Eliminate delay between looping XNA songs?
I'm making a game with XNA and trying to get some background music to loop correctly. Because the file is an MP3 of about 30 seconds in length, I instantiated it as a `Song`. I want it to loop perfectly, but even when I set the `MediaPlayer.IsRepeating` property to `true`, there is always a delay of about one second before the song starts up again. Is there any way to eliminate this delay such that the song loops instantly, so it can play more fluently?

# Answer
> 7 votes
The MediaPlayer in XNA has always had a short delay when looping songs and I haven't seen any way to resolve the issue. What is your target platform? You could consider using XACT if you are targeting the Xbox or Windows as it doesn't have the same issues as the MediaPlayer API.

I'd recommend against using SoundEffect (as recommended by Sprunth) to play background music if you are going to release on XBLIG or the WP7 marketplace as that doesn't mesh well with the built in media player and leads to certification/peer review issues. For example, if you play your background music as a SoundEffect on the Xbox and a player wants to use their own custom soundtrack your music will still keep playing over top, whereas if you had used a Song as recommended it would "magically" stop. Similar bad things happen on the phone.

# Answer
> 4 votes
I made a quick xna app with a ~15 second mp3 and can confirm that MediaPlayer does have this issue when looping. I tried it again with SoundEffect (and SoundEffectInstance for looping in XNA4) and the issue disappeared. So I guess you could switch to SoundEffect?

Some research/sources: Looping music using MediaPlayer problem Ways of fixing the delay gap when looping MP3s in XNA 3.0

---
Tags: xna, xna-4.0, music
---