# Question
Title: Can I still call something a "game engine" if I use other APIs to build it?
I am planning to create a game engine for iOS that is similar to Cocos2d.

I wanted to use frameworks like UIKit to display UIViews and UIImageviews. In Cocos2d they don't use the objects in UIKit. If I used the objects in UIKit in my game engine could I still call it a game engine?

# Answer
> 6 votes
Yes, you could. You could call your product whatever you wanted, really. It's your product.

There isn't a strict definition for the term "game engine" within the industry. Most people will probably agree that an "engine" provides some reusable components and tools, typically at a high level, for building a product like a game and a "game engine" specifically provides those tools with the intent of building a complete game (versus a "physics engine" which only focuses on providing functionality to simulate physics).

Using *other* frameworks/APIs/engines underneath the abstraction of your own engine (or even exposing them) doesn't *itself* invalidate your use of the term "engine." It may not be the best idea, but that isn't what you asked.

# Answer
> 3 votes
**A game engine is a system designed for the creation and development of video games.** (wikipedia http://en.wikipedia.org/wiki/Game\_engine)

Most of the game engines out in the market use some API's some way or the other. None of the engines out in the market has the developer's physics engine, they all either use PhysX, Havok or Bullet etc.

Some engines like Unreal or Unity use Beast for lightmapping.

There are other countless examples but for the sake of keeping the answer short, yes you can call it a game engine as long as it lets you create games.

---
Tags: terminology
---


title: Key-Binding in XNA

text:
# Question
Title: Key-Binding in XNA
I have been thinking about this issue for a while now and my recent efforts to find an already existing answer have not been successful.

I am trying to implement a menu system via which the player can map custom keys to each of the controls in the game (of which there are not a whole lot of). What i currently have is a functional menu where the user is able to specify which key they want each control bound to. This screen then writes these keys to a simple XML file from which the rest of the game is able to access these key bounds.

My problem is this: The user is able to use both the mouse and the keyboard to bind the controls to, however these are separate *types* according to XNA. When i go to retrieve the keybinding that has been loaded from the file i dont know which type it is, as it could be either. Is there some way of dealing with multiple *types* in this case or am i going to have to create my own type which encompasses both types within it?

At this point I am open to any ideas, Thanks in advance.

# Answer
> 2 votes
forgive me if i understood your question incorrectly, i have given this some thought in the past and decided that i would create an Enum for each action, and map each action to an enum for the controller method and an enum for the button /key press

this would in theory allow you to use both controller and keyboard (and mouse for that matter at the same time)

all you need to do is code the listening method to return the correct enum set when asking for the mapping of an action

finally when in you update loop that key is pressed you need to fire that event and have any component that is listening for it respond accordingly.

personally i would just create a wrapper class to do this for you and have the components talk to the wrapper (therefore maintaining separation of concerns a bit more)

# Answer
> 1 votes
A clarification question: "can your shortcuts consist of both a key AND a mousepress?" e.g. "CTRL" + right-click mouse? In that case you could make a small struct with both a ButtonState and a Keys membervariable to store both. This makes for easy XML serialiation/deserialization.

If you only want EITHER key OR mouse, you could still store the shortcut in a struct like that in the XML file and then after deserializing the XML, you can then iterate through all the shortcut objects and construct a list of Keys-shortcuts and a list of ButtonState-shortcuts based on which membervariable has a value in each shortcut object.

---
Tags: xna, input
---


# Question
Title: How to swallow touches on CCMenu while sliding?
I'm creating a sliding menu for my game something like angry birds level selection but I'm having problem with buttons. If I accidentally touch any of the buttons while swiping the level starts to load.

# Answer
> 1 votes
It sounds like the level loads when the button receives ccTouchMoved. Try to make the level load when the button receives ccTouchEnded.

# Answer
> 0 votes
Unsure what the equivalent would in coco be but maybe make the buttons touch intent where as if they are touched for a length of time then start level otherwise ignore, you should be able to swipe across them all without being on a single button long enough to start the level.

---
Tags: c++, cocos2d-x
---


# Question
Title: How to implement buffs / debuffs / temporary stat changes in an RPG?
> **Possible Duplicate:**
> What’s a way to implement a flexible buff/debuff system?

In the context of creating an engine for a RPG I want to implement a generic way to give effects / buffs / debuffs to the player, for instance:

```
strength boost : +15 to strength last for 10 mins
sickness : all attributes are divided by 2. Permanent until removed

```

Now the problem is that effects can stack upon each others but they can be removed independently. For instance you could have both above-mentioned effects and only remove the "sickness" one leaving the other one.

Are there any existing solutions to this problem? My idea is to always recompute the "final" statistics by applying each effect in chronological order to the "initial" stat, but I wonder: is there any downside?

# Answer
> 12 votes
Given the fact that you have this sickness divisor, you'll get in trouble if you try to stack and destack your buffs chronologically. Arithmetic will trick you, e.g. this is what could happen:

```
        player base strength: 5
strength boost applied (+15): 20
       sickness applied (/2): 10
strength boost removed (-15): -5 (--> oops?!)

```

To avoid this problem I would maintain a simple `std::list` of all the active buffs, update them and recompute the stats *each frame*. This is what a single buff/debuff could look like, with `stats` an array of size `STAT_COUNT`:

```
struct Buff
{
    enum Type
    {
        Type_BonusMalus,
        Type_Multiplier,
    };

    Type type;
    int value[STAT_COUNT];
    float timeLeft; // FLT_INFINITY = permanent

    void updateAndApply(float dt, int* stats)
    {
        for (int i=0; i<STAT_COUNT; ++i)
        {
            switch (type)
            {
                case Type_BonusMalus: stats[i] += value[i]; break;
                case Type_Multiplier: stats[i] *= value[i]; break;
            }
        }
        if (timeLeft != FLT_INFINITY)
        {
            timeLeft -= dt;
        }
    }

    bool hasTimedOut()
    {
        return (timeLeft <= 0.0f);
    }
};

```

Let's assume that `buffList` is the current `std::list<Buff>`. Your update function would look something like this:

```
void updateAndApplyBuffs(float dt, int* stats)
{
    // set base stats
    setToBase(stats);

    // update & apply buffs
    std::list<Buff>::iterator it;
    for (it = buffList.begin(); it != buffList.end(); ++it)
    {
        it->updateAndApply(dt, stats);
    }

    // remove the ones that timed out
    // SuperCool® STL stolen from http://stackoverflow.com/a/596708/1005455
    buffList.remove_if(std::mem_fun(&Buff::hasTimedOut));
}

```

When your player picks up a new buff, you simply create it and push it to the back of the list. When you need to cancel a buff, remove it from the list. The buffs with a duration will time out by themselves after a while.

This will apply the buffs "chronologically", but I personally don't recommend this gameplay-wise. For instance the sickness divisor would be more or less penalizing depending on if you get it before or after a boost. To circumvent this issue, I would rather always apply the divisors/multipliers first, and the bonuses/maluses second:

```
void updateAndApplyBuffs(float dt, int* stats)
{
    // set base stats
    setToBase(stats);

    std::list<Buff>::iterator it;

    // apply multipliers first
    for (it = buffList.begin(); it != buffList.end(); ++it)
    {
        if (it->type == Buff::Type_Multiplier)
            it->updateAndApply(dt, stats);
    }

    // then apply bonuses/maluses
    for (it = buffList.begin(); it != buffList.end(); ++it)
    {
        if (it->type == Buff::Type_BonusMalus)
            it->updateAndApply(dt, stats);
    }

    // remove buffs that timed out
    // SuperCool® STL stolen from http://stackoverflow.com/a/596708/1005455
    buffList.remove_if(std::mem_fun(&Buff::hasTimedOut));
}

```

This should give you a solid basis, not over-engineered, not too hacky.

# Answer
> 6 votes
Typically, when you're talking about stat-management, there are a million ways to accomplish what you're looking to do, but also probably a few established techniques which are widespread.

Consider two players in PvP:

Their stats/levels are the same - they each have 20STR, and HP is based on STR * 10, Damage is STR * 2.

Also assume we're using an old school system, where current max\_health and max\_damage are caps which can be lowered when poisoned/cold, et cetera.

Lastly, consider division by X to be multiplication by 1/X.

Olag\_the\_Serious picked up a +15 strength amulet and then got sick. Jimmy\_the\_Geek got sick, but then picked up a +15 strength amulet.

Then they fight.

Olag's stats:

```
STR = (20 + 15) * 0.5 // 17.5
Health = STR * 10     // 175
Damage = STR * 2      // 35

```

Jimmy's stats:

```
STR = (20 * 0.5) + 15 // 25
Health = STR * 10     // 250
Damage = STR * 2      // 50

```

So now we've got this really unbalanced fight between these two characters who have done the exact same things, other than the order of picking up buffs.

How do we fix this?

Break your integer and fractional stats into two groups. Add the integers. Then take the final integer and use that as the basis for calculating your fractions.

```
var finalStat = 0,
    fractionalBaseline = 0,

    ints = [2, 15, -7],
    fractions = [0.2, -0.1, 4];

for each ints as int
    fractionalBaseline += int;
end

finalStat = fractionalBaseline;

for each fractions as multiplier
    finalStat += Math.floor(frationalBaseline * multiplier);
end

```

Okay, so the PseudoScript is kinda ugly, but that's the idea.
Now, it doesn't matter what order anything happens in.
We've calculated the baseline with the ints, and then we use the baseline (rather than a running tally) to calculate fractions, which we then convert to ints (totally optional - some games only do that for the user-visible stats), and add them to the final stat.

You might think this is cheating the player, by not adding the fraction to the final tally. What it's really doing is giving everyone a fair experience, because now:

Olag:

```
STR = (20 + 15) * 0.5 // 17.5
Health = STR * 10     // 175
Damage = STR * 2      // 35

```

Jimmy:

```
STR = (20 + 15) * 0.5 // 17.5
Health = STR * 10     // 175
Damage = STR * 2      // 35

```

It's a fair fight.

Even better, when they get rid of their sicknesses, they'll go back to the same health -- removing an int is simple, but removing a fraction, you convert it to an int based on the current baseline (or float, if you're doing that) and subtract that number.

Just remember that whenever you add an int-bonus, that changes the baseline for the stat, so recompute the fractions, as well.
When you add a fraction, the baseline stays the same.

There's also nothing saying this can't be 100% OOP or Entity/Component-based. This is just the basic concept for arriving at how to have both `Boots of Buttkicking (+3 against Butts)` and `Almost-Quad Damage (397%)` in the same game, and have it be fair.

# Answer
> 2 votes
I'm doing something similar at the moment; I've split effects into single-shot (your strength boost or sickness) and multi-shot (poison - takes X hitpoints each Y seconds). Build a class (if you're writing OO code - if not, it should not be too hard to get the idea) to manage the effects, and make it a property of each character. You can define IDs for each type of effect. For example

```
#define EFFECT_POISON 0
#define EFFECT_STRENGTH 1

```

and store them inside the Effects class inside a dictionary (keys = effect ids) of some sort. But really, any kind of iterable collection works - you can build a struct like

```
struct Effect
{
int EffectID;
int Duration;
int MultiShotFrequency;
}

```

and store one for each effect in a linked list for example). Every second of game time (I add up the time between frames until it's a full second) just iterate through the effects and see which one has to be applied.

Also expose public methods such as

```
//                      -1 for infinity?   0 for single shot?
ApplyEffect(int EffectID, int Duration, int MultiShotFrequency)
RemoveEffect(int EffectID)
//then you would go like:
ApplyEffect(EFFECT_POISON, 10, 1); //Poison each second for 10 seconds.
ApplyEffect(EFFECT_STRENGTH, -1, 0); //Strength boost of infinite duration (permanent), singleshot
RemoveEffect(EFFECT_POISON);

```

You can use floating points instead of integers if you want to apply effect each 0.5 seconds for example.

---
Tags: c++, game-mechanics, rpg, effect-modifier
---


# Question
Title: What physics engine support force fields and bodies represented as points?
I need a game engine that supports force fields in 2d or 3d, but suitable for 2d calculations, like bullet.

Each body I want to simulate is represented as a set of points. Each point has positive mass and can accept force. Force field is updated every tick. Engine should accept force applied to every point and return point speed values and coordinates. Each body made of particles should move as a whole thing in result, relative position of particles must persist, hence this is a rigid body. If engine does not support setting body as a set of points it should allow setting density function, or some other means to let have non-uniform density.

Is there any that can do that, preferably cross-platform.

# Answer
As explained in the comments, each physics engine will do it, so will Bullet. You can use btCompoundShape to create a rigid body from multiple "sub"-bodies, each with its own mass.
> 1 votes

---
Tags: physics, physics-engine
---


# Question
Title: Performance of pixel shaders vs. SpriteBatch: XNA
Precondition: I read this question/answer about using shaders, or spritebatch, to render and mark a sprite.

I need to do something like that. I also have a 2D lighting PoC which I need to write. The way it will work will basically be something like:

* Draw all the sprites
* Draw lighting gradients to create a lighting texture
* Multiply/add the lighting texture to achieve different effects

(I use multiple passes of add/multiply the lighting texture to achieve different effects.)

My question is really about a generalization: can I say with certainty that **pixel shaders are always faster than adding/multiplying textures to the SpriteBatch?** Or that adding/multiplying is always faster? Or if it's not generalizable, how do I decide which approach to take, given that I can probably code either of them?

(If it matters, I'm using MonoGame 3.0 beta for Windows games)

# Answer
> 2 votes
if i understood correctely, you are asking about what is faster, mix colors in pixel shaders or mix colors using blend states ?

In general case, using Blender States should be faster cause Video Boards normally have specifically dedicated piece of harware to perform this operation. (In this aproach you can also use the pixel shader to perform other funcy stuff in the texture you read)

But, for example, if you need to perform 3 pass to get the result you want (each one with a different blend state), probably mixing the color in just one pass in one pixel shader would be faster.

To be honest (assuming you are targeting PC), unless you are doing MASSIVE color mixing, both approach wont be a bottleneck in your application.

just to clarify one last thing. Spritebatch is just an easy to let you handle textures and text easily (and also performatic way), behind the curtains, it is actually drawing a full screen quad, using a shader ......

---
Tags: 2d, xna-4.0, shaders, lighting, monogame
---


title: Not So Beginner Tutorial Request

text:
# Question
Title: Not So Beginner Tutorial Request
So my game is done for now but every time it flashes on the screen and my game loop is awful. So crowded with logic.

I need to learn more about games and how they are running. My idea now is that at the heart of the game you have a while loop. Inside that you are checking for events to happen. Each time an event happens, you spawn a thread that accomplishes a task.

You then have a layer that draws on the screen the "map". Also a layer that says where objects collide. And finally the logic of how objects interact.

I am using C++ and SDL and I need a complete tutorial that takes me through a complex example to get started. I am a good programmer but have no experience with games. Any suggested tutorials would help.

All tutorials I have found so far are too easy and don't do anything worth while.

# Answer
> 3 votes
The Lazy Foo articles section was a great guide for me. Obviously his tutorials are top notch for sdl but these cover other things like game loops, state machines, ai etc.

http://lazyfoo.net/articles/index.php

My game loops are just an extension of his ideas in the game loop article and its served me well.

# Answer
> 1 votes
I'm not a very good game programmer but I'll try to help you.

I suggest a very good book on game engine concepts called "Game Engine Architecture". You should definitelly read it.

And one more thing: dive into the code of open-source games like Supertux and Kobo Deluxe. Both have very good performance and well organized code.

Hope it helps! =)

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


# Question
Title: What's the term for the "vertical looking angle" in FPSs?
I guess the "vertical angle" of looking in an FPS could be called the pitch of the camera, but surely there is another term for it?

(I'm trying to mod ArmA II, but I can't find anything in their documentation and forums about the camera pitch or whatnot. The ArmA people call the horizontal angle "direction.")

# Answer
The typical term for this is indeed "pitch," but that doesn't mean that all games will use that term explicitly, which may be why you can't find it.

Sometimes you'll also hear "angle of attack" although the latter does have a more specific meaning and is often abused.
> 3 votes

---
Tags: terminology, first-person-shooter
---


# Question
Title: Ogre3D particle effect causing error on iPhone
1) First I have added the Particle Folder from the Ogre SDK (contains `Smoke.particle`).

2) Added the `Smoke.material` And `smoke.png` and `smokecolors.ong`.

3) After this I added the Plugin = Plugin\_ParticleFX in the `plugins.cfg`.

Here is my code:

```
#Defines plugins to load

# Define plugin folder
PluginFolder=./

# Define plugins
Plugin=RenderSystem_GL
Plugin=Plugin_ParticleFX

```

4) I have added the particle path in the `resources.cfg` (adding the particle file in this causes the crash):

```
#Resource locations to be added to the 'bootstrap' path
# This also contains the minimum you need to use the Ogre example framework
[Bootstrap]
Zip=media/packs/SdkTrays.zip

# Resource locations to be added to the default path
[General]
FileSystem=media/models
FileSystem=media/particle
FileSystem=media/materials/scripts
FileSystem=media/materials/textures
FileSystem=media/RTShaderLib
FileSystem=media/RTShaderLib/materials

Zip=media/packs/cubemap.zip
Zip=media/packs/cubemapsJS.zip
Zip=media/packs/skybox.zip

```

6) Finally I did all the settings, my code is here:

```
mPivotNode = OgreFramework::getSingletonPtr()->m_pSceneMgr->getRootSceneNode()->createChildSceneNode();  // create a pivot node

// create a child node and attach an ogre head and some smoke to it
Ogre::SceneNode* headNode = mPivotNode->createChildSceneNode(Ogre::Vector3(100, 0, 0));
headNode->attachObject(OgreFramework::getSingletonPtr()->m_pSceneMgr->createEntity("Head", "ogrehead.mesh"));
headNode->attachObject(OgreFramework::getSingletonPtr()->m_pSceneMgr->createParticleSystem("Smoke", "Examples/Smoke"));

```

7) I run this and got the error below:

```
An exception has occurred: OGRE EXCEPTION(2:InvalidParametersException): Cannot find requested emitter type. in ParticleSystemManager::_createEmitter at /Users/davidrogers/Documents/Ogre/ogre-v1-7/OgreMain/src/OgreParticleSystemManager.cpp (line 353)

```

8) Getting crash at:

```
(void)renderOneFrame:(id)sender
{
    if(!OgreFramework::getSingletonPtr()->isOgreToBeShutDown() &&
       Ogre::Root::getSingletonPtr() && Ogre::Root::getSingleton().isInitialised())
    {
      if(OgreFramework::getSingletonPtr()->m_pRenderWnd->isActive())
      {
         mStartTime = OgreFramework::getSingletonPtr()->m_pTimer->getMillisecondsCPU();
//( getting crash here)

```

Does anyone know what could be causing this?

# Answer
> 2 votes
The error message \*Cannot find requested emitter type. in ParticleSystemManager::\_createEmitter\* can basically have two central reasons:

1. The ParticleFX plugin wasn't successfully loaded. This is a problem as the emitter types are defined in it.
2. You specified a non-existing emitter type in your particle script

Either way the answer lies in the Ogre.log file. The following lines should be there:

> 19:19:12: Loading library .\Plugin\_ParticleFX
> 19:19:12: Installing plugin: ParticleFX
> 19:19:12: Particle Emitter Type 'Point' registered
> 19:19:12: Particle Emitter Type 'Box' registered
> 19:19:12: Particle Emitter Type 'Ellipsoid' registered
> 19:19:12: Particle Emitter Type 'Cylinder' registered
> 19:19:12: Particle Emitter Type 'Ring' registered

If that part is missing in your log, then double check that the plugin DLL file is present in your execution folder and named as specified in your above listed `plugins.cfg` file. If those lines are present however, ensure that you used one of the mentioned emitter types in your script, spelled exactly the same way.

BTW to be exact: The crash will occur in this line, since that is when Ogre tries to use the unknown emitter type:

```
OgreFramework::getSingletonPtr()->m_pRoot->renderOneFrame();

```

---
Tags: iphone, ogre
---


# Question
Title: Designing a "Grid" like object that contains game objects
I am working on a 2D game, where there's a game "board" on which other game objects are placed.

This this is 2D, my starting point was to design a class that will internally use a 2d array for the actual stored game objects.

This class could be simply accessed by 2 indices: (i, j) to get game objects on it.

My problem is that i have no idea how to make the game "board" "propagate" its data onto its children.

Design questions i ran into are:

1. Should the children placed on the board have display properties such as size, screen position?
2. Should the board itself dictate this information?
3. How to update children in case the board changes some of its properties? (position, etc).
4. Should the board be aware of the types of objects stored in it ?

I have no idea how similar things such as WPF or other UI frameworks go about organizing a "container like" object that can arrange or apply certain UI properties to its children.

# Answer
> 3 votes
The answer to most of your questions is: It depends.

What you should keep in mind when designing this kind of system:

* Does the grid have a constant size?
* All cells have the same size?
* GameObjects can be in-between cells?
* Most of the cells will be full or empty?
* How often does your GameObjects change it's position?
* What is the source of logic? The board or the GameObjects?

If your board size is constant and cells are all of the same size, then it's good to make the board control the position. But if your GameObjects can be in-between the cells, then it's better to make them control the position separately from its index.

If most of your cells are going to be empty, putting your GO's in an array and just keeping it's indices available inside it is a good idea. If they most cells are going to be filled, an 2d array seems better.

To decide what updates(the board or the game objects) think of what is the source of the logic. For example: In a Chess game, it's a mix. The piece gives its rules, but the board knows where is everything.

And keep in mind: Do what feels right and seems good for you, but don't pre-optimize! If it's working and no flaws are detected, keep it this way.

# Answer
> 0 votes
Ideally, you'd structure it in whatever way would allow you to write self-describing code.

```
player["Black"].piece["Rook2"].move(2, 0);

```

Versus

```
chess_board.move("Black", "Rook2", [2, 0]);

```

Both of these are horrible pseudocode hacks and not exactly indicative of the final product, but hopefully provide consideration of how you might want to address the abstract concepts of *playing* the boardgame in terms of your code.

In terms of common issues, are you planning on animating pieces as they move?
If so, you might want pieces to control their own state.

Another consideration might be to "bind" and "unbind" pieces from squares.
Give the pieces a simple, loosely-coupled interface for querying the square they're in and/or the square they're moving to.

Your board could talk 100% in grid-coordinates (making rule-keeping easier, depending on the game), then the pieces could use those grid-coordinates to enforce rules, AND to request a connection to talk to their new grid square (dropping the connection to the previous square).

Most of the positioning logic for drawing, et cetera, could be held within a piece, which just needs to take the grid-coordinates and position itself inside the center of the grid square (when it's done animating).

At this point, pieces and squares could be put in separate arrays and updated separately, even.
Pieces would control their logic/presentation based on the grid coordinates they're given by the squares they're talking to.
Squares could maintain any bonuses that they might hold (snakes/triple-word-score/go directly to jail), and confer those to a piece, if the square believes that the rule is appropriate to that piece at that time (eg: go-to-jail/jail + just-visiting).

Note that this isn't ***THE*** way to do things.
In fact, it might be way over-engineered for your needs.
Or under-engineered.

Or it might just look like nonsense, because you'd really like to write the code from the perspective of the player who rolls dice/picks up a card/etc and manually moves a piece, versus a piece which moves itself or a board which pushes a piece around.

---
Tags: c#, architecture
---


# Question
Title: Which platform (server) use for turn based card game?
My game will do next:

1. Dealing 4 cards to every player
2. Random player is turning over 1 card, after him another (which has seen card of previous player) and etc.
3. On the end player with the highest card wins and dealing cards starts again

I think it would be best that player could choose room in which he would play.

So my question is what type of comunication to use? Over Game center, my custom server or there is some spacialized server for that kind of thing?

**UPDATE (added second question):**

I have read on severral forums that Game Center has limit up to 4 or 16 players. My game will play over 16 people (for start I'm sure that there will be 30-40 players in same time in game). Or that means that there can be max 4/16 plaers in same match (room)?

**UPDATE 2:**

My game will have 4 players (exactly 4). I will set max. timeout 10 seconds and after that if player has not turned card game is over for every player (this is that kind of game). Players can not leave the match and return again later. This is the flow of the game: player 1 plays his card, after that player 2, 3, 4 and than again player 1. Each player has to play and it's not possible to skip someone. And I need to do everything programaticaly; start the match, join the match (autom-match is only available except invite).. If all of that i can do with Game center, that's great, I will do that then.

# Answer
You say turn-based, but haven't used the magic word "asynchronous". (The question is, will the players be able to leave the match and return again later when it is their turn? I'd imagine you want the answer to be yes.)

You are right about the max number of players limitation in GameCenter. (16 for asynchronous matches, I'm not sure about real-time.) I believe the minimum number is 2. (Check out the GameKit documentation for more specifics.)

There are a lot of things to consider when deciding whether you want to want to write your own server. Your web programming experience is definitely a factor. (Would you feel confident you are writing a secure and not-exploitable server?) Of course, the cloud services are not guaranteed to be infallible in this regard either. Another is long-term cost. There was that recent story about the company who closed their online servers because the piracy was going to cost them too much. (The game was called Battle Dungeon.)

I'm assuming asynchronous here, but an alternative to writing your own is to use a service. (I'm sure there is someone offering a "cloud based real-time multiplayer service", but I don't know about it offhand.) I have not used any of these, but I would spend some time and evaluate the following list (more or less in order of my impression of them, but again, I can't recommend from experience): Parse, FatFractal, StackMob, Kinvey, Kumulos, Applicasa.

Good luck!

**UPDATE after Q #3**: Ahhh, you are not wanting asyncronous games then. Yes, you can do all of that with GameKit. Here is a link to the GameCenter Programming Guide section on Real-Time matches.
> 1 votes

# Answer
If you choose to write your own server, consider using the Node.js platform. The asynchronous model makes it really easy to handle a lot of connections. In traditional programming network code can make performance plummet if you are not careful.
> 0 votes

---
Tags: iphone, ios, game-center
---


# Question
Title: MultiTexturing by neighbouring points textures
**Visual example:**

I've been trying to understand multitexturing for a while now, I've created a terrain generator but have no need for height just yet and I still want one texture to blend over to another texture nicely.

I think Blau said that you only need 4 textures per vertex. My only guess then is that each point in a terrain has 4 neighbours - right? And that point is the main texture to sample from / blend from. Because it can't mean that 4 textures are all you get on a whole map in a game.

My idea is to have an "TextureID" for each point and whenever this point comes up, you load the textures in the effect with that neighbours textures.

Example (for each point):

```
effect.Parameters["MainTexture"].Setvalue(Content.Load<Texture2D>("MainTexture"))
effect.Parameters["TextureTopOfPoint"].SetValue(Content.Load<Texture2D>(textureID));
effect.Parameters["TextureRightOfPoint"].SetValue(Content.Load<Texture2D>(textureID));
effect.Parameters["TextureBottomOfPoint"].SetValue(Content.Load<Texture2D>(textureID));
effect.Parameters["TextureLeftOfPoint"].SetValue(Content.Load<Texture2D>(textureID));

/*
   Now the Pixel and Vertex Shader can calculate a blend effect
   from Center point to it's neighbouring points
*/

```

and somehow in the Effect file, blend from "Center point" to all it's neighbours. I also guess this would be a "slow" process.

Problems are:

* Is this possible? I can't accept 4 textures for a whole map, so how do I manage to have multiple textures at the same time? And I don't want a solution with colors (like this) or heightmap, because I want it to be possible to have 4 or more textures on a flat surface.
* How do I access each point's neighbour and when do I know when to set them?

My map contains Areas, each Area has it's own VertexBuffer and IndexBuffer.

(Example: MapWidth=4096, MapHeight=4096, each square = 128x128 = (32 * 128 x 32 * 128 grid)

```
public class Area
{
    public VertexPositionTexture[] Vertices { get; set; }
    public int[] Indexs { get; set; }

    public VertexBuffer GetVertexBuffer() { /* create a vertexbuffer */ }
    public IndexBuffer GetIndexBuffer() { /* creates a indexbuffer */ }
}

```

**Edit** (still not optimal)

Implemented some kind of method, but this method still relies on colors and I have no blendmap. I just use the color in the Vertex to check for a value (r, g, b, a)

Effect Code:

```
float4 PixelShaderFunction(VS_OUTPUT input) : COLOR
{
   float4 colour = float4(0,0,0,0);

   colour += tex2D(GroundText0Sampler, input.TexCoord) * input.Color.r;
   colour += tex2D(GroundText1Sampler, input.TexCoord) * input.Color.g;
   colour += tex2D(GroundText2Sampler, input.TexCoord) * input.Color.b;
   colour += tex2D(GroundText3Sampler, input.TexCoord) * input.Color.a;

   return colour;
}

```

# Answer
The idea of blending 4 textures together by using a 5th texture to specify how to blend them together can be easily extended to 8, 12, 16, ... textures. As a quick refresher this is how the default approach works:

You have 4 textures for detailing, for example:

* Rocks
* Grass
* Water
* Concrete

And one texture which specifies how to blend these together. In the pixel shader we sample the colour for the final pixel like this:

```
float4 blending = tex2D(blendmap, In.uv);
float4 output;
output.rgba =
    tex2D(rocks, In.uv).rgba * blending.r +
    tex2d(grass, In.uv).rgba * blending.g +
    tex2d(water, In.uv).rgba * blending.b +
    tex2d(concrete, In.uv).rgba * blending.a +

output.rgba /= 4;

```

As you see we are limited to 4 textures because our blend map has only 4 channels.

Now all we need to allow 8 textures is adding a second blend map, add the terms of the second blend map and then divide by 8 at the end. We can keep doing this, it's not going to get any cheaper anyway because we will need to store in some way how the textures are blended.

I also think that you don't need more than 8 or maybe 12 textures to have a really good looking terrain. Smaller details can be added using projections and of course you can use multiple terrain meshes that partially obscure each other.
> 2 votes

---
Tags: xna, c#, textures, hlsl, effect
---


# Question
Title: Seamless transition between planet and space
I have been curious about how this kind of seamless transition from space to planet can be implemented. It would be nice if someone could explain this as I can't really wrap my head around the solution.

# Answer
> 3 votes
Over time, move the camera from far away from the planet to close to the planet surface. This is analogous to the way that you can seamlessly transition from one side of a Quake level to the other side, merely by moving the camera from one side to the other.

There really is no fundamental difference between the two.

# Answer
> 2 votes
Write a Function that describes your Surface, and then do low sampling on far distances and tight sampling on near distances. And then add some shiny visual effects.

# Answer
> 2 votes
http://acko.net/blog/making-worlds-1-of-spheres-and-cubes/

http://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html

This guy did exactly what your looking to do, his site goes into tons of details.

---
Tags: 3d, procedural-generation
---


# Question
Title: Tool to create a bitmap font from a true type font
What tool do you use to convert ttf fonts to bitmap fonts?

Following is a list of features I'm looking for. I'd be happy with any tool really, but one that had these features would be better.

* outputs power-of-2 texture atlas
* parsible config file (so I don't have to use their rendering library)
* output kerning information
* cross platform
* a rendering library would be great if it lets me make the actual OpenGL calls.

So what tool have you used? Were you happy with it?

# Answer
> 22 votes
### Font Builder

Font Builder does almost everything I need. Both Font Studio and Angel Code's BMFont and perform similar tasks. Here are some of Font Builders features.

* A QT app, and so works equally well on all platforms.
* Open source so it can easily extend the app if needed
* Designed to allow custom image and description(layout) exporters, making it even easier to extend
* Loads fonts from the filesystem instead of windows registry. This makes it a ton easier to generate texture fonts from my own TTFs.
* Auto sizes the final image so I don't need to guess( like in FontStudio). Further, these textures can be constrained to be power of 2 sizes.
* Kerning pairs are supported, so that info can be exported if your TTF uses them.

It's not all perfect however. The default layout plugins suck. The Box layout tool just fills the texture from top left to bottom right using the characters alphabetically. Not very efficient. I changed it to sort the characters by height first and quickly improved its efficiency (a 2 line change).

# Answer
> 11 votes
Google showed quite a few of those beasts. This might be close to what you're after
http://www.angelcode.com/products/bmfont/
You mention cross-platform, but do you mean the tool, or the output? (which would be cross platform maybe apart from endianness)

# Answer
> 4 votes
Try FontStudio: http://www.ogre3d.org/forums/viewtopic.php?f=11&t=47802

It's made especially for creating bitmap fonts for games.

I post a link to the Ogre3D forum, because it hasn't got a home of its own currently.

Find a link to the latest version in the last post of that topic (page 2).

# Answer
> 3 votes
There are many complicated and feature-rich tools out there but my favorite tool for building bitmap fonts is Codehead's Bitmap Font Generator (CBFG). It's a simple tool which does one thing very well. It's clearly documented with tips for implementation.

Like most bitmap font creators, it is of course graphics API independent because it simply exports an image (and an easy to read data structure). However, implementing your own text-rendering system, in OpenGL or Direct3D, is not too difficult--render a quad for each letter and apply the bitmap font texture with appropriate coordinates.

I hope this helps!

Note: This is a Win32 application only, but I still recommend it!

# Answer
> 2 votes
I have used this tool in the past: http://www.lmnopc.com/bitmapfontbuilder/. It works really nice and has a lot of options

# Answer
> 2 votes
A great tool for the mac is Glyph Designer and has become the tool of choice among Cocos2D users. It has many features and has recently been updated to include command line support!

# Answer
> 1 votes
The last time I was looking for this (for an iPhone game), I tried various options but couldn't find one that did everything I wanted. I needed to render a single texture using very small characters from a commercial TTF font. I needed to be able to specify character ranges so it would only contain the characters I needed. I wanted it to pack the glyphs as tightly as it could. I needed texture coordinates at runtime. I didn't care about "real" kerning, but I needed glyph measurements at runtime so it would be spaced sensibly. So I wrote a small Windows app that rendered all the characters and saved out the ABC spacings (as reported by Windows) along with texture coordinates.

BTW, if you want to render very small text (like less than 16 pixels high) under XP or Vista, you will run into shortcomings with Windows' anti-aliasing. An easy fix for me was to use http://drwatson.nobody.jp/gdi++/index-en.html to get transparent supersampling. If I were starting over, I'd probably take the same approach but look at FreeType2 instead of native text rendering.

If your text isn't updated often, you could just use the platform's text rendering (or maybe FreeType) to render whole chunks to texture as needed at runtime. Then you just need to render a single quad for each string, but the texture allocation gets more complicated. On the upside, though, you get flawless text rendering and layout for free on those difficult Asian languages along with your significantly faster GL code. Rendering lots of individual characters is expensive, even with degenerate tri strips or whatnot.

# Answer
> 1 votes
On the Mac you can only use Hiero (http://slick.cokeandcode.com/demos/hiero.jnlp) as far as I know. It is not as powerful as the above, but with a little bit of Photoshop magic it'll do.

# Answer
> 0 votes
The keyword you're looking for is a "rasterizer". XNA has one built in. A quick Google search brings up FreeType. I'm not sure what else is out there.

# Answer
> 0 votes
If you want an interactive tool you may want to take a look at FontForge, which is a full font editor that supports a variety of tools for converting TTF fonts into bitmap formats. It supports various types of scripting, so you should be able to integrate it into a pipeline as well.

# Answer
> 0 votes
http://creators.xna.com/en-US/utilities/bitmapfontmaker is one, but its not cross platform as a tool.

# Answer
> 0 votes
a new bitmap font generator has been released for OS X: bmGlyph (http://www.bmglyph.com). available only on the mac app store. ouputs font atlas and bitmaps (hd/sd) with a lots of feature.

---
Tags: tools, fonts, pipeline
---


# Question
Title: XNA Why is Texture.GetData one dimensional?
This is question has been really killing me. In XNA when you want to convert an image to color data using Texture.GetData, it only lets you make it a one dimensional array instead of a 2D one. This makes it much more difficult to work with. Is there a specific reason it's like that?

# Answer
Xna is built uppon Directx and Directx use this strategy cause this is how the the display driver exposes information it gets from the video board. (actually it exposes an array of bytes). Also to give you a 2d array, the api would need to know the "size" of each texel and the dimensions of you texture to make the conversion. For performance reason, they let the user decide if they want/need to make the conversion.

You can always convert the recovered array in a 2d one. (or you can wrap it in a class that make the coordinate conversion)
> 8 votes

# Answer
As Tpastor had a great answer on *why*, here is *how* to convert it from the hard to read 1D array, to a simple 2D array for easy access to each pixel.

```
Color[,] TextureTo2DArray(Texture2D texture)
    {
        Color[] colorsOne = new Color[texture.Width * texture.Height]; //The hard to read,1D array
        texture.GetData(colorsOne); //Get the colors and add them to the array

        Color[,] colorsTwo = new Color[texture.Width, texture.Height]; //The new, easy to read 2D array
        for (int x = 0; x < texture.Width; x++) //Convert!
            for (int y = 0; y < texture.Height; y++)
                colorsTwo[x, y] = colorsOne[x + y * texture.Width];

        return colorsTwo; //Done!
    }

```
> 5 votes

---
Tags: xna, 2d
---


title: Testing multiplayer android

text:
# Question
Title: Testing multiplayer android
In what way can an android game be tested considering the following constrains:

* minimal to no budget, so I cannot hire an external company to do the testing for me
* Testing should occur on multiple devices and types (phones and tablets, I have 1 available for each)
* I do not have a team of testers, nor a large group of people with android devices willing to back me up.
* The game is a multiplayer game (min 2, max 4 players per game) with a backend that will be hosted on an external server (which is already arranged), so for every testrun 2 devices are needed.
* The game server is not built in java and will be unit tested, the testing is more about doing integration testing.
* Optional is stress testing the game server so we can get some sort of baseline for this hardware.

# Answer
> 1 votes
**Minimal to no budget** means you're doing it yourself. As an indie developer, you shouldn't be considering to hire an external company to "test" for you-- this is a game, not a NASA rocket.

If you have the hardware, then you're already halfway there. A couple of ways to gather people to test your game:

* If you live near a university or college, you might have success postering with things like "Game test volunteers needed! Android developer needs 2-4 students who are very interested in gaming to test new multiplayer game SPROCKETS. Game genre is RTS strategy. PIZZA will be provided." and attach your number
* Meetup.com might put you into contact with like-minded individuals in your area
* You might also try Craigslist (volunteer jobs) and kijiji (also asking for volunteers)

---
Tags: android, testing
---


title: Diffuse light direction

text:
# Question
Title: Diffuse light direction
I'm learning a tutorial from Rastertek about diffuse light with DX 11, here's the shader code:

```
float4 LightPixelShader(PixelInputType input) : SV_TARGET
{
    float4 textureColor;
    float3 lightDir;
    float lightIntensity;
    float4 color;

    // Sample the pixel color from the texture using the sampler at this texture coordinate location.
    textureColor = shaderTexture.Sample(SampleType, input.tex);

    // Invert the light direction for calculations.
    lightDir = -lightDirection;

    // Calculate the amount of light on this pixel.
    lightIntensity = saturate(dot(input.normal, lightDir));

    // Determine the final amount of diffuse color based on the diffuse color combined with the light intensity.
    color = saturate(diffuseColor * lightIntensity);

    // Multiply the texture pixel and the final diffuse color to get the final pixel color result.
    color = color * textureColor;

    return color;
}

```

And I don't understand why to invert the direction, it says in a comment line "invert the light direction for calculations", why is it necesary?

Thanks.

# Answer
> 5 votes
@alariq is correct, assume you have this scenario:

The light is shining DOWN and LEFT. The normal of the surface is UP and to the RIGHT.

If you just take the dot product:

```
float lightIntensity = saturate( dot( N, L ) )

```

The saturate function is going to clamp the value to being between 0 and 1. So, that's going to be

```
lightIntensity = (0.5, 0.75) • (-0.75, -0.5) = -0.375 - 0.375 = -0.75

```

But oh no! That will be clamped off to 0, and the point will appear in total darkness. How sad.

So if you turn lightDir around,

```
float lightIntensity = saturate( dot( N, -L ) )
lightIntensity = 0.375 + 0.375 = 0.75

```

Oh, that works. Why?

Well the light at the vertex should be most intense when lightDir is directly opposed to N.

But the dot product of two normalized vectors is **the cosine** of the angle between them

```
u • v = |u||v| cos(t)

```

If |u|=|v|=1, then

```
u • v = cos(t)

```

But cos(0) = 1, which should correspond with maximal illumination. Here's what we'll do. We'll turn lightDir AROUND, so then when -lightDir lines up perfectly with N, then lightDir is actually head-on with N.

All what we're doing is manipulating the vectors so that the dot product (which is actually the cosine of the angle between lightDir and N) gives a maximal value when lightDir is head-on with N.

# Answer
> 3 votes
This is necessary to receive a correct sign of a dot product. **lightIntensity** of a point depends on the angle between the two vectors: one is normal in a point of interest and second is a vector which goes from point of interest to light source.

That is, if the normal points at the light - intensity will be maximal. Imagine you are looking at the sun: your view vector is same as sun light direction, but with a different sign. So we need to inverse light direction to get correct dot product.

Your shader is for the case of direct light source (which is the approximation of a light source at infinity - like sun, and so intensity of a point depends only at its direction - not its position). In case of a point light formula might be more intuitive (assume **lightPos**, **pointPos** and **normal** in same space):

```
posToLightDir = normalize(lightPos - pointPos); // same as inverted lightDir in your case
lightIntensity = saturate(dot(normal, posToLightDir));

```

In case of directional light **pointPos** is not needed, so

```
// here normalize(lightPos) would be same as -lightDir
posToLightDir = normalize(lightPos);

```

You can search for Lambertian cosine Law, or Lambertian Reflectance

---
Tags: directx, hlsl, lighting
---


# Question
Title: How do I best remove an entity from my game loop when it is dead?
Ok so I have a big list of all my entities which I loop through and update. In AS3 I can store this as an Array (dynamic length, untyped), a Vector (typed) or a linked list (not native). At the moment I'm using Array but I plan to change to Vector or linked list if it is faster.

Anyway, my question, when an Entity is destroyed, how should I remove it from the list? I could null its position, splice it out or just set a flag on it to say "skip over me, I'm dead." I'm pooling my entities, so an Entity that is dead is quite likely to be alive again at some point. For each type of collection what is my best strategy, and which combination of collection type and removal method will work best?

# Answer
> 13 votes
I would store all add/removes in separate lists and do those operations after I've iterated through the update-loop.

# Answer
> 10 votes
The Flixel framework uses the dead flag (actually several flags that determine whether it should be drawn, updated, and so on). I'd say that if you're going to revive entities, and if performance is an issue, you use the dead flag. In my experience, instantiating new entities is the most expensive operation in the use case you describe, and splicing out or nulling elements may lead to memory bloat given Flash's sometimes-squirrely garbage collection.

# Answer
> 3 votes
While some techniques are inherently more efficient than others, it'll only matter if you're running out of cycles on your target platform. Use whatever technique allows you to get your game done quicker. Try not to rely on the specific implementation of your container data structures in the meantime and it'll help you to optimize afterwards if you need it.

Just to address some of the techniques already discussed by others here. If order of entities is important, then a dead flag can allow you to splice during your update loop on the next frame. eg. very simple pseudocode:

```
void updateGame()
{
  // updateEntities()
  Entity* pSrcEntity = &mEntities[0];
  Entity* pDstEntity = &mEntities[0];
  newNumEntities = 0;
  for (int i = 0; i < numEntities; i++)
  {
    if (!pSrcEntity->isDead)
    {
       // could be inline but whatever.
       updateEntity(pDstEntity, pSrcEntity);
       // if entity just died, don't update the pDstEntity pointer,
       // and just let the next entity updated overwrite it.
       if (!pDstEntity->isDead)
       {
          pDstEntity++;
          newNumEntities++;
       }
    }
    pSrcEntity++;
  }
}
numEntities = newNumEntities;

```

These are the characteristics of this scheme:

* natural compactness of entities (albeit with possibly 1 frame latency before an entity slot can be reclaimed).
* no random re-ordering issues.
* while doubly Linked lists have O(1) insertion/deletion, but are very hard to prefetch for optimal cache latency hiding. Keeping them in a compact array allows block prefetching techniques to work nicely.
* In the case of multi-object destruction, you don't have to do redundant shift-copies to maintain order and compactness (it all gets done once during the update pass)
* You take advantage of touching data that will need to be in cache already during the update.
* It works well if your source and destination entity poitners are to separate arrays. You can then double-buffer your entity arrays in order to take advantage of multicore/ eg. one thread updating/writing the entities for frame N, while another thread is rendering the previous frame's entities for frame N-1.
* Compactness means it's easier to DMA the whole lot to a heterogenous processor for even more CPU work offloading eg. SPUs or GPUs.

# Answer
> 2 votes
Speaking in terms of my general programming experience, splicing is usually a slow operation, involving shifting all existing elements up one. I'd think **setting it to null would be the best solution here**; a dead flag would work but you'd need to take care to not let it make your code messy.

We were just actually talking about resource pooling in the chatroom though, actually. It's a very good practice, and good to hear you are doing that. :)

# Answer
> 2 votes
Personally, I would use a linked list. Iterating over a liked list is fast, as well as adding and removing items. Using an Array or Vector would be a good choice if you need direct access to items in the structure (eg. access to an index), but it doesn't sound like you need that.

Whenever you remove an item from the linked list, you could add it to a pool of objects which can then be re-cycled to save on memory-allocation.

I have used the polygonal-datastructures in several projects and have been very happy with them.

**Edit:** Sorry, I think the answer wasn't very clear in terms of removal strategy: I'd suggest to remove the item from the list, as soon as it's dead and add it directly to the *pooling-structure* (recycle). Since removing an item from a linked list is very performant, I don't see a problem in doing so.

# Answer
> 1 votes
"just set a flag on it to say "skip over me, I'm dead." I'm pooling my entities, so an Entity that is dead is quite likely to be alive again at some point"

I think you answered your own question with regards to this specific application. I would get away from arrays if you ever plan to do work on them other than push and pop. Linked lists would be a smarter way to go if you plan on doing heavy operations. With all that said, if you plan to re-integrate the same entity back into the game then it makes sense to only set a boolean variable and check for it during game operation loops.

# Answer
> 0 votes
One clean and general solution i found on a lib i used was using a lockable map.

you have 2 operations `lock()` and `unlock()`, while you iterate over the map you'll `lock()`, now from this point every operation that changes the map doesn't take effect, it just gets pushed into a `CommandQueue` that will run once you call `unlock()`.

So removing an entity would have the following pseudo-code:

```
void lockableMap::remove(std::string id) {
   if(isLocked) {
       commandQueue.add(new RemoveCommand(id));
   } else {
       //remove element from map
   }

```

and when you `unlock()`

```
isLocked = false
commandQueue.execute(this);

```

Only thing you have to consider is that you'll only remove the entity after the loop.

EDIT: this is the solution proposed by Simon.

# Answer
> 0 votes
Here's an answer I got from Liosan:
https://gamedev.stackexchange.com/a/46765/24633

# Answer
> 0 votes
I have two methods.

When you call an object to be deleted, it really sets two flags:

1.One to tell the container that an object has been deleted

2.One to tell the container which objects have been requested to be deleted

```
void object::deleteObject()
{
    container->objectHasBeenDeleted = true;
    isToDelete = true;
}

```

**One** Using a vector of objects

```
std::vector<object*> objects;

```

Then in the update function, check to see if an object has been deleted and if so iterate through all the objects and remove the ones that have a delete flag

```
void container::update()
{
    if (objectHasBeenDeleted)
    {
        std::vector<object*>::iterator ListIterator;
        for(ListIterator=objects.begin(); ListIterator!=objects.end();)
        {
            if( (*ListIterator)->isToDelete )
            {
                ListIterator = objects.erase(ListIterator);
                delete *ListIterator;
            }
            else {
                ++ListIterator;
            }
        }
    objectHasBeenDeleted = false;
    }
}

```

**Two** Using a (pointer to a) vector of objects.

```
std::vector<object*> *objects;

```

In the update function, if an object is to be deleted, iterate through the objects and add the ones that aren't to be deleted to a new vector. delete the objects vector and set the pointer to the new vector

```
void container::update()
{
    if (objectHasBeenDeleted)
    {
        std::vector<object*> *newVector;
        unsigned long i;
        for (i = 0; i < objects->size(); i++)
        {
            if (!objects->at(i)->isToDelete)
            {
                newVector->push_back(objects->at(i));
            }
        }
        delete objects;
        objects = newVector;
        objectHasBeenDeleted = false;
    }
}

```

---
Tags: game-loop
---


title: XNA - move camera over tilemap

text:
# Question
Title: XNA - move camera over tilemap
I am trying to build a game based on Advance Wars in XNA. I am so far where the tiles are placed on the screen, except here starts my problem. During the game, I ofcourse want to move the camera around over the map.

Except I got no idea on how to do this. I hope there is a way of just moving a camera around and not reposition every object on the map (thus all the tiles and units), since that is currently to only thing I might get to work, with my current knowledge.

Sorry for the short post, please let me know if I need to provide code or anything else.

# Answer
> 1 votes
there are a number of Camera Tutorials around that will show you how to go about creating a Matrix that will automatically move your camera to a position that you determine

all you then need to do is pass it to the Spritebatch and everything will work as expected

what you need to be careful with is then converting a onscreen event to a world position

http://adambruenderman.wordpress.com/2011/04/05/create-a-2d-camera-in-xna-gs-4-0/

code from article

```
public class Camera2d
{
    private const float zoomUpperLimit = 1.5f;
   private const float zoomLowerLimit = .5f;

   private float _zoom;
   private Matrix _transform;
       private Vector2 _pos;
   private float _rotation;
   private int _viewportWidth;
   private int _viewportHeight;
   private int _worldWidth;
   private int _worldHeight;

   public Camera2d(Viewport viewport, int worldWidth,
      int worldHeight, float initialZoom)
   {
      _zoom = initialZoom;
      _rotation = 0.0f;
      _pos = Vector2.Zero;
      _viewportWidth = viewport.Width;
      _viewportHeight = viewport.Height;
      _worldWidth = worldWidth;
      _worldHeight = worldHeight;
   }

   #region Properties

   public float Zoom
   {
       get { return _zoom; }
       set
       {
           _zoom = value;
           if (_zoom < zoomLowerLimit)
              _zoom = zoomLowerLimit;
           if (_zoom > zoomUpperLimit)
              _zoom = zoomUpperLimit;
       }
   }

   public float Rotation
   {
       get { return _rotation; }
       set { _rotation = value; }
   }

   public void Move(Vector2 amount)
   {
       _pos += amount;
   }

   public Vector2 Pos
   {
       get { return _pos; }
       set
       {
           float leftBarrier = (float)_viewportWidth *
                  .5f / _zoom;
           float rightBarrier = _worldWidth -
                  (float)_viewportWidth * .5f / _zoom;
       float topBarrier = _worldHeight -
                  (float)_viewportHeight * .5f / _zoom;
           float bottomBarrier = (float)_viewportHeight *
              .5f / _zoom;
       _pos = value;
       if (_pos.X < leftBarrier)
           _pos.X = leftBarrier;
       if (_pos.X > rightBarrier)
           _pos.X = rightBarrier;
       if (_pos.Y > topBarrier)
           _pos.Y = topBarrier;
       if (_pos.Y < bottomBarrier)
           _pos.Y = bottomBarrier;
    }
   }

   #endregion

   public Matrix GetTransformation()
   {
     _transform =
        Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
        Matrix.CreateRotationZ(Rotation) *
        Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
        Matrix.CreateTranslation(new Vector3(_viewportWidth * 0.5f,
            _viewportHeight * 0.5f, 0));

       return _transform;
   }
}

```

Usage

```
ScreenManager.SpriteBatch.Begin(SpriteSortMode.BackToFront,
                    null, null, null, null, null,
                    Camera.GetTransformation());

// Draw the background texture
ScreenManager.SpriteBatch.Draw(Textures["BG"],
   new Rectangle(0, 0, worldWidth, worldHeight),
   null, Color.White, 0f, Vector2.Zero, SpriteEffects.None, 1);

ScreenManager.SpriteBatch.End();

```

---
Tags: xna, c#, camera, movement
---


# Question
Title: How do I use threads together with DirectX11?
I have only found the documents on MSDN: http://msdn.microsoft.com/en-us/library/windows/desktop/ff476884(v=vs.85).aspx Although it doesn't say anything about creating them, it mentions that device is thread-safe while device context is not.

Does the framework use threads by itself (if driver supports it) when it thinks it's more optimal? Or do we have to use some external library like BOOST to play around with threads?

# Answer
You have to create the threads yourself, using your threading library of choice (boost, C++11 async, Windows threads, etc). The idea is that you will create several threads and split up your CPU rendering work amongst them. Each thread uses a D3D11 deferred context to accumulate all the D3D11 commands (state changes, draw calls, etc.) it wants to execute. Later, in your main thread, you'll use the immediate context to call each deferred context, to send those command buffers to the GPU to be rendered. The main thread should also do the `Present()` call to display the final frame on-screen.

There's a little more detail in the blog post Direct3D 11 Multithreading by Rory Driscoll:

> The basic idea behind multithreading in Direct3D 11 is that you create an immediate device context on the main thread. Then, for each thread on which you’d like to be able to render, you create a deferred context. As you can probably guess from the names, commands executed on the immediate context get executed immediately, but those on the deferred context just get saved off into a command list. You then execute the deferred command lists on the main thread using the immediate device context.

Note that the D3D11 driver may also create threads internally for its own purposes, but this is under-the-hood and has nothing to do with "multithreaded rendering" per se.
> 8 votes

---
Tags: directx11, multithreading
---


title: Multipule VBO in Opengl

text:
# Question
Title: Multipule VBO in Opengl
I have currently in my application 2 VBO one which is a streamed buffer and for the moment the other is a static buffer.

However even when the steam buffer is not bound and the static buffer is bound calling drawarray will use the data from the streamed buffer rather than the static one.

The streamed buffer is used for sprite batching and is created as followed

```
VBO = new VertexBuffer();
VBO->createBuffer(GL_ARRAY_BUFFER, m_BufferSize, GL_STREAM_DRAW);
//void VertexBuffer::createBuffer(GLenum Type, GLsizei size, GLenum usage)
// {
//  glGenBuffers(1, &m_BufferID);
//  m_size = size;
//  m_Type = Type;
//  bind();
//  glBufferData(m_Type, m_size, NULL,  usage);
//  unbind();
// }

VBO->bind();
//void bind()       {glBindBuffer(m_Type, m_BufferID);}

VBO->setBufferData(NULL, GL_STREAM_DRAW);
//void VertexBuffer::setBufferData(GLvoid* Data, GLenum usage)
// {
//  glBufferData(m_Type, m_size, Data, usage);
// }

//enable the vertex attributes for the VAO in this case vertex pos and texture are needed
glEnableVertexAttribArray((GLuint)MLRenderer::ML_ATT_VERTEXPOS);  // Vertex position
glEnableVertexAttribArray((GLuint)MLRenderer::ML_ATT_TEXTURE0); //vertex texture coord
glEnableVertexAttribArray((GLuint)MLRenderer::ML_ATT_VERTEXCOL);

glVertexAttribPointer(MLRenderer::ML_ATT_VERTEXPOS, 3, GL_FLOAT, GL_FALSE, sizeof(MLFormats::VertexPosTexCol), (GLubyte *)NULL );
glVertexAttribPointer(MLRenderer::ML_ATT_TEXTURE0, 2, GL_FLOAT, GL_FALSE, sizeof(MLFormats::VertexPosTexCol), (GLubyte*)sizeof(Vector3f));
glVertexAttribPointer(MLRenderer::ML_ATT_VERTEXCOL, 4, GL_FLOAT, GL_FALSE, sizeof(MLFormats::VertexPosTexCol), (GLubyte*)(sizeof(Vector2f) + sizeof(Vector3f)));

VBO->unbind();
//void unbind() {glBindBuffer(m_Type, 0);}

```

Rendering using that buffer is as followed

```
VBO->bind();
//lock the shader
m_shader->lock();
//apply the uniforms

m_shader->addUniform("inMVP", (MLRenderer::MLCoreGL::getOrtho()));
m_shader->addUniform("Tex1", 0);

//*INFO*
//In order for the mapping to work correctly a max limit needs to be made for the vbo
//this will then be filled with data up to a point. once the data is filled then a new
//mapped range is needed and the draw call can be made. this means only a max amount of sprites
//can be batch drawn but it meas a fixed size index buffer is possible
if (m_BufferOffset +  (count * m_spriteSize) >= m_BufferSize)
{
    //glBufferData(GL_ARRAY_BUFFER, m_BufferSize, NULL, GL_STREAM_DRAW);
    VBO->setBufferData(m_BufferSize, NULL, GL_STREAM_DRAW);
    m_BufferOffset = 0;
}

MLFormats::VertexPosTexCol* mappedData = (MLFormats::VertexPosTexCol*)VBO->mapRange(m_BufferOffset, m_BufferOffset +  (count  * m_spriteSize));

//!!!---set vertex Data----!!!

glBindTexture(GL_TEXTURE_2D, texture);
VBO->unmap();

glDrawArrays(GL_TRIANGLES, (m_BufferOffset/sizeof(MLFormats::VertexPosTexCol)), count * 6);
m_BufferOffset += (count * m_spriteSize);

VBO->unbind();
//unbind the texture
glBindTexture(GL_TEXTURE_2D, 0);

//unlock the shader
m_shader->unlock();

```

That all works no problem but its when it comes to my point sprite rendering that I get a problem.

The static buffer is created like so

```
//create a new buffer with the right size;
m_PointBuffer = new VertexBuffer();
m_PointBuffer->createBuffer(GL_ARRAY_BUFFER, sizeof(Vector3f) * 2, GL_STATIC_DRAW);
m_PointBuffer->bind();

//set the vertex attributes
glEnableVertexAttribArray((GLuint)MLRenderer::ML_ATT_VERTEXPOS);
glVertexAttribPointer(MLRenderer::ML_ATT_VERTEXPOS, 3, GL_FLOAT, GL_FALSE, sizeof(Vector3f), (GLubyte*)NULL);

//DEMO ADD A TEMP POINT
Vector3f v3[2];
v3[0] = Vector3f(400,400, 0);
v3[1] = Vector3f(300,660, 0);
m_PointBuffer->setBufferData(sizeof(Vector3f) * 2, (GLvoid*)v3, GL_STATIC_DRAW);
//void VertexBuffer::setBufferData(GLsizei size, GLvoid* Data, GLenum usage)
// {
//  glBufferData(m_Type, size, Data, usage);
// }
m_PointBuffer->unbind();

```

Then when I come to draw the point sprites

```
m_PointBuffer->bind();
m_pointSpriteShader->lock();

m_pointSpriteShader->addUniform("inMV", m_modelView);
m_pointSpriteShader->addUniform("Tex1", 0);
m_pointSpriteShader->addUniform("Size2", m_halfSize);
m_pointSpriteShader->addUniform("ProjectionMat", MLRenderer::MLCoreGL::getOrtho());

glBindTexture(GL_TEXTURE_2D, m_textureID);
glDrawArrays(GL_POINTS, 0, 2);

m_PointBuffer->unbind();

glBindTexture(GL_TEXTURE_2D, 0);

m_pointSpriteShader->unlock();

```

Im sure there is something im missing completely but at the moment I cant see what the issue is.

# Answer
Dekowta

In your case I would rewrite the draw code next way:

1. Apply shader
2. Setup uniforms
3. Bind needed buffer (**glBindBuffer**)
4. Setup attrib pointers (**glVertexAttribPointer**)
5. Do not forget to enable them (**glEnableVertexAttribArray**)
6. call **glDrawArrays**
7. disable attribs (**glDisableVertexAttribArray**)

OpenGL is a state machine and the fact that you setup vertex attribs between bind/unbind of **VBO** does not really mean that when you bind your **VBO** next time all vertex attribs will be enabled again.

Nice documentation about using Vertex Buffer Objects can be found here
> 2 votes

# Answer
As has been stated many, *many* times before, `glVertexAttribPointer` takes the buffer object that was bound to `GL_ARRAY_BUFFER` ***at the time the function is called***. Changing the `GL_ARRAY_BUFFER` binding will have no effect on rendering unless you make the `glVertexAttribPointer` calls again.
> 4 votes

---
Tags: opengl, sprites, vbo
---


title: XNA (BEPU) Physics Performance

text:
# Question
Title: XNA (BEPU) Physics Performance
Im using XNA 4.0 with the BEPU physics engine v1.2 and I have encountered some performance problems on Xbox. Im not sure if the my mesurements are an expected result of the Xbox (with alot of dynamic physics objects). ***So I wonder if anyone else thinks the numbers are fair or not?***

Here's my mesurement:

Im runing a simulation with 100 dynamic boxes and a static plane as my ground. Now this sim is multithreaded on hardware threads 1, 3, 4 and 5 (Xbox) and I see a significant perf boost because of that. However the performance of the simulation varies between 3-5.5 ms for **resting** objects on the 360. Is that not way to much or is it fair? The PC version runs the sim at about 0.7-1 ms. However that version is multithreaded over 8 cores. But it's still a very big leap.

# Answer
My fault as usually.

If you're using BEPU Physics. Be aware that some events don't check for changes before they fire, causing an internal loop, resulting in terrible performance.

In my case setting the position to the exactly same position again (wich happens in some cases) fires this kind of infinit update loop and drops performance.

This performance hit will be even more noticable on the Xbox because of the poor floating point performance.
> 1 votes

---
Tags: xna, c#, physics, xbox360
---


# Question
Title: Making character's skills and abilities as commands, good practice?
I am designing for a game that consist of characters who have unique offensive skills and other abilities such as building, repairing, etc. Players can control multiple of such characters.

I'm thinking of putting all of such skills and abilities into individual commands. A static controller would register all of these commands into a static command list. The static list would consist of all the available skills and abilities of all the characters in the game. So when a player selects one of the characters and click on a button on the UI to cast a spell or perform an ability, the View would call the static controller to fetch the desired command from the list and execute it.

What I'm not sure of however if this is a good design given that I'm building my game in Unity. I am thinking I could have made all the skills and abilities as individual components, which would then be attached to the GameObjects representing the characters in the game. Then the UI would need to *hold* the GameObject of the character and then execute the command.

What would be a better design and practice for a game that I am designing?

# Answer
## TL;DR

This answer goes a little crazy. But it's because I see you're talking about implementing your abilities as "Commands," which implies C++/Java/.NET design patterns, which implies a code-heavy approach. That approah is valid, but there's a better way. Maybe you're already doing the other way. If so, oh well. Hopefully others find it useful if that's the case.

Look at Data-Driven Approach below to cut to the chase. Get Jacob Pennock's CustomAssetUility here and read his post about it.

## Working With Unity

Like others have mentioned, traversing a list of 100-300 items is not as big a deal as you might think. So if that's an intuitive approach for you, then just do that. Optimize for brain efficiency. But the Dictionary, as @Norguard demonstrated in his answer, is the easy no-brainpower-required way to eliminate that problem since you get constant-time insertion and retrieval. You should probably use it.

In terms of making this work well within Unity, my gut tells me that one MonoBehaviour per ability is a dangerous path to go down. If any of your abilities maintain state over time a they execute, you'll need to manage that a provide a way to reset that state. Coroutines alleviate this problem, but you're still managing an IEnumerator reference on every update frame of that script, and have to absolutely make sure you have a sure-fire way to reset abilities lest incomplete and stuck-in-a-state-loop abilities quietly start screwing up the stability of your game when they go unnoticed. "Of course I'll do that!" you say, "I'm a 'Good Programmer'!". But really, you know, we're all objectively terrible programmers and even the greatest AI researchers and compiler writers screw stuff up all the time.

Of all the ways you could implement command instantiation and retrieval in Unity, I can think of two: one is fine and won't give you an aneurysm, and the other allows for ***UNBOUNDED MAGICAL CREATIVITY***. Sort of.

## Code-Centric Approach

First is a mostly-in-code approach. What I recommend is that you make each command a simple class that either inherits from a BaseCommand abtract class or implements an ICommand interface (I'm assuming for the sake of brevity that these Commands will only ever be character abilities, it's not hard to incorporate other uses). This system assumes that each command is an ICommand, has a public constructor that takes no parameters, and requires updating each frame while it is active.

Things are simpler if you use an abstract base class, but my version uses interfaces.

It's important that your MonoBehaviours encapsulate one specific behavior, or a system of closely-related behaviors. It's okay to have lots of MonoBehaviours that effectively just proxy out to plain C# classes, but if you find yourself doing too may update calls out to all sorts of different objects to the point where it's starting to look like an XNA game, then you're in serious trouble and need to change your architecture.

```
// ICommand.cs
public interface ICommand
{
    public void Execute(AbilityActivator originator, TargetingInfo targets);
    public void Update();
    public bool IsActive { get; }
}

// CommandList.cs
// Attach this to a game object in your loading screen
public static class CommandList
{
    public static ICommand GetInstance(string key)
    {
        return commandDict[key].GetRef();
    }

    static CommandListInitializerScript()
    {
        commandDict = new Dictionary<string, ICommand>() {

            { "SwordSpin", new CommandRef<SwordSpin>() },

            { "BellyRub", new CommandRef<BellyRub>() },

            { "StickyShield", new CommandRef<StickyShield>() },

            // Add more commands here
        };
    }

    private class CommandRef<T> where T : ICommand, new()
    {
        public ICommand GetNew()
        {
            return new T();
        }
    }

    private static Dictionary<string, ICommand> commandDict;
}

// AbilityActivator.cs
// Attach this to your character objects
public class AbilityActivator : MonoBehaviour
{
    List<ICommand> activeAbilities = new List<ICommand>();

    void Update()
    {
        string activatedAbility = GetActivatedAbilityThisFrame();
        if (!string.IsNullOrEmpty(acitvatedAbility))
            ICommand command = CommandList.Get(activatedAbility).GetRef();
            command.Execute(this, this.GetTargets());
            activeAbilities.Add(command);
        }

        foreach (var ability in activeAbilities) {
            ability.Update();
        }

        activeAbilities.RemoveAll(a => !a.IsActive);
    }
}

```

This works totally fine, but you can do better (also, a `List<T>` isn't the optimal data structure for storing timed abilities, you might want a `LinkedList<T>` or a `SortedDictionary<float, T>`).

## Data-Driven Approach

It's probably possible that you can reduce your ability's effects down into logical behaviors that can be parameterized. This is what Unity was really built for. You, as a programmer, design a system that then either you or a designer can go and manipulate in the editor to produce a wide variety of effects. This will great simplify the "rigging" of the code, and focus exclusively on execution of an ability. No need to juggle base classes or interfaces and generics here. It will all be purely data driven (which also simplifies initializing command instances).

The first thing you need is a ScriptableObject that can describe your abilities. ScriptableObjects are awesome. They're designed to work like MonoBehaviours in that you can set their public fields in Unity's inspector, and those changes will get serialized to disk. However, they're not attached to any object and don't have to be attached to a game object in a scene or instantiated. They are the catch-all data buckets of Unity. They can serialize basic types, enums, and simple classes (no inheritance) marked `[Serializable]`. Structs can't be serialized in Unity, and serialization is what allows you to edit the object fields in the inspector, so remember that.

Here's a ScriptableObject that tries to do a lot. You can break this out into more serialized classes and ScriptableObjects, but this is supposed to just give you an idea of how to go about doing it. Normally this looks ugly in a nice modern object oriented language like C#, since it really feels like some C89 shit with all those enums, but the real power here is that now you can create all sorts of different abilities without ever writing new code to support them. And if your first format doesn't do what you need it to do, just keep adding to it until it does. So long as you don't change field names, all your old serialized asset files will still work.

```
// CommandAbilityDescription.cs
public class CommandAbilityDecription : ScriptableObject
{

    // Identification and information
    public string displayName; // Name used for display purposes for the GUI
    // We don't need an identifier field, because this will actually be stored
    // as a file on disk and thus implicitly have its own identifier string.

    // Description of damage to targets

    // I put this enum inside the class for answer readability, but it really belongs outside, inside a namespace rather than nested inside a class
    public enum DamageType
    {
        None,
        SingleTarget,
        SingleTargetOverTime,
        Area,
        AreaOverTime,
    }

    public DamageType damageType;
    public float damage; // Can represent either insta-hit damage, or damage rate over time (depend)
    public float duration; // Used for over-time type damages, or as a delay for insta-hit damage

    // Visual FX
    public enum EffectPlacement
    {
        CenteredOnTargets,
        CenteredOnFirstTarget,
        CenteredOnCharacter,
    }

    [Serializable]
    public class AbilityVisualEffect
    {
        public EffectPlacement placement;
        public VisualEffectBehavior visualEffect;
    }

    public AbilityVisualEffect[] visualEffects;
}

// VisualEffectBehavior.cs
public abtract class VisualEffectBehavior : MonoBehaviour
{
    // When an artist makes a visual effect, they generally make a GameObject Prefab.
    // You can extend this base class to support different kinds of visual effects
    // such as particle systems, post-processing screen effects, etc.
    public virtual void PlayEffect();
}

```

You could further abstract the Damage section into a Serializable class so you could define abilities that deal damage, or heal, and have multiple damage types in one ability. The only rule is no inheritance unless you use multiple scriptable objects and reference the different complex damage configuration files on disk.

You still need the AbilityActivator MonoBehaviour, but now he does a little more work.

```
// AbilityActivator.cs
public class AbilityActivator : MonoBehaviour
{
    public void ActivateAbility(string abilityName)
    {
        var command = (CommandAbilityDescription) Resources.Load(string.Format("Abilities/{0}", abilityName));
        ProcessCommand(command);
    }

    private void ProcessCommand(CommandAbilityDescription command)
    {

        foreach (var fx in command.visualEffects) {
            fx.PlayEffect();
        }

        switch(command.damageType) {
            // yatta yatta yatta
        }

        // and so forth, whatever your needs require

        // You could even make a copy of the CommandAbilityDescription
        var myCopy = Object.Instantiate(command);

        // So you can keep track of state changes (ie: damage duration)
    }
}

```

# The COOLEST part

So the interface and generic trickery in the first approach will work fine. But in order to really get the most out of Unity, ScriptableObjects will get you where you want to be. Unity is great in that it provides a very consistent and logical environment for programmers, but also has all the data entry niceties for designers and artists you get from GameMaker, UDK, et. al.

Last month, our artist took a powerup ScriptableObject type that was supposed to define behavior for different kinds of homing missiles, combined it with an AnimationCurve and a behavior that made missiles hover along the ground, and made this crazy new spinning-hockey-puck-of-death weapon.

I still need to go back and add specific support for this behavior to make sure it's running efficiently. But because we made this generic data description interface, he was able to pull this idea out of thin air and put it into the game without us programmers even knowing he was trying to do it until he came over and said, "Hey guys, look at this cool thing!" And because it was clearly awesome, I'm excited to go add more robust support for it.
> 18 votes

# Answer
TL:DR -- if you're thinking about stuffing hundreds or thousands of abilities into a list/array that you'd then iterate through, every time there's an action called, to see if the action exists and if there's a character who can perform it, then read below.

If not, then don't worry about it.
If you're talking about 6 characters/character-types and maybe 30 abilities, then it's really not going to matter what you do, because the overhead of managing complexities might actually require more code and more processing than just dumping everything in a pile and sorting...

Which is exactly why @eBusiness suggests that you're unlikely to see performance issues during event-dispatch, because unless you're trying really hard to do so, there's not a lot of overwhelming work here, compared to transforming the position of 3-million vertices on-screen, etc...

Also, this is not *the solution*, but rather *a solution* for managing larger sets of similar issues...

But...

It all comes down to how big you're making the game, how many characters share the same skills, how many different characters/different skills there are, right?

Having the skills be components of the character, but having them register/unregister from a command-interface as characters join or leave your control (or get knocked out/etc) still makes sense, in a very StarCraft sort of way, with hotkeys and the command card.

I've had very, very little experience with Unity's scripting, but I'm very comfortable with JavaScript as a language.
If they allow it, why not have that list be a simple object:

```
// Command interface wraps this
var registered_abilities = {},

    register = function (name, callback) {
        registered_abilities[name] = callback;
    },
    unregister = function (name) {
        registered_abilities[name] = null;
    },

    call = function (name,/*arr/undef*/params) {
        var callback = registered_abilities[name];
        if (callback) { callback(params); }
    },

    public_interface = {
        register : register,
        unregister : unregister,
        call : call
    };

return public_interface;

```

And it might be used like:

```
var command_card = new CommandInterface();

// one-time setup
system.listen("register-ability",   command_card.register  );
system.listen("unregister-ability", command_card.unregister);
system.listen("use-action",         command_card.call      );

// init characters
var dave = new PlayerCharacter("Dave"); // Character Factory pulls out Dave + dependencies
dave.init();

```

Where the Dave().init function might look like:

```
// Inside of Dave class
init = function () {
    // other instance-level stuff ...

    system.notify("register-ability", "repair",  this.Repair );
    system.notify("register-ability", "science", this.Science);
},

die = function () {
    // other clean-up stuff ...

    system.notify("unregister-ability", "repair" );
    system.notify("unregister-ability", "science");
},

resurrect = function () { /* same idea as init */ };

```

If more people than just Dave have `.Repair()`, but you can guarantee that there's only going to be one Dave, then just change it to `system.notify("register-ability", "dave:repair", this.Repair);`

And call the skill by using `system.notify("use-action", "dave:repair");`

I'm not sure what the lists you're using are like. (In terms of the UnityScript type-system, AND in terms of what's going on post-compilation).

I can probably say that if you've got hundreds of skills that you were planning on just stuffing into the list (rather than registering and unregistering, based on which characters you currently have available), that iterating through a whole JS array (again, if that's what they're doing) to check a property of a class/object, which matches the name of the action you want to perform, is going to be less performant than this.

If there are more-optimized structures, then they're going to be more performant than this.

But in either case, now you have Characters who control their own actions (take it a step further and make them components/entities, if you wish), AND you have a control system which requires a minimum of iteration (as you're just doing table-lookups by name).
> 3 votes

---
Tags: unity, architecture, design-patterns
---


# Question
Title: How do I pass arguments to an XNA Game executable?
How do for example make it possible to pass an argument to the .exe file and read it in my XNA Game?

Examples:

**Enable Editor:**

```
game.exe -devmode

```

**Set Resolution:**

```
game.exe -width 1280 -height 720

```

and in the game check the arguments before starting the game. I searched for this earlier and thought about it again but found nothing about it.

# Answer
> 11 votes
At the end of the day, XNA games are just regular .NET applications.

Read the docs on Main() and args.

You can also use `System.Environment.GetCommandLineArgs` (link).

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


title: Timestep in multiplayer game

text:
# Question
Title: Timestep in multiplayer game
I'm trying to wrap my brain around the concept of creating a server/client multiplayer experience.

My problem is mainly related to timestep. Consider the following scenario:

A client connects to a server. The client sends his inputs to the server to indicate he wants to move. Server simulates the input and determines the position of that client in the game world.

Since the client and the server are both running on different timesteps, how do you accurately simulate so that all clients are in sync with the server? My server is currently set at at 30ms timestep. When I process client movements, there are potentially hundreds of requests waiting to be processed, yet no way to indicate how long it took between each one of the requests.

I'm really not grasping how to properly simulate on the server based on time, in order to have everything sync up.

# Answer
> 3 votes
Simply put, you need to send a time-stamp with each snapshot from the server, and with each input from the client.

On both ends you need a process to "fill in" any frames where packets are not received.

In my game (a fast-paced action game - yours may be different), on the server, I discard any "older" (out-of-order) input, and simply guess that if no new input packets arrive, the same buttons just keep being held down (there's a bit more stuff for making sure short button presses/releases are handled, but that's the basic premise).

On the client I keep a "lag buffer" (described in this article that Tetrad linked). I use a rolling average of arrival times to ensure that the lag buffer stays the right length - making the client game run a bit slower or faster to catch up. If snapshots don't arrive in time then I do extrapolation on the client. Otherwise I interpolate between snapshots in the buffer.

The client is also responsible for tracking the round-trip-time for inputs and using that for prediction (the server sends back the timestamp of the input that it used when calculating a given frame). It buffers inputs for that length of time, replaying them to take the player's position from the "old" position (in the snapshot from the server) to the predicted "present" position.

Basically the server just keeps running at a fixed frame rate. It is up to the clients stay synchronised with the server.

Of course, this is just a high-level overview. There's a *lot* of nitty-gritty details that you have to figure out when you implement it.

---
Tags: xna, c#, multiplayer, timestep
---


# Question
Title: Per color collision is really expensive - can my approach be improved?
I've been working on adding a color based collision component which takes a list of colors and checks to see if an object is colliding with any of them. However, the operation seems to be extremely expensive, even though I am only colliding 2 objects. I think something is wrong with my TestCollision method but, I can't find the error.

```
    public List<Color> Colors = new List<Color>();
    private Texture2D _texture;
    public Texture2D Texture
    {
        get { return _texture; }
        set
        {
            _texture = value;
            ColorData = _texture.GetData();
        }
    }
    public Color[,] ColorData { get; private set; }

    public PerColorCollision(Entity e, string name) : base(e, name)
    {
        ColorsColliedWith = new List<Color>();
    }

    public PerColorCollision(Entity e, string name, Texture2D texture) : base(e, name)
    {
        Texture = texture;
        ColorsColliedWith = new List<Color>();
    }

    public List<Color> ColorsColliedWith { get; private set; }

      public override bool TestCollision(Entity e)
    {

        if (BoundingBox.Intersects(e.GetComponent<Collision>().BoundingBox))
        {
            PerColorCollision ppc = e.GetComponent<PerColorCollision>();

            //Get the area of intersection
            var intersection = new Rectangle();
            intersection.Y = Math.Max(BoundingBox.Top, ppc.BoundingBox.Top);
            intersection.Height = Math.Min(BoundingBox.Bottom, ppc.BoundingBox.Bottom) -
                                  intersection.Y;
            intersection.X = Math.Max(BoundingBox.Left, ppc.BoundingBox.Left);
            intersection.Width = Math.Min(BoundingBox.Right, ppc.BoundingBox.Right) -
                                 intersection.X;

            foreach (var color in Colors)
            {
                for (int y = intersection.Y; y < intersection.Bottom; y++)
                {
                    for (int x = intersection.X; x < intersection.Right; x++)
                    {
                        //We subtract our bounding boxes to set the position back to relative, since the area of intersection would be the at the absolute positions
                        Color color1 = ColorData[(x - BoundingBox.Left), (y - BoundingBox.Top)];
                        Color color2 =
                            ppc.ColorData[
                                (x - ppc.BoundingBox.Left),
                                (y - ppc.BoundingBox.Top)];
                        if (color1.A != 0 && color2 == color)
                        {
                            ColorsColliedWith.Add(color);
                            break;
                        }
                    }
                    if (ColorsColliedWith.Contains(color))
                        break;
                }
            }
        }

        if (ColorsColliedWith.Count > 0)
            return true;
        return false;
    }

    public override void Update()
    {
        ColorsColliedWith.Clear();
        base.Update();
    }

```

In the base.Update it runs the TestCollision method against all of the partners in Collision.Partners. Is there any other optimization that I can do?

# Answer
Color based per pixel collision *is* very expensive, but I assume you have a good reason for not going for something like combining 2d boxes/circles or SAT which can only do convex shapes.

The main things you can do to speed things up are lessening your number checks and/or lessening the time a check takes. The former you've already done about as well as you can for per pixel collision so we'll focus on the latter.

Currently for an intersected area, you make a check for the intersecting width * the intersecting height * the number of individual colors being checked for. Even with only a couple objects to check collision between, that's going to add up very fast.

The first thing would be to greatly reduce the GetComponent's called. As is you're getting three things from your Entity *every pixel* a number of times equal to the number of colors you're checking for! Pulling out of an array is quick, like you're doing with color1, but when you have to go get the array, left, and top every time you're going to find yourself burning a lot of unnecessary cycles. Unless the component is moving while you are in this loop, you know the left and top of the bounding box will remain constant. The array also shouldn't change unless the sprite is changing on another thread somehow while you're in this loop. Instead of getting them every time, get them at the top and store them in variables, then use those variables to get color 2 just like how you're doing for color1.

At this point you should test your code out again as this is probably going to be your biggest gain. However, there is always more optimization you can do. What really matters is how much you need, but if at this point the collision is not acceptable for your needs, then continue on down.

One very quick thing that may or may not gain you much is the Contains check you are doing once per row. Contains isn't the most optimal way to early out of the second loop, considering any situation that triggers the break in the inner loop will trigger the outer and that's the only place it changes within. It will only ever (in this function anyway) get one thing added to it before it breaks out so it shouldn't really be too costly. But if you've got more things in it, doing that repeatedly is going to add up somewhat. You can probably replace it with something as simple as a boolean you turn true when you find a match should you want to/have no reason not to axe it.

From here there are other things you can do, but they start to get to be more of a pain to implement. Other areas to look at would be stopping checking colors themselves, thus bringing 4 compares down to 1; and/or limiting yourself to a finite pallet (allowing you to pull various constant time shenanigans).

If you were to have something like a 256 color pallet for instance, you could store a second array of the sprite with which of those 256 indices it's color falls on. Each one would be a single byte keeping the size fairly small. From there you'd just have to do what you're currently doing with that array instead of the actual colors, which would keep you from having to check the RGBA values independently.

If you wanted to do this without giving up color variations, you could use a method to hash the RGBA values down to a total 0-255. While each number in that case would represent a range of colors instead of a single one, depending on your needs such may prove sufficient.

If you could get your number of discrete colors for purposes of collision down to something like 32 or 64, you could even use bit flags to check for all the colors you're looking for in a single check no matter how many you seek...

In all these cases keep in mind that **you should only optimize until it works sufficiently for your purposes**. There will nearly always be more you can do to optimize, given what tradeoffs you're willing to make. Such is a trap to be avoided, as you usually get diminishing returns quickly. If you use System.Diagnostics.Stopwatch you can time sections of your code which is excellent for figuring out what part of your code is *actually* causing issue. Few things are worse than spending a bunch of time and heartache making a section run really tight only to find that it still has to wait on other bottlenecks which are taking far longer.
> 3 votes

# Answer
Your worst case test at the moment is where there's no collision at all, so I'd concentrate on that first. For example maybe you know from your map data approximately where the edge of the road is and can test to see if you're close to the edge without looking at pixels? Maybe if all 4 corners of the car are on the road then you don't need to test the rest of it?

I suspect nesting those loops differently will help significantly in many cases too. Most notably if you're colliding with the last colour in the array then you'll have to check the whole rectangle several times to find that out currently. Moving the outer loop round the colours to be the inner loop would speed things up significantly there.

You also may (or may not) find that swapping the nesting of the x and y loops will help. I'm not sure what the memory layout of arrays in C# is, so you'll have to profile to see which is best.

You could also pre-process the car sprites to find a reduced bounding box that only covers the opaque pixels.
> 0 votes

---
Tags: xna, collision-detection, xna-4.0
---


# Question
Title: Mapped texture to a gluSphere not wrapping correctly
I have a 3D sphere rendered using **JOGL** by means of `GLUquadric`. I'm trying to add a texture but it is not rendering as correctly.

Does anyone understand why the texture (upper-right of sphere) isnt being wrapped, nor repeated around the rest of the sphere?

# Answer
Really bad UV coordinates.

If two vertices use the SAME uv coordinate, the final color will be the same between both vertices, because they sample the same texel in the texture.

I suggest you check out the gluQuadricTexture function.
> 3 votes

---
Tags: java, rendering, jogl
---