# Question
Title: How can I stop looking for keyboard input for a length of time?
I'm pretty new to programming, and even newer to C# and XNA. I currently call a method that looks for keyboard input in my Update method. This method has if statements for doing what needs to be done when a key has been pressed. The problem is, since it's being called constantly, it's impossible to press a key quickly enough for it to register only once.

One issue this creates is going through a menu. A short tap of a key sends the "cursor" that indicates which menu item is selected wheeling through the menu several times. I'd like to be able to "turn off" keyboard input for perhaps a fourth of a second after any valid key has been pressed.

# Answer
What you're trying to do is simple to solve without having to resort to doing any timing on the input (in fact I recommend you *not* to do so in this case - timing is more useful for scenarios such as limiting the firing rate of a spaceship).

If you want for only the initial press of the key to be registered, the way it's usually done is:

1. Keep track of *both* the current and the previous frame's keyboard state.
2. Detect a key press by checking if the key is **down in the current frame** but was **up on the previous frame**.

Code example:

```
private KeyboardState _currentKeyboardState;
private KeyboardState _previousKeyboardState;

public void Update(GameTime elapsed)
{
    // Before handling input
    _currentKeyboardState = Keyboard.GetState();

    if(_currentKeyboardState.IsKeyDown(Keys.Down) &&
       _previousKeyboardState.IsKeyUp(Keys.Down))
    {
        // Handle key press of the down key
    }

    // <Handle other keys here>

    // After handling input
    _previousKeyboardState = _currentKeyboardState;
}

```

Personally, I like to wrap this up in some separate `InputManager` class and provide methods such as `IsKeyDown(key)` versus `OnKeyPress(key)` to distinguish both scenarios clearly.
> 19 votes

# Answer
David pretty much summed it up entirely. However, if you are interested I attached at the end a condensed version of what I use. It's just a game component you can add to the game with Components.Add() then call to check if buttons were just pressed, released, or are currently down. You can just throw it directly in your project (you might want to change the namespace though). If you need help/an explanation let me know. Happy coding.

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

namespace XNAGenericsLibrary
{
    public class InputHandler : Microsoft.Xna.Framework.GameComponent
    {
        #region Field Region

        static KeyboardState keyboardState;
        static KeyboardState lastKeyboardState;
        static GamePadState[] gamePadState;
        static GamePadState[] lastGamePadState;

        #endregion

        #region Property Region

        public static KeyboardState KeyboardState
        {
            get { return keyboardState; }
        }

        public static KeyboardState LastKeyboardState
        {
            get { return lastKeyboardState; }
        }

        public static GamePadState[] GamePadStates
        {
            get { return gamePadState; }
        }

        public static GamePadState[] LastGamePadStates
        {
            get { return lastGamePadState; }
        }

        #endregion

        #region Constructor Region

        public InputHandler(Game game)
            : base(game)
        {
            keyboardState = Keyboard.GetState();

            gamePadState = new GamePadState[EnumMethods.GetValuesArray<PlayerIndex>().Length];
            foreach (PlayerIndex index in EnumMethods.GetValuesArray<PlayerIndex>())
                gamePadState[(int)index] = GamePad.GetState(index);
        }

        #endregion

        #region XNA methods

        public override void Update(GameTime gameTime)
        {
            lastKeyboardState = keyboardState;
            keyboardState = Keyboard.GetState();

            lastGamePadState = (GamePadState[])gamePadState.Clone();
            foreach (PlayerIndex index in EnumMethods.GetValuesArray<PlayerIndex>())
                gamePadState[(int)index] = GamePad.GetState(index);

            base.Update(gameTime);
        }

        #endregion

        #region Keyboard Region

        public static bool KeyboardPressed(Keys key)
        {
            return (keyboardState.IsKeyDown(key) && lastKeyboardState.IsKeyUp(key));
        }

        public static bool KeyboardReleased(Keys key)
        {
            return (keyboardState.IsKeyUp(key) && lastKeyboardState.IsKeyDown(key));
        }

        public static bool KeyboardDown(Keys key)
        {
            return keyboardState.IsKeyDown(key);
        }

        #endregion

        #region GamePad Region

        public static bool GamePadButtonPressed(Buttons button, PlayerIndex index)
        {
            return (gamePadState[(int)index].IsButtonDown(button) && lastGamePadState[(int)index].IsButtonUp(button));
        }

        public static bool GamePadButtonReleased(Buttons button, PlayerIndex index)
        {
            return (gamePadState[(int)index].IsButtonUp(button) && lastGamePadState[(int)index].IsButtonDown(button));
        }

        public static bool GamePadButtonDown(Buttons button, PlayerIndex index)
        {
            return gamePadState[(int)index].IsButtonDown(button);
        }

        #endregion
    }

    class EnumMethods
    {
        public static T[] GetValuesArray<T>()
        {
            return (typeof(T).GetFields(BindingFlags.Static | BindingFlags.Public).Select(x => (T)x.GetValue(null))).ToArray<T>();
        }
    }
}

```

EDIT- By the way, this works with the XBox 360 which uses the Compact Framework. If targeting the PC you can replace calls to EnumMethods.GetValuesArray() with Enum.GetValues(), which would probably be more efficient.
> 4 votes

# Answer
To answer your question (`for a length of time?`), there's a simple way to do this

Just use something like

```
int framesPassed = 0;
public override void Update(GameTime gameTime) {
     if (framesPassed > 30) {
          framesPassed = 0;
          doYourStuff();
     }
     framesPassed++;
}

```

which will ensure that you'll call `doYourStuff()` after 30 frames pass.

If you really need to do something after X (5) seconds, I'd recommend you to do something like this

```
double secondsPassed = 0.0;
public override void Update(GameTime gameTime) {
     secondsPassed += gameTime.ElapsedGameTime.TotalSeconds;
     if (secondsPassed > 5.0) {
          secondsPassed -= 5.0;
          doYourStuff();
     }
}

```
> 2 votes

---
Tags: xna, c#, input, keyboard
---


title: Where does touch control logic go?

text:
# Question
Title: Where does touch control logic go?
I'm creating a game (or app, depending on how you would define it...) where I'm moving objects (with sprites) on the screen.

I've got this to half-work in both scenarios, but I can't seem to get it to work completely using only one...

My problem is, I don't know where the touches should be handled for the objects. I have a separate layer that has all the objects on that layer. I put all the touch logic on that layer and it works fine, but I can only move 1 object at a time (I have to declare a currentObject variable to keep track of what is moving) and I don't know how to see if a touch is handled on the layer without a currentObject variable. Here's my touch began method:

```
-(BOOL)ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event{
       BOOL isTouchHandled = CGRectContainsBorder([current.sprite boundingBox], lastTouchLocation);

       return isTouchHandled;
}

```

I also tried to have all the touch control in the objects itself, which let me move all the objects separately, but I couldn't have the objects react to any of the layer variables or events (I can't figure out how to get the objects to see what the current states are of the variables on the layer). the code for that touch began is:

```
-(BOOL)ccTouchBegan:(UITouch*)touch withEvent:(UIEvent*)event{
       BOOL isTouchHandled = CGRectContainsBorder([sprite boundingBox], lastTouchLocation);

       return isTouchHandled;
}

```

The only difference between them is that the layer is accessing the instance variable of the object, and the object accesses its own variable.

*Note: these functions aren't being implemented at the same time, I'm trying one and seeing if it works and then trying the other and seeing if it works...*

So, how could I fix this? Is there a way to be able to move all the objects independently? I have events that moving the objects react to once the move over a certain point, but I want the objects to be able to be moved after all the events happen as well and I can either get them to react to the events and move the current to the next object (control of touch is on the layer) or I can move all the objects independently but I can't access the layer's events (control is with the object)...

# Answer
It depends on what you want to do... if the user should be able to move one object at a time, it should be sufficient to find the closest object and move that upon movement.

If you need to handle multiple touches, you should first and foremost set:

```
// put this in your AppDelegate's applicationDidFinishLaunching* method
[glView setMultipleTouchEnabled:YES];

```

In any case you might also want to implement your own `ccTouchMoved` instead of just `ccTouchBegan`, to keep track of movement. The cocos2d documentation has a nice summary of the touch delegates and the available methods.

**Update:** Just FYI: You can implement the touch controls in a separate class by implementing the `CCStandardTouchDelegate` or `CCTargetedTouchDelegate` protocol and add it as delegate to the `CCTouchDispatcher`. This way you can decouple your input logic from your display classes.. so maybe the input handler would know about the layer and the sprites, but layer and sprites won't know about the input handler. This will make up for a cleaner architecture and less cluttered classes.
> 1 votes

---
Tags: cocos2d-iphone, ios, touch
---


title: MMO Collision detection

text:
# Question
Title: MMO Collision detection
I am building a MMO game server for a 2D game and am currently implementing the collision detection, and I am would like to know what I should do.

Lets say I have 1000 players playing and 10,000 objects, should I just iterate over them all to determine if colliding? This seems a bit pricey.

I could separating the world into chunks and iterating every object for each player in it's chunk.

I would like to know some other ideas or what is standard. What's the best way for a MMO server to handle collision detection with `static objects`?

# Answer
1. The world being **separated into chunks** is indeed the first step you should take, with each chunk being handled separatedly.
2. **Static objects**? Purely static in the sense that they never move, and never disappear? Then you could simply **incorporate these objects into whatever data structure you're using for player navigation** in the world (such as a grid, navigation mesh or visibility graph). No need for doing any individual collision detection. This could be done manually by the designers, or automatically by the engine as a preprocessing step of the content pipeline.
3. If on the other hand you'd like to actually perform collision detection between **dynamic entities** inside each chunk, depending on the expected amount of simultanous entities you might benefit from **using a spatial partitioning data structure** (such as a quadtree or a grid) to reduce the amount of entities that need to be iterated. In general, research the broader topic of *broad-phase collision detection* (no pun intended) which includes the aforementioned spatial division techniques as well as other approaches such as sweep and prune.
> 14 votes

---
Tags: collision-detection, mmo, server
---


title: Analytics in an Offline Game

text:
# Question
Title: Analytics in an Offline Game
I'm attempting to program an offline puzzle game in C++. I'm trying to figure out the best way (particularly during the alpha) to report back to me

* Whether people finish the level
* Where people died
* How long they took on the level
* The current version that they are playing

I don't currently have a public database server which I could dump it in to.

Is there any already written libraries that (for instance) drop analytics into a Google App Engine Database or Google Docs Spreadsheet?

What approach (if any) have you used for storing analytics?

# Answer
I don't personally know of any libraries/services but I would say first search Google. A search for "game analytics" gave http://gameanalytics.com/ as a promising first result. That being said, my thought would be to register for a free server account. Then put a small script on it to accept calls to a page that would save whatever data is given to it. So, you could have a page that would accept

* Client version
* Level number
* Array of locations died at
* If level completed
* Time taken to finish
* Security key to prevent falsified reports (such as a MD5 of a combination of the dynamic numerical data)
* Any other needed data

You could also save each report locally then send them in batches when the user wants to. That way they can see that it accesses the internet only when sending those reports. Given that this would be purely opt-in, I doubt many would try to reverse engineer and send false reports. Then the server script could store the reports in a MySQL database that you could sort, search, and create analytics reports from. Or, you could just pay for a more robust and secure service specifically designed for this. Again, I suggest searching Google.
> 1 votes

# Answer
While Google Analytics are more well-known for tracking websites, if you are creating mobile games in Android or iOS, there is also Google Analytics for Android and iOS native applications. Another alternative is Flurry. Both offers free analytic tool.
> 0 votes

---
Tags: c++, google-app-engine, analytics
---


# Question
Title: Determining the X, Y co-ordinates in sprite sheets
I am new to Android COCOS2D and developing a simple game to start with. I am developing a game for kids in which the kids shall spell out the names of the fruits they select. I have developed the sprite sheet consisting of pictures of several fruits. Kindly tell me how will the fruit on which the kid taps will get selected. How are the x and y co-ordinates in the sprite sheet determined??

I shall be thankful in case anyone can help me out with this. Thanks in advance

# Answer
> 1 votes
Depends on your spritesheet and how you'd like to refer to each sprite.

**Horizontal Strip, Evenly Spaced**

```
[0][1][2][3][4][5][6][7][8]

```

Coordinates for tile corresponding to position `N`:

```
X = N * TileWidth
Y = 0

```

**Grid, Evenly Spaced, Single Index**

```
[0][1][2]
[3][4][5]
[6][7][8]

```

Coordinates for tile corresponding to position `N`:

```
X = (N % Cols) * TileWidth
Y = floor(N / Cols) * TileHeight

```

In this example `Cols` equals 3.

**Grid, Evenly Spaced, Double Index**

```
[0,0][1,0][2,0]
[0,1][1,1][2,1]
[0,2][1,2][2,2]

```

Coordinates for tile corresponding to position `NX` and `NY`:

```
X = NX * TileWidth
Y = NY * TileHeight

```

**Irregular Sprite Sheet**

Store rectangle regions of each sprite in a seperate file. E.g.

```
0 0 30 60      // First sprite at (0,0) with size (30,60)
30 0 100 60    // Second sprite at (30,0) with size (100,60)
0 60 130 60    // Third sprite at (0,60) with size (130,60)

```

---
Tags: android, cocos2d
---


# Question
Title: How to make a Realtime 3D Eulerian Fluid Simulation like "From Dust" in C#/Unity3D?
So, for a game project I'm going to be working on I need to make a fully working 3D fluid simulator in Unity3D using C#, that can work in real time.

The only problem is, I've never done anything like fluid simulation. I've been doing tons of research on it, and I think a Eulerian based fluid simulator would fit my needs best (just like this).

Basically what I need is something that can react to changing terrain and move realistically.

The people that made that simulator have a research paper online, and I've read through it. I understand the basics, but I have no idea how I could get that in to C# or Unity3D. So I was wondering if any of you could help me, either by linking to other fluid-simulators where the code is open source, so I can pick it apart and change it to my needs, or by giving me tips on where to start/what I would need to do.

I've spent hours looking online for fluid simulators, but haven't found a single one programmed in C# as of yet, I have a program that can convert C++ to C#, but I don't understand C++ well enough to know where to put the scripts in Unity once they're converted.

Any help at all would be extremely appreciated, I'm really interested in teaching myself how to make this system, but I just have no clue where I should start, or what has already been done that I could build off of.

# Answer
Disclaimer: I haven't heard of a paper describing how *From Dust* was done, so this is entirely guess-work.

A few things I noticed about *From Dust*:

* Anything on the landscape is a fluid (notice what happens when you drop a lot of sand at once) - everything just has different viscosities.
* You never get overhangs (at least on my computer) - this would be a cliff in terms of landscape.

This means that it isn't a proper 3D fluid simulation (I doubt you could do a 3D one in realtime at that scale) - I did some research into the topic myself a while back and pretty-much every post/article/paper I came across dealt with accurate 3D fluid dynamics: you just don't need this.

If was to actually implement this I would do the following:

* A large amount of particles. These would have to be simulated on the GPU - in order and not simultaneously (so first landscape and then water). Each simulation would be aware of the result of the previous one, so in your first run landscape would be aware of nothing and water aware of landscape. During any subsequent run landscape would be aware of water and water would be aware of landscape. This means the landscape would erode one frame behind, *but the user won't notice it anyway.*
    + The simulation for each is quite simple: particles avoid each other and react to gravity. They can never fall below the particles of the previous simulation (e.g. water particles can't go under landscape). Their viscosity determines the springiness between particles of the same type.
* Create a rough surface with marching cubes (these would be relatively big).
* Use a geometry shader and NURBS to smooth out the geometry on the GPU.
* In both physics and mesh generation skip processing particles that are under the current surface.
* If two particles settle (stop moving) close to each other combine them into one bigger one.

You could also do a full 3D fluid dynamic simulation, but at a much lower resolution than the level and use marching cubes to generate the mesh; and then NURBS to smooth it out. Alternatively:

* Possibly have a quad-tree-like structure of simulations.
* If one system becomes to complex create a split in the structure. Essentially you want something like a gamut alarm; but for fluid dynamics.
* If the user interacts with an area create a split in the structure.
* If one of the systems stabilizes merge it into it's parent.
* You could also tie the simulation accuracy to the camera position - but it might result in odd scenarios. Alternatively if you start running out of bandwidth you could start merging the simulation furthest from the camera.

This might get you close to what you want - but I never tackled it because I didn't have a concept to back the technology; and it's no small under-taking.

Finally, remember that once you get past the fluid simulation *From Dust* is a really simple game - I don't think they had much bandwidth left after implementing the technology.
> 6 votes

# Answer
How detailed of water are you looking for? Also what scale are we talking about?

If you need realtime water I suggest a much simpler approach which I'm going to dub the Minecraft approach. Basically partition your grid into very small blocks (this depends on the scale of the game). Every update check if the water is the same height as the surrounding 9 blocks. If it is not then talk to the other 9 blocks, divide them equally, and set the new water level from that new average.

This is iterative meaning that it doesn't work instantly but gradually over time - which as you may have seen from Minecraft actually makes it more realistic because it looks like it flows.
> 0 votes

---
Tags: c#, unity, water, euler-method
---


# Question
Title: Designing first game, deciding which language to use
Looking to make my first basic game (maybe some platformer) but haven't got across the "which language" barrier yet and hoping to get a few tips.

I have basic knowledge of C++ and classes and can pass by with PHP. Did a tad bit with Java but not much past basic stuff that's shared in C and made a few goodies in Visual Basic, but nothing special.

Based on what I know, I felt C++ would be my ideal choice to write a game in since I have the most experience with it and can learn the rest of the language as I go. But every site I've read on this topic say "DO NOT USE C++" because of the complexity of the language. I've read that Python is a good language to use for games and it's similarity with PHP would help me start off. Never made anything in Python before and was wondering if the effort would be worth it.

Based on this, what tips would you give me?

Thanks for any help, I'll appreciate it!

# Answer
> 5 votes
It all depends on your aims and skills.

I would argue that the language is not the major choice... The engine/framework is. You can write your own (largest game companies do just that). There are many already available.

But keep in mind that very few major games are not written at least partly in C/C++ or similar. The company I worked for was doing AAA titles for console PC and mobile (and on occasions for Mac).

I can attest that C and C++ are prominently used. Even for Microsoft's platforms where the common mortals have access only to higher level APIs large companies are given access to C/C++ APIs.

Although not everything is necessarily written in C/C++. Some platform specific functions are only available from another language, so some of that is always present. LUA is used a lot (as a script language), Python ends up being used in the pipeline and to a lesser extent in games (I haven't personally encountered such code but I heard they had python scripts in some games).

So the choice is yours. Do you feel you want to invest in learning a major language (Although not the nicest or cleanest to use)? Or do you want to start making games quickly?

* If you are OK doing memory management and being careful with your code go with C++
* If you want to leave some of the memory management and keep most of the portability of the language, go with C++ and smart pointers. Remember to make good use of STL and BOOST.
* If you want to get a game or two on one major platform choose the platform you think is the best for you and you will probably find tools and resources to guide you.
* If you simply want to make a game for fun and maybe release it at some point in time chose a language you are comfy with, find the libraries and engines that will help you with the low level stuff and go for it.
* If you want a fast way to develop games without too much programming there are many game engines and game kits available.

Wherever you use C, C++, C#, Java or Python... you will have a lot of to do if you don't use any game engine, framework or libraries. Therefore you could have a look at Ogre, SlimDX, Unity...

Whatever you choose remember to use a source control system for your code... I have never benefited from a tool more than from that. I would recommend GIT as you don't need to setup a server but you can if you need to do so later down the road. Take the time to properly setup a branching strategy or integrate the branching model from nvie.

Also remember about licensing. If your game is ever to be released you should be careful about the libraries you chose to use. Sometimes it's better to use commercial libs sometimes not.

**Edit**: Someone said: "There are only two kinds of programming languages: those people always bitch about and those nobody uses."

# Answer
> 3 votes
I would recommend C# and the XNA framework. The language is very similar to C++ but far simpler to use and a good place to start learning, also it's similar to Java which you say you've used.

Even if you haven't, I'd actually recommend C# as one of the best first languages to learn because of its simplicity, automatic garbage collection and tendancy to call in-built functions very self explanatory things.

XNA is a game framework that could be described as 'beginners DirectX' and is a good introduction to the ideas such as the update and draw cycles that are common to almost all games.

C# and XNA go hand in hand.

There are good tutorials here: http://www.riemers.net/

# Answer
> 1 votes
If you have only a basic knowledge of C++, I don't think that's going to be enough to (easily) develop something like a platformer. Python is an easy to learn language so it's not a bad choice at all.

If you pick C++ I recommend you use SFML for graphics and sound, and either Box2D or Chipmunk for physics, if you want such a thing. If you do pick Python have a look at Pygame (graphics) and Pymunk (physics).

But developing a platformer isn't exactly easy; you might want to start with something easier, like an adventure game (where you only click around the screen and you don't have to worry about complex character interactions).

# Answer
> 1 votes
I agree mostly with Asher, XNA is ... was a good language to learn on and C# is very intuitive and far easier to work with than C++. C# and Java are incredibly similar, so you'll feel something familiar there. What you know in C++ can be applied to C#, you just have to forget about all the annoying and confusing stuff :) But if you are going to learn a framework, just start learning SlimDX, I've recently given up on XNA because well... it's based upon DX9, an aging framework, and it looks like XNA has reached the end of the road. It cannot run DX10/11 under the hood, and that's what you want to be using. That is current technology. Using SlimDX is incredibly similar to using XNA but it is far more powerful and you know you are learning current technology.

# Answer
> 0 votes
I know your asking about language, but I would really have to say that it doesn't matter. Unless you really know your going to be hitting some performance barrier, need a certain level of portability, or really know what your doing.

If you want to learn how to make games, then I would recommend this book, it will have you up and running in no time what so ever. Beginning Game Development with Python and Pygame

However, if you want to combine this learning with sharpening your c++ skills, then maybe that would make a decent choice. It depends what you want to learn. How to make a game, or how to make a game in a certain language.

You really shouldn't find python any more effort to learn than any other language. And it's not like your switching to functional programming or anything, it's all the same. Just not as much memory management.

---
Tags: c++, python
---


title: Multiplayer API with Unity 3.5 and AS3

text:
# Question
Title: Multiplayer API with Unity 3.5 and AS3
On the faq for the current preview release, http://unity3d.com/unity/preview/faq it says that while networking is not currently supported for flash compilation, we can write our own in AS3 using the Flash API. I can't seem to find the docs for this API or figure out the right way to work in both AS3 and Unity. Can anyone point me in the right direction?

# Answer
> 1 votes
Take a look at http://playerio.com/. Very nice and relatively easy network multiplayer library with both flash and unity support.

# Answer
> 0 votes
Here's a link to a thread on the Unity3D forums, where some progress seems to be being made towards the end:

http://forum.unity3d.com/threads/116650-UnityShared.swc-Communicating-between-Unity-Flash-Content-and-AS3.

# Answer
> -2 votes
I'm having the same issue I'm currently creating a wrapper class for Scoreoid follow are blog I hope to have it done today.

About Scoreoid - http://www.scoreoid.net/ Scoreoid, developed by game developers for game developers, is a non-restrictive, reliable and easy to use gaming platform designed to handle but not limited to scoring, leaderboards and game management, including advanced functions such as platform content awareness, for multi-platform games.

Almog

---
Tags: flash, unity, networking, actionscript-3, actionscript
---


# Question
Title: How do I simulate the mouse and keyboard using C# or C++?
I want to start develop for Kinect, but hardest theme for it - how to send keyboard and mouse input to any application. In previous question I got an advice to develop my own driver for this devices, but this will take a while.

I imagine application like a gate, that can translate SendMessage's into system wide input or driver application with API to send this inputs. So I wonder, is there are drivers or simulators that can interact with C# or C++?

Small edition: SendMessage, PostMessage, keybd\_event will work only on Windows application with common messages loop. So I need driver application that will work on low, kernel, level.

# Answer
For a C# Application:

To move the mouse, the Cursor class is our friend, as Cursor.Position can be used to move the mouse.

To simulate key-presses, The Sendkeys class is your friend, with SendKeys.Send() being used to simulate a keyboard press

For clicking the mouse, I know of no nice wrappers, but this code should work:

```
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);

public const int MOUSEEVENTF_LEFTDOWN = 0x02;
public const int MOUSEEVENTF_LEFTUP = 0x04;
public const int MOUSEEVENTF_RIGHTDOWN = 0x08;
public const int MOUSEEVENTF_RIGHTUP = 0x10;

public void MouseClick()
{
mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0);
mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0);
}

```

*(Just replace x and y with the actual mouse position, perhaps using the Cursor class again)*

Alternatively, you can use something like the Global Mouse and Keyboard Library from CodeProject for a simple and clean interface to the whole process
> 2 votes

# Answer
What you need is to create a system driver for a human interface device, HID. The previous advice to create a driver is correct because, as you noticed, you can't simply go stuffing events into higher level systems and get universal coverage.

You may want to start here: enter link description here and then continue looking around MSDN for driver samples to base your work from.
> 2 votes

# Answer
Well, the best way to do such thing is to create your own keyboard/mouse driver using WDK. It's accurate and good looking solution, but it will take a lot of time if you're novice in programming.

Other solution is to use GlovePIE. You can write down your own script and then use it. So then you'll need to send message with your applicaton to GlovePIEand it will generate input on Kernel level, so this will work in DirectX games and message loop applications.

Well, really I want something like this, but with possibility to run as background process (GlovePIE start with window mode and then you can turn it) or maybe as library. If I found something else, I'll update answer.
> 1 votes

---
Tags: input, simulations, mouse, keyboard, kinect
---


# Question
Title: How do games using physic engines for 2d games handle platform corners?
I have seen games like latest "2'5D" sonics that handle collision detection at platform corners pretty well. The problem I'm having is that my game uses an ellipsoid as my player's body to let it move on slopes, etc... But when it gets close to the end of a platform (which has a rectangular collider) the collision is not correct because the player collider is not rectangular too.

How do they do collision on the edges to get an smooth movement and don't seem like the player is falling through the edge?.

# Answer
I haven't actually done this myself, but I would assume that most games 1) don't actually use physics simulations for the player himself, instead preferring to control him manually to get the exact feeling down and 2) I would guess the collision is handled by a ray instead of a oval.

If you have just a single point you're testing at the player's feet then you can avoid the issue of going off corners, but still be able to work on slopes properly.

Somewhat unrelated, but worth sharing: tuning Canabalt (includes talking about how their collision detection works).
> 1 votes

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


# Question
Title: 2D platformer multiple rectangle collision cause jitter
I posted this question two weeks ago: 2D platformer corner collision and I implemented NoobsArePeople2's solution.

Problem is, when player intersects two rectangles that are inside each other, he starts jittering. I don't know how to describe it so I made a video: http://www.youtube.com/watch?v=2AYUGeuxM0c

In the first 4 or so seconds, you can see that when he collides with two rectangles that arent in each other or touching each other, everything works fine, but in the rest of the video, you can see that when player touches side, he starts to jitter (please note that because of fraps, my game was running at quarter of FPS I normaly have, so without fraps the jitter is much faster)

To give you idea how my collision rectangles look now, here is debug mode (each rectangle is randomly colored)

I have couple of algortihms in place that merge rectangles into one (still need to do some work on that), but some simply cannot be merged. One example is the C object on the right. Right now it is made of 7 rectangles (will be 3 after I complete my algorithm) and when player slides on side of it, he starts to jitter.

I suspect problem is in my gravity, but Im not sure. I've spent 5 days on trying to fix this and Im lost.

Heres my code (slighty modified from platformer sample):

```
        for (int i = 0; i < playerCollisionRectangles.Count; i++)
        {
            Vector2 depth = Collision.GetIntersectionDepth(player.PlayerRectangleInWorld, playerCollisionRectangles[i]);
            if (depth != Vector2.Zero)
            {
                float absDepthX = Math.Abs(depth.X);
                float absDepthY = Math.Abs(depth.Y);

                // Resolve the collision along the shallow axis.
                if (absDepthY < absDepthX)
                {
                    // Resolve the collision along the Y axis.
                    player.PlayerPositionY += Convert.ToInt32(depth.Y);
                }
                else
                {
                    // Resolve the collision along the X axis.
                    player.PlayerPositionX += Convert.ToInt32(depth.X);
                }
            }
        }

```

And here is my gravity code (very very simple):

```
        if (Gravity)
        {
            //for camera
            position.Y += 2;
            //position in world
            playerPositionY += 2;
        }

```

And lastly here is one of my methods to move player (i have similiar methods to move him left and up):

```
    public void MoveRight()
    {
        animate.Enabled = true;
        animate.Row = 0;
        position.X += speed;
        playerPositionX += speed;
    }

```

# Answer
I think the problem is that when you are iterating through your collisions (playerCollisionRectangles) -- you are adjusting the position of your player more than once. This would explain the correct behavior when you are passing over single rectangles. When you are passing over more than one rectangle, the depth correction is being fired multiple times, causing jitter.
> 1 votes

---
Tags: xna, c#, 2d, collision-detection, collision-resolution
---


# Question
Title: How do i make player input object spawning data driven?
I'm using component based design and am at the stage or re-factoring simple player input to be data driven.

Currently i have a `PlayerControlComponent`, which an entity has if it should be player controlled. Currently only a single entity has this.

I have an `InputSystem` that acts on entities with `PlayerControlComponent`, `PhysicalComponent` and `MoveableComponent` components.

Below is the code that actually does the entity creation:

```
if (_InputActionManager.IsAction(_ActionFireBullet))
{
    if (WorldManager.CanDoAction(playerControlComponent.CreateBulletActionId))
    {
        // Create a bullet and fire it
        using (var entityTemplate = WorldManager.GetEntityTemplate(@"EntityTemplates\Bullet"))
        {
            var bulletPhysicalComponent = entityTemplate.Item.GetComponentOfType<PhysicalComponent>();
            var bulletMoveableComponent = entityTemplate.Item.GetComponentOfType<MoveableComponent>();

            bulletPhysicalComponent.Position = physicalComponent.Position + physicalComponent.Direction * physicalComponent.Radius;
            bulletPhysicalComponent.Direction = physicalComponent.Direction;
            bulletMoveableComponent.Velocity = moveableComponent.Velocity + physicalComponent.Direction * 200;
        }

        WorldManager.MarkActionDone(playerControlComponent.CreateBulletActionId);
    }
}

```

I want to get to the stage where I can have an XML file that indicates some how that a given entity will create a new entity based on a given template and **set initial values** such as position, direction and velocity in the above example.

I want to avoid having to change code and maybe add systems and components for each type of thing I want to spawn.

For example, currently if I wanted to add the ability for an enemy to spawn a missile I'd need to define my missle entity template (fine), create a new component to mark the entity as being able to fire a missle, then create a system that uses that component (want to avoid), then create a system with code similar to the above (want to avoid).

As another example, say I want to change the speed of the bullet, currently I do that in code, but I want to be able to do that in a data-driven way.

**How can I create and manage a way of creating an entity based on an event occuring, with properties based on the entity that created it?** i.e. Player presses Fire, bullet spawned at ship location, moving away from ship.

# Answer
> 2 votes
*Disclaimer: The ideas on this post are untested.*

One solution that comes to my mind, is perhaps to use a Factory Method together with Reflection. Your external template file (XML or JSON) would provide a description of each type of entity, listing all of its components and their initial parameters. Then:

1. The **Factory Method** takes care of **instantiating the components** knowing only their names. Similar to what you already seem to have but with a string key.
2. **Reflection** would then be used to access the **component's properties by name and set their initial values**. IIRC, relevant methods are `Object.GetType()`, `Type.GetProperty(name)`, `PropertyInfo.SetValue(object, value, null)`.

If your initial property values were simple values without dependencies this would probably be enough. But your example seems to need a lot more complexity than this, because it **depends on the parent's values**, and is in the form of an **expression, not a simple value**.

That certainly makes things more complicated. I can foresee two roads for incorporating that behavior:

1. Either you implement some sort of **simplified scripting system** with your own syntax and fitting your needs, that would receive the necessary context, parsing the expression and executing it accordingly.

This system would need to be able to handle a set of basic data types (int, float, string, boolean, Vector2, Vector3), would need to be able to access properties on the parent component (which would be translated to Reflection calls), and know how to perform the basic arithmetic operations between data types. I don't think this would be an easy task.
2. Or another alternative I can think about is maybe using C# runtime compilation (I talk a little about it here and show an example) and put **C# code directly in the template**.

Then you would go through the template file at load time and prepare/compile one method for each initialization entry, taking the parent entity as a parameter. This way you can put C# code directly in the template, which would be executed later when instantiating the entities. The biggest advantage is not having to create your own scripting language though.

Something like this on your template (take all that follows as a sort of pseudocode, I have not considered all the possibilities):

```
<component name="Bullet">
    <property name="Position" value="parent.physicalComponent.Position + parent.physicalComponent.Direction * parent.physicalComponent.Radius;" />
</component>

```

Which would be wrapped and compiled at runtime inside a method such as (**notice the use of the dynamic keyword to disable static checking**):

```
public static object GetBulletPositionInitialValue(dynamic parent)
{
    return parent.physicalComponent.Position + parent.physicalComponent.Direction * parent.physicalComponent.Radius;
}

```

Notice that the method also follows a naming convention `Get + ComponentName + PropertyName + InitialValue` so that you can access it later by name using reflection.

I'm just shooting out a few ideas though, I'm not entirely sure whether this would actually work though. :-)

---
Tags: c#, component-based, data-driven
---


title: image editor to create texture atlas

text:
# Question
Title: image editor to create texture atlas
While I am slowly learning how to build an android game, I would like to build images for a game, especially texture atlas.

But the only image handling system I am familiar with is Photoshop. And I am not sure it is a good tool to organize images and to get coordinates for game dev.

Is there any good tool for this purpose? If photoshop is still good for this, any reference to show how to do it would be appreciated.

UPDATE: the second question was answered by this But still want to hear more options.

UPDATE2: In case you are using libgdx, I found it does the packing for you.

# Answer
Sprite Sheet Packer is a tool initially thought for XNA, but since it exports a PNG along with a TXT/XML with the sprite coordinates (and is easily extended via plugins) it may suit your requirements.
> 5 votes

# Answer
Here's another one Sprite Sheet Maker. It's a bit more advanced than Sprite Sheet Packer, but it's not free, *unless* you're a blogger or a framework developer - interesting license.
> 2 votes

---
Tags: asset-management
---


# Question
Title: Networking server/client library to setup p2p connection
I'm making a multiplayer game, and I want to setup a p2p network.
I'm coding a server in python to make the matches and send each player it's adversary ip and port, but I'm having trouble to make udp hole punching to work.
On the client side I'm using ENET library that works over UDP.
Is there any library specific for game networking that will include all necesary from making the match to setup the p2p?

# Answer
> 2 votes
There is a big problem for the P2P: the NAT curse. Peer to peer is difficult because a lot of client are connected through NAT.

If you are interested in lan play, broadcasting may be a solution (do not try to cheat by Faking a LAN throught a VPN...)

A good alternative may be linjingle: a library developed by google to allow audio/video in XMPP sessions (you may know XMPP as Jabber Istant Messaging).

In this case you have to setup a Jabber server and extend it to provide gaming functionalities, then write the client using jingle to allow them to exchange their data.

# Answer
> 1 votes
You need a solution that will do the firewall penetration for you. In general, this is called STUN:

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

No matter what, you will need your users to all talk to a single server that they can all see at least once to find each other, and help poke through each others firewalls. If you want to blow the money on bandwidth, it's certainly simpler if that server also reflects their traffic for them.

This appears to be an open source implementation, although I haven't used it:

http://sourceforge.net/projects/stun/

If you make your game with Steamworks on PC, I believe their p2p matchmaking will do the hard work for you.

---
Tags: networking
---


# Question
Title: OpenGL Core 3.2 framebuffer rendering black on Mac OSX
I'm trying to get a 2 pass post-processing system going in OpenGL in a cross-platform manor using FBOs. I'm starting the dev on mac OSX (since in the past I've found it the most finicky to get working of windows/linux/osx), I have a toggle to toggle between using the FBO(post-processing) and not. The shaders are working, but it seems the FBO didn't load the texture unit bound to it. The following is the init code for the FBO and it's texture:

```
glGenTextures(1,&fboimg);
glBindTexture(GL_TEXTURE_2D,fboimg);

glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 512, 512, 0,
             GL_RGBA, GL_UNSIGNED_BYTE, 0);
glBindTexture(GL_TEXTURE_2D, 0);

glGenFramebuffers(1,&fboHandle);
glBindFramebuffer(GL_FRAMEBUFFER,fboHandle);

glFramebufferTexture2D(GL_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,GL_TEXTURE_2D,fboimg,0);

GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

switch(status)
    {

        case GL_FRAMEBUFFER_COMPLETE:    cout<<"The fbo is complete\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT\n"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER"<<endl; break;
        case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER:    cout<<"GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER"<<endl; break;
    }

if(status != GL_FRAMEBUFFER_COMPLETE)
{
    cout<<"status !=  GL_FRAMEBUFFER_COMPLETE"<<endl;
    GLUtils::checkForOpenGLError(__FILE__,__LINE__);
}
else
{
    //shader and VAO setup for post
    fboSetup = true;
}

```

Here is the render code:

```
//start rendering to FBO
if(postFlag&&fboSetup)
{
    glBindFramebuffer(GL_FRAMEBUFFER, fboHandle);

}
glUseProgram(programHandle);

//start rendering scene one way or another
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

glUniformMatrix4fv(mats.projHandle,1,GL_FALSE, glm::value_ptr(mats.projMatrix));
glUniformMatrix4fv(mats.mvHandle,1,GL_FALSE,glm::value_ptr(mats.modelViewMatrix));

//bind to vertex array object
glBindVertexArray(vaoHandle);
//render scene
glDrawArrays(GL_TRIANGLES, 0, 240*3 );

//do post-processing if we have it enabled
if(postFlag&&fboSetup)
{
    glFlush();
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    glUseProgram(fboProgram);

    glClear(GL_COLOR_BUFFER_BIT);

    glBindTexture(GL_TEXTURE_2D,fboimg);

    glUniform1i(glGetUniformLocation(fboProgram,"sampler0"),fboimg);
    glUniform2f(glGetUniformLocation(fboProgram,"resolution"),512,512);
    glBindVertexArray(vaoFBO);
    glDrawArrays(GL_TRIANGLES, 0, 6);
    glBindTexture(GL_TEXTURE_2D, 0);
}

```

Tried everything I can think of or find in a FBO tutorial or have read about. I don't get any errors and it returns as complete. (Also I can't seem to get it glTexImage2d a image of size width and height. says invalid values, and if I try to use GL\_TEXTURE\_RECTANGLE it says invalid enum :-/ but that's for a different question after I just get it working to begin with^^)

# Answer
> 1 votes
I'm an idiot. Textures 101:

```
glBindTexture(GL_TEXTURE_2D,fboimg);
glUniform1i(glGetUniformLocation(fboProgram,"sampler0"),fboimg);

```

should be:

```
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D,fboimg);
glUniform1i(glGetUniformLocation(fboProgram,"sampler0"),0);

```

---
Tags: opengl, c++, macos
---


title: Combine 3D objects in XNA 4

text:
# Question
Title: Combine 3D objects in XNA 4
Currently I am writing on my thesis for university, the theme I am working on is 3D Visualization of hierarchical structures using cone trees.

I want to do is to draw a cone and arrange a number of spheres at the bottom of the cone. The spheres should be arranged according to the radius and the number of spheres correctly.

As you can imagine I need a lot of these cone/sphere combinations.

# First Attempt

I was able to find some tutorials that helped with drawing cones and spheres.

**Cone**

```
    public Cone(GraphicsDevice device, float height, int tessellation, string name, List<Sphere> children)
    {
        //prepare children and calculate the children spacing and radius of the cone
        if (children == null || children.Count == 0)
        {
            throw new ArgumentNullException("children");
        }

        this.Height = height;
        this.Name = name;
        this.Children = children;

        //create the cone
        if (tessellation < 3)
        {
            throw new ArgumentOutOfRangeException("tessellation");
        }

        //Create a ring of triangels around the outside of the cones bottom
        for (int i = 0; i < tessellation; i++)
        {
            Vector3 normal = this.GetCircleVector(i, tessellation);

            // add the vertices for the top of the cone
            base.AddVertex(Vector3.Up * height, normal);
            //add the bottom circle
            base.AddVertex(normal * this.radius + Vector3.Down * height, normal);

            //Add indices
            base.AddIndex(i * 2);
            base.AddIndex(i * 2 + 1);
            base.AddIndex((i * 2 + 2) % (tessellation * 2));

            base.AddIndex(i * 2 + 1);
            base.AddIndex((i * 2 + 3) % (tessellation * 2));
            base.AddIndex((i * 2 + 2) % (tessellation * 2));
        }

        //create flate triangle to seal the bottom
        this.CreateCap(tessellation, height, this.Radius, Vector3.Down);

        base.InitializePrimitive(device);
    }

```

**Sphere**

```
    public void Initialize(GraphicsDevice device, Vector3 qi)
    {
        int verticalSegments = this.Tesselation;
        int horizontalSegments = this.Tesselation * 2;

        //single vertex on the bottom
        base.AddVertex((qi * this.Radius) + this.lowering, Vector3.Down);

        for (int i = 0; i < verticalSegments; i++)
        {
            float latitude = ((i + 1) * MathHelper.Pi / verticalSegments) - MathHelper.PiOver2;
            float dy = (float)Math.Sin(latitude);
            float dxz = (float)Math.Cos(latitude);

            //Create a singe ring of latitudes
            for (int j = 0; j < horizontalSegments; j++)
            {
                float longitude = j * MathHelper.TwoPi / horizontalSegments;

                float dx = (float)Math.Cos(longitude) * dxz;
                float dz = (float)Math.Sin(longitude) * dxz;

                Vector3 normal = new Vector3(dx, dy, dz);

                base.AddVertex(normal * this.Radius, normal);
            }
        }

        // Finish with a single vertex at the top of the sphere.
        AddVertex((qi * this.Radius) + this.lowering, Vector3.Up);

        // Create a fan connecting the bottom vertex to the bottom latitude ring.
        for (int i = 0; i < horizontalSegments; i++)
        {
            AddIndex(0);
            AddIndex(1 + (i + 1) % horizontalSegments);
            AddIndex(1 + i);
        }

        // Fill the sphere body with triangles joining each pair of latitude rings.
        for (int i = 0; i < verticalSegments - 2; i++)
        {
            for (int j = 0; j < horizontalSegments; j++)
            {
                int nextI = i + 1;
                int nextJ = (j + 1) % horizontalSegments;

                base.AddIndex(1 + i * horizontalSegments + j);
                base.AddIndex(1 + i * horizontalSegments + nextJ);
                base.AddIndex(1 + nextI * horizontalSegments + j);

                base.AddIndex(1 + i * horizontalSegments + nextJ);
                base.AddIndex(1 + nextI * horizontalSegments + nextJ);
                base.AddIndex(1 + nextI * horizontalSegments + j);
            }
        }

        // Create a fan connecting the top vertex to the top latitude ring.
        for (int i = 0; i < horizontalSegments; i++)
        {
            base.AddIndex(CurrentVertex - 1);
            base.AddIndex(CurrentVertex - 2 - (i + 1) % horizontalSegments);
            base.AddIndex(CurrentVertex - 2 - i);
        }

        base.InitializePrimitive(device);
    }

```

The tricky part now is to arrange the spheres at the bottom of the cone. I tried is to draw just the cone and then draw the spheres. I need a lot of these cones, so it would be pretty hard to calculate all the positions correctly.

# Second Attempt

So the second try was to generate a object that builds all vertices of the cone and all of the spheres at once. So I was hoping to render a cone with all its spheres arranged correctly. After a short debug I found out that the cone is created and the first sphere, when it turn of the second sphere I am running into an `OutOfBoundsException` of ushort.MaxValue.

**Cone and Spheres**

```
    public ConeWithSpheres(GraphicsDevice device, float height, float coneDiameter, float sphereDiameter,
        int coneTessellation, int sphereTessellation, int numberOfSpheres)
    {
        if (coneTessellation < 3)
        {
            throw new ArgumentException(string.Format("{0} is to small for the tessellation of the cone. The number must be greater or equal to 3", coneTessellation));
        }

        if (sphereTessellation < 3)
        {
            throw new ArgumentException(string.Format("{0} is to small for the tessellation of the sphere. The number must be greater or equal to 3", sphereTessellation));
        }

        //set properties
        this.Height = height;
        this.ConeDiameter = coneDiameter;
        this.SphereDiameter = sphereDiameter;
        this.NumberOfChildren = numberOfSpheres;
        //end set properties

        //generate the cone
        this.GenerateCone(device, coneTessellation);

        //generate the spheres

        //vector that defines the Y position of the sphere on the cones bottom
        Vector3 lowering = new Vector3(0, 0.888f, 0);

        this.GenerateSpheres(device, sphereTessellation, numberOfSpheres, lowering);
    }

    // ------ GENERATE CONE ------
    private void GenerateCone(GraphicsDevice device, int coneTessellation)
    {
        int doubleTessellation = coneTessellation * 2;

        //Create a ring of triangels around the outside of the cones bottom
        for (int index = 0; index < coneTessellation; index++)
        {
            Vector3 normal = this.GetCircleVector(index, coneTessellation);

            //add the vertices for the top of the cone
            base.AddVertex(Vector3.Up * this.Height, normal);

            //add the bottom of the cone
            base.AddVertex(normal * this.ConeRadius + Vector3.Down * this.Height, normal);

            //add indices
            base.AddIndex(index * 2);
            base.AddIndex(index * 2 + 1);
            base.AddIndex((index * 2 + 2) % doubleTessellation);

            base.AddIndex(index * 2 + 1);
            base.AddIndex((index * 2 + 3) % doubleTessellation);
            base.AddIndex((index * 2 + 2) % doubleTessellation);
        }

        //create flate triangle to seal the bottom
        this.CreateCap(coneTessellation, this.Height, this.ConeRadius, Vector3.Down);

        base.InitializePrimitive(device);
    }

    // ------ GENERATE SPHERES ------
    private void GenerateSpheres(GraphicsDevice device, int sphereTessellation, int numberOfSpheres, Vector3 lowering)
    {
        int verticalSegments = sphereTessellation;
        int horizontalSegments = sphereTessellation * 2;

        for (int childCount = 1; childCount < numberOfSpheres; childCount++)
        {
            //single vertex at the bottom of the sphere
            base.AddVertex((this.GetCircleVector(childCount, this.NumberOfChildren) * this.SphereRadius) + lowering,
                Vector3.Down);

            for (int verticalSegmentsCount = 0; verticalSegmentsCount < verticalSegments; verticalSegmentsCount++)
            {
                float latitude = ((verticalSegmentsCount + 1) * MathHelper.Pi / verticalSegments) - MathHelper.PiOver2;
                float dy = (float)Math.Sin(latitude);
                float dxz = (float)Math.Cos(latitude);

                //create a single ring of latitudes
                for (int horizontalSegmentsCount = 0; horizontalSegmentsCount < horizontalSegments; horizontalSegmentsCount++)
                {
                    float longitude = horizontalSegmentsCount * MathHelper.TwoPi / horizontalSegments;
                    float dx = (float)Math.Cos(longitude) * dxz;
                    float dz = (float)Math.Sin(longitude) * dxz;

                    Vector3 normal = new Vector3(dx, dy, dz);

                    base.AddVertex((normal * this.SphereRadius) + lowering, normal);
                }
            }

            //finish with a single vertex at the top of the sphere
            base.AddVertex((this.GetCircleVector(childCount, this.NumberOfChildren) * this.SphereRadius) + lowering,
                Vector3.Up);

            //create a fan connecting the bottom vertex to the bottom latitude ring
            for (int i = 0; i < horizontalSegments; i++)
            {
                base.AddIndex(0);
                base.AddIndex(1 + (i + 1) % horizontalSegments);
                base.AddIndex(1 + i);
            }

            //Fill the sphere body with triangles joining each pair of latitude rings
            for (int i = 0; i < verticalSegments - 2; i++)
            {
                for (int j = 0; j < horizontalSegments; j++)
                {
                    int nextI = i + 1;
                    int nextJ = (j + 1) % horizontalSegments;

                    base.AddIndex(1 + i * horizontalSegments + j);
                    base.AddIndex(1 + i * horizontalSegments + nextJ);
                    base.AddIndex(1 + nextI * horizontalSegments + j);

                    base.AddIndex(1 + i * horizontalSegments + nextJ);
                    base.AddIndex(1 + nextI * horizontalSegments + nextJ);
                    base.AddIndex(1 + nextI * horizontalSegments + j);
                }
            }

            //create a fan connecting the top vertiex to the top latitude
            for (int i = 0; i < horizontalSegments; i++)
            {
                base.AddIndex(this.CurrentVertex - 1);
                base.AddIndex(this.CurrentVertex - 2 - (i + 1) % horizontalSegments);
                base.AddIndex(this.CurrentVertex - 2 - i);
            }
            base.InitializePrimitive(device);
        }
    }

```

Any ideas how I could fix this?

# Answer
Try using a 32bit index buffer instead of a 16bit one - it looks like you are running out of indicies.

What you could look into is an engine with scene graph support. A scene graph is essentially a tree of nodes - where each node is attached to a parent via some matrix transform/translation (sound familiar?). If you are not allowed to use middleware a scene graph is somewhat trivial to implement.
> 3 votes

---
Tags: 3d, xna-4.0
---


# Question
Title: temperamental ID3D10EffectVectorVariable
I am setting an HLSL effect variable in the following way in a number of places.

```
extern ID3D10EffectVectorVariable* pColour;

pColour = pEffect->GetVariableByName("Colour")->AsVector();

pColour->SetFloatVector(temporaryLines[i].colour);

```

In one of the places it is set in a loop, each line in the vector `temporaryLines` has a D3DXCOLOR variable associated with it. The most annoying thing about this problem is that it actually works on rare occasions, but most of the time it doesn't. Are there any known issues with this kind of code?

Here it works:

```
void GameObject::Draw(D3DMATRIX matView, D3DMATRIX matProjection)
{
device->IASetInputLayout(pVertexLayout);

mesh.SetTopology();//TODO should not be done multiple times

// select which vertex buffer and index buffer to display
UINT stride = sizeof(VERTEX);
UINT offset = 0;
device->IASetVertexBuffers(0, 1, mesh.PBuffer(), &stride, &offset);
device->IASetIndexBuffer(mesh.IBuffer(), DXGI_FORMAT_R32_UINT, 0);

pColour->SetFloatVector(colour);

// create a scale matrix
D3DXMatrixScaling(&matScale, scale.x, scale.y, scale.z);

// create a rotation matrix
D3DXMatrixRotationYawPitchRoll(&matRotate, rotation.y, rotation.x, rotation.z);

// create a position matrix
D3DXMatrixTranslation(&matTranslation, position.x, position.y, position.z);

// combine the matrices and render
matFinal =
    matScale        *
    matRotate       *
    matTranslation  *
    matView * matProjection;
pTransform->SetMatrix(&matFinal._11);
pRotation->SetMatrix(&matRotate._11);    // set the rotation matrix in the effect
pPass->Apply(0);
device->DrawIndexed(mesh.Indices(), 0, 0);   //input specific
}

```

Here is occasionally works:

```
void BatchLineRenderer::RenderLines(D3DXMATRIX matView, D3DXMATRIX matProjection)
{
device->IASetInputLayout(pVertexLayout);

device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_LINESTRIP);

// select which vertex buffer and index buffer to display
UINT stride = sizeof(LINE);
UINT offset = 0;
device->IASetVertexBuffers(0, 1, &pBuffer, &stride, &offset);
device->IASetIndexBuffer(iBuffer, DXGI_FORMAT_R32_UINT, 0);

allLines = temporaryLines.size();

for(int i = 0; i < allLines; i++)
{
    pColour->SetFloatVector(temporaryLines[i].colour); // in the line loop too?

    // combine the matrices and render
    D3DXMATRIX matFinal =
        temporaryLines[i].scale *
        temporaryLines[i].rotation *
        temporaryLines[i].position *
        matView * matProjection;

    pTransform->SetMatrix(&matFinal._11);
    pRotation->SetMatrix(&temporaryLines[i].rotation._11);    // set the rotation matrix in the effect

    pPass->Apply(0);

    device->DrawIndexed(2, 0, 0);
}

temporaryLines.clear();
}

```

the effect file:

```
float4x4 Transform;    // a matrix to store the transform
float4x4 Rotation;     // a matrix to store the rotation transform
float4   LightVec   = {0.612f, 0.3535f, 0.612f, 0.0f};    // the light's vector
float4   LightCol   = {1.0f,   1.0f,    1.0f,   1.0f};    // the light's color
float4   AmbientCol = {0.3f,   0.3f,    0.3f,   1.0f};    // the ambient light's color
float4   Colour;

// a struct for the vertex shader return value
struct VSOut
{
    float4 Col : COLOR;    // vertex normal
    float4 Pos : SV_POSITION;    // vertex screen coordinates
};

// the vertex shader
VSOut VS(float4 Norm : NORMAL, float4 Pos : POSITION)
{
    VSOut Output;

    Output.Pos = mul(Pos, Transform);    // transform the vertex from 3D to 2D

    Output.Col = AmbientCol;    // set the vertex color to the input's color

    float4 Normal = mul(Norm, Rotation);

    Output.Col += saturate(dot(Normal, LightVec)) * LightCol * Colour; // add the diffuse and passed in light

    return Output;    // send the modified vertex data to the Rasterizer Stage
}

// the pixel shader
float4 PS(float4 Col : COLOR) : SV_TARGET
{
    return Col;    // set the pixel color to the color passed in by the Rasterizer Stage
}

// the primary technique
technique10 Technique_0
{
    // the primary pass
    pass Pass_0
    {
        SetVertexShader(CompileShader(vs_4_0, VS()));
        SetGeometryShader(NULL);
        SetPixelShader(CompileShader(ps_4_0, PS()));
    }
}

```

# Answer
Without being able to see it running (or the rest of the code) it's hard to say, but are you sure it's actually what you think failing here? That value is only used in the lighting equation where it's contribution is based on the angle between the normal of the vertex and the lighting vector. It could be the normal value on the line vertex is such that it breaks. Have you tried just setting the output colour of the VS (Output.Col) to just be equal to "Colour" to rule out any other possibilities? That way the value will just be set directly and will validate it's this that's broken. With that set, also try setting a specific value in the code rather than pull the value out of the line structure to ensure that's valid.

Other than that, there's any number of reasons it could be broken, e.g. the vertex layout might not exactly match the actual structure correctly, etc.

I'm not sure what the state of PC shader debugging is like as I haven't had much call to use them (e.g. PIX, NVidia or ATI tools), but they might also be able to let you see better what's going on.
> 1 votes

# Answer
Set your FloatVector before you set the Input Layout.

I had the same problem once:

https://stackoverflow.com/questions/2936472/setmatrix-does-not-copy-all-values-to-hlsl
> 2 votes

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


# Question
Title: Why does the D3DXCOLOR structure not work as I expect?
I looked up some R G B values for certain colours, such as "Indian red" for example, which has the RGB values (238, 64, 4).

If I use those values into a D3DXCOLOR structure like this: `D3DXCOLOR(238, 64, 4, 255)`, the colours display oddly - as white! This displays as yellow: `D3DXCOLOR(238, 64, 0, 255)`. Why is this?

# Answer
> 6 votes
The problem is that D3DXCOLOR does not accept 4 integer values from 0 to 255 for RGBA, but rather 4 floats from 0 to 1.

anything above 1 is treated effectively as 1. So to get the right values divide the RGB value you want by 255 to get a value from 0 to 1.

PAIN!

# Answer
> 0 votes
Try some well-known colours - D3DXCOLOR(255, 0, 0, 255) should be red, D3DXCOLOR(0, 255, 0, 255) should be green, and D3DXCOLOR(0, 0, 255, 255) should be blue. If the components are switched in some way, that should show you how.

D3DXCOLORs don't have any intrinsic method of rendering, so it is presumably the manner in which you are using those values which is broken in some way. Perhaps you could post your rendering code and show how you are getting these colours to appear on the screen.

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


# Question
Title: How to continuously find all entities within a radius efficiently?
I have a very large number of entities (units). On each step, each unit needs to know the positions of all units near it (distance is less then given constant **R**). All units move continuously. This is in 3D.

On average, there will be 1% of the total unit count near any other given unit with the given constraints.

How can I do this efficiently, without bruteforcing?

# Answer
> 15 votes
Use one of the common space partitioning algorithms, such as a Quadtree, Octree, BSP tree, or even a simple Grid System. Each has their own pros and cons for each specific scenario. You may read more about them in these books.

Generally (or so I've heard, I'm not too familiar with the reasoning behind this) a Quadtree or Octree is better fit for outdoor environments, while the BSP tree fits indoor scenes better. And the choice between using a Quadtree or an Octree depends on how flat your world is. If there's little variation in the Y axis using an Octree would be wasteful. An Octree is basically a Quadtree with an additional dimension.

Finally, don't disregard the simplicity of the Grid solution. Many people ignore that a simple grid can sometimes be enough (and even more efficient) for their problems, and jump straight to a more complex solution instead.

Using a grid consists simply in dividing the world into evenly spaced regions and storing the entities in the appropriate region of the world. Then, given a position, finding the neighbouring entities would be a matter of iterating over the regions that intersect your radius of search.

Let's say your world ranged from (-1000, -1000) to (1000, 1000) in the XZ plane. You could for instance divide it into a 10x10 grid, like so:

```
var grid = new List<Entity>[10, 10];

```

Then you'd place entities into their appropriate cells in the grid. For instance an entity with XZ (-1000, -1000) would fall on cell (0,0) while an entity with XZ (1000, 1000) would fall on cell (9, 9). Then given a position and a radius in the world, you could determine which cells are intersected by this "circle" and iterate only over those, with a simple double for.

Anyway, research all of the alternatives and pick the one that seems to fit your game better. I admit I'm still not knowledgeable enough on the subject to decide which of the algorithms would be best for you.

**Edit** Found this on another forum and it might help you with the decision:

> Grids work best when the vast majority objects fit within a grid square, and the distribution is fairly homogenous. Conversely, quadtrees work when the objects have variable sizes or are clustered in small areas.

Given your vague description of the problem, I'm leaning against the grid solution too (which is, assuming units are small and fairly homogeneously distributed).

# Answer
> 0 votes
I wrote this some time back. It's now on a commercial site, but you can get the source for personal use for free. It may be overkill and it's written in Java, but it's well documented so it should not be too hard to trim and rewrite in another language. It basically uses an Octree, with tweaks to handle really large objects and multi-threading.

I found an Octree offered the best combination of flexibility and efficiency. I started out with a grid, but it was impossible to size the squares properly and large patches of empty squares used up space and computing power for nothing. (And that was just in 2 dimensions.) My code handles queries from multiple threads, which adds a *lot* to the complexity, but the documentation should help you work around that if you don't need it.

# Answer
> 0 votes
To boost your efficiency, try to trivially reject the 99% of "units" that are not near the target unit using a very inexpensive bounding box check. And I would hope you could do this without structuring your data spatially. So if all your units are stored in a flat data structure you could try to race through it from start to finish and firstly check is the current unit outside the bounding box of the unit of interest.

Define an oversized bounding box for the unit of interest such that it can safely reject items that have no chance of being considered "near" it. The check for exclusion from a bounding box could be made cheaper than a radius check. However on some systems where this was tested it was found not to be the case. The two perform almost equally. This edited after much debate below.

First: 2D bounding box clip.

```
// returns true if the circle supplied is completely OUTSIDE the bounding box, rectClip
bool canTrivialRejectCircle(Vertex2D& vCentre, WorldUnit radius, Rect& rectClip) {
  if (vCentre.x + radius < rectClip.l ||
    vCentre.x - radius > rectClip.r ||
    vCentre.y + radius < rectClip.b ||
    vCentre.y - radius > rectClip.t)
    return true;
  else
    return false;
}

```

Compared with something like this (in 3D):

```
BOOL bSphereTest(CObject3D* obj1, CObject3D* obj2 )
{
  D3DVECTOR relPos = obj1->prPosition - obj2->prPosition;
  float dist = relPos.x * relPos.x + relPos.y * relPos.y + relPos.z * relPos.z;
  float minDist = obj1->fRadius + obj2->fRadius;
  return dist <= minDist * minDist;
}.

```

If the object is not trivially rejected then you perform a more expensive and accurate collision test. But you are just looking for nearnesss so the sphere test is suitable for that, but only for the 1% of objects that survive the trivial rejection.

This article supports the box for trivial rejection. http://www.h3xed.com/programming/bounding-box-vs-bounding-circle-collision-detection-performance-as3

If this linear approach doesn't give you the performance you need, then a hierarchical data structure may be required such as the other posters have been talking about. R-Trees are worth considering. They support dynamic changes. They are the BTrees of the spatial world.

I just didn't want you going to all that trouble of introducing such complexity if you could avoid it. Plus what about the cost of keeping this complex data strucure up to date as objects move around several times per second?

Bear in mind that a grid is a one level deep spatial data structure. This limit means that it is not truly scaleable. As the world grows in size, so do the number of cells you need to cover. Eventually that number of cells itself becomes a performance problem. For a certain sized world however, it will give you a massive performance boost over no spatial partitioning.

# Answer
> 0 votes
I have to make this an answer because I don't have the points to comment or upvote. For 99% of the people who ask this question, a bounding box is the solution, as described by Ciaran. In a compiled language, it will reject 100,000 irrelevent units in the blink of an eye. There's a lot of overhead involved with non-brute-force solutions; with smaller numbers (say under 1000) they'll be more expensive in terms of processing time than brute force checking. And they'll take vastly more programming time.

I'm not sure what "a very large number" in the question means, or what other people looking here for answers will mean by it. I suspect my numbers above are conservative and could be multiplied by 10; I am personally quite prejudiced against brute force techniques and am seriously annoyed at how well they work. But I wouldn't want someone with, say, 10,000 units to waste time with a fancy solution when a few quick lines of code will do the trick. They can always get fancy later if they need to.

Also, I would note that a bounding sphere check requires multiplication where the bounding box does not. Multiplication, by its nature, takes several times as long as addition and comparisons. There's bound to be some combination of language, OS, and hardware where the sphere check will be faster than a box check, but in most places and times the box check has to be faster, even if the sphere does reject a few irrelevant units the box accepts. (And where the sphere is faster, a new release of the compiler/interpreter/optimizer is very likely to change that.)

---
Tags: performance, data-structure, efficiency
---


# Question
Title: What are these rendering artifacts and how can I fix them?
**Here is the artifact:**

**Here is some clarifying information:**

1. This appears only at 480 units from the origin, and seems to get worse (to a point) as I move away.
2. All water should have sand rendered behind it, but the sand should be occluded (since I will eventually be rendering the water semi-transparently).

**Here is my guess:**

This looks like z-fighting, but my issue with this hypothesis is that none of these polygons are co-planar.

# Answer
What are your far and near clipping planes set to? Try adjusting them to be closer together and see if that solves the issue. I think it's z-fighting as well, and it could crop up even if the polygons aren't on the same plane, depending on the precision of the depth buffer, the closeness of the clipping planes, etc.
> 5 votes

# Answer
As D C said, this is probably z-fighting, caused by insufficient depth buffer resolution, caused by a too-near near plane.

You might be interested in the answers to this question of mine, How do I methodically choose the near clip plane distance for a perspective projection?, which describe several different approaches to choosing the near clipping plane.
> 1 votes

---
Tags: xna
---


# Question
Title: What are some examples of MMOs with small development teams?
I'd like to see a list of MMOs with small development teams in order to better understand where small teams have found a place for themselves.

While examples of MMORPGs are of interest, so are games focusing on socializing, trade and commerce, city or empire building, crafting, exploration, strategy and so on. Any shipping game supporting between, say 800 and 10,000 simultaneous players belongs on this list.

# Answer
> 4 votes
You might have already seen my answer to Why are MMOs hard?, but it has a list of several games that were developed by 1-2 people. The major disagreement some people had with them, is whether some of them *qualify* as MMOs. However, at least *one* of them has over a thousand players (A Tale in the Desert), which certainly qualifies as "massive". :)

# Answer
> 10 votes
The minimum number of people required to make an MMO is one, as demonstrated by LOVE, a released MMO developed entirely by Eskil Steenberg. To see LOVE in action, check out this youtube video.

# Answer
> 7 votes
Gods and Idols was developed by one person (Full disclosure: me) and has been in open beta since early 2008. http://www.GodsAndIdols.com

# Answer
> 6 votes
## Minecraft

I have not played this myself, and I don't know if there is a restriction on number of players which might be too low for "massive multiplayer".

> Minecraft was developed for about a week before its public release on May 17, 2009 on the TIGSource forums, where it gained a considerable level of popularity. It has been continually updated and patched since then

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

## Stendhal

Stendhal is a 2D RPG which has been developed by about 5 people in their spare time. (I am one of them). The first version was released after 3 month spare time by one developer. But it was rather basic back then and more a prove of concept than a playable game. After about 6 month to one year it was fully playable and quite fun. Nowadays it is under heavy development and patches are released regularly.

You can have a look at our release history (click "Read all the news items" at the bottom). It nicely shows how the game was improved from patch to patch since 2005. 5 years may seem like a really huge amount of time, but you have to keep two things in mind: First it is a spare time project. Second it was fun to play after about a year. We spent the last 4 years of adding to an existing game by releasing patches.

Ohloh has some nice statistics about commits: http://www.ohloh.net/p/stendhal/contributors

# Answer
> 2 votes
Star Trek Online was a core team of ~40-50 for two years. Kingdom of Loathing has had a dev team of about 5. Urban Dead is a one-man-show I think. How low do you want to go? STO is a AAA 3D game, so two years is almost unheard of. KoL and UD are both web-based, so I'm not sure what would be considered "surprising" other than hearing a game was developed by a sentient AI or somesuch. How about Minecraft, thats ~1-3 people and has now made millions (but is still technically alpha)?

# Answer
> 2 votes
I agree with some of the comments that it's unclear what would be considered surprising. There's a huge range of sizes of games that can be considered to be “MMOs”.

Realm of the Mad God was developed by 2 people in 30 days for the TIGSource Assemblee competition. The game was playable & fun, had lots of users, had an active forum, and had an active user-built wiki soon after the end of the 30 day period. They've continued working on it for the past year (new dungeons, monsters, items, classes, gameplay, etc.) and have had occasional help from others with art, music, sound, design. They don't usually release metrics but at one point they mentioned 1200 concurrent players and 37,000 players in one day. It's not “out of beta” yet but I think the core team will remain 2 people. (Full disclosure: I'm one of the “occasional help” set of people; they're using my maps.)

# Answer
> 2 votes
Here are two articles and a presentation on the idea of small MMOs that I absolutely love. Both offer great examples and great advice...

First is Boutique MMOs on The Escapist.

The second one is A Game Business Model: Learning from Touring Bands on DanC's Lost Garden blog.

Third is a presentation by NetDevil at GDC 2008 Small Teams Big Dreams. It was a great talk and I found myself nodding my head a lot when I was there.

Definitely read those articles. Both are fantastic reads for this topic.

Another thing to do that will help you better understand this realm of "successful MMOs nobody's heard of created by small teams" is go play them. Try them out and see what it is about them that makes them work. And with the developers eye, look at them and think about what it took the developer to create them.

Both in relation to the two articles I linked to and the comment about testing, lot of it comes down to what you define as an MMO, and what you define as success. If one has the "MMO means WoW" mindset, then you'll never be able to wrap your head around the idea of A Tail In The Desert as being an MMO, or a MUD for that matter.

In terms of how you define an MMO, if you as a developer have to create all the content for your users (write quests, storylines, other unique content), then it's going to take a lot of work. But if you let the user define the game (think MineCraft and sandbox style), then it's a lot different.

And success is (I think) looking at how much money are you making, how much it cost to make the game, and how many developers you have. If you have 2 developers with little upfront cost, then having $20k a month come in is not bad. If you have 100 developers and it cost you $50m to develop the game, it's another story.

# Answer
> 1 votes
If 30 people is small enough, Darkfall Online has necessitated 7 years of development for a non instanced MMOFPS which is able to have more than 5k people online at the same time.

# Answer
> 1 votes
Supposedly there are 8 developers working on Infinity: Quest for Earth http://www.infinity-universe.com/Infinity/index.php?option=com\_content&task=view&id=114&Itemid=49

Its even more interesting that most of what you see is procedurally generated.

# Answer
> 1 votes
Tibia was wrote with only 4 developers (and one of them was only working in the website) as a student project.

From Wikipedia:

> In 1995 the four German students Guido Lübke, Stephan Payer, Ulrich Schlott and Stephan Vogler worked for the first time on the online role-playing game Tibia, as a student’s project. To be contrary to the text-based games at that time, they wanted to design a graphical game which gives players a realistic view of the virtual world. Just two years later, in January 1997, the first version of "Tibia" went online on servers of the university.
>
> Due to the huge success of Tibia, the four former students decided to found their own company. The year 2001 was the founding year of the CipSoft GmbH in Regensburg, Germany. Over 50 permanent employees and a dozen assistants work for CipSoft GmbH. In 2010, the company had an annual turnover of about 8 million Euro.

I was playing Tibia back in the 90's so I can give you more insights on how they managed to make this game with only 4 people.

## The game was simple

Back in the 90's the game was very lame simple, there was no logging of who killed who, no protection zone, very simple spells, no safe way to trade item (you had to drop the item and the buyer drop the money).

While this "simpleness" looks more like "lameness" it actually made the gameplay fun. e.g.: since the server didn't log the player deaths, a killer could cover his tracks my throwing his victim body on a river.

## The art was stolen borrowed

It was only a student project, so they took all the game art from Ultima VI and VII, as the game became more popular they started to replace the Ultima VI with they own artwork but even nowadays you can still notice a strong semblance in some items

## The community

Although nowadays Tibia is power-gamer infested like any other MMORPG, in the "student project" days it was more a Role-player niche. This helped in the success of the game. Remember that this game was very simple, a power-gamer could easily abuse this lack of polish.

---
Tags: mmo, development-speed
---


# Question
Title: Using GPU on Silverlight 5 for a Fast Fourier Transform
I've got an audio library for Silverlight that is in need of some acceleration on slower machines. Specifically, this library makes extensive and repeated use of the FFT transform as a part of its acoustic echo cancellation and noise reduction algorithms, and I'm wondering if it would make any sense to use the GPU for this (as described, for instance, here: http://www.inf.fu-berlin.de/lehre/SS10/SP-Par/download/fft1.pdf).

I know that Silverlight 5 provides a fairly simple port of Microsoft's XNA framework, but unfortunately, I'm a complete novice to 3D coding in general, and XNA in particular. It seems to me like it should be theoretically possible to use some combination of vertex and/or pixel shaders to work this magic, but before I go too far down this road, I wanted to get some expert opinions on a few questions:

(1) SL5's XNA implementation throws the output of its pipeline onto a single "DrawingSurface". I had been thinking that this is where I might be able to read the results of the calculations (kind of how you could use a WriteableBitmap to read the results of pixel shader calculations in SL4). But I can't figure out how I would do that: there's no "GetPixels()" method, or anything like that. In regular XNA 4.0, the VertexBuffer has a GetData() method, as do the Texture2D and Texture3D classes, but those methods are missing in the SL5 version. Does anyone know of any way to actually read the results of shader outputs? Or is the GPU a write-only device in SL5?

(2) It seems like the real problem with GPU calculations is reading the results *quickly*. Assuming I can solve problem #1, does anyone know whether an FFT would be amenable to this sort of solution?

(3) Silverlight 5 is limited to HLSL Level 2, which has a number of serious limitations, so far as instructions, registers, available functions, and so forth. Is it at all reasonable to expect to be able to port an FFT or some portion thereof over to this?

Thanks in advance.

# Answer
According to Shawn Hargreaves (from MS), this isn't supported in Silverlight 5. His unofficial guess as to why is that (a) it would be difficult to get it working consistently across all GPU drivers, and (b) for all but a tiny class of demo-ware-style problems, it wouldn't make any sense.

Oh well.
> 3 votes

# Answer
I wrote a custom content importer to "GetData" for a Texture2D.

http://www.dustinhorne.com/post/2011/12/28/Getting-Color-Data-for-a-Texture2D-in-Silverlight-5-XNA.aspx
> 1 votes

---
Tags: xna, gpu, gpgpu
---


title: XNA and C# Draw method question

text:
# Question
Title: XNA and C# Draw method question
If I missed the answer to this question being already posted I apologize but I was unable to find it.

I'm new to C# and XNA and converting a VB game I created into them. Im finding a problem I'm not sure how to get around.

I'm using a generic list that contains information about nonplayer characters including the Graphic, Vector2, Rectangle. I'm reading this information from a file. So I have a class to receive all the information then I add it to the generic List. It then passes that information back to the main Game1.cs.

My problem is when it gets to the Draw method after loading all the information into the generic List\<\> the other methods in the main see the list EXCEPT the Draw and Update methods. I thought this would be because of the protected status of those methods but it will not let me change them to public.

So to sum up NPCClass.cs creates a class to accept the information. LoadLevel.cs reads from a text file and loads a instance of the NPCClass and adds it to a generic list of the NPCClass that is contained in the Game1.cs. The Draw Method in Game1.cs will not see the generic List even tho I have it publicly declared in Game1.cs main.

Thank you for any help and if i'm going at this completely incorrectly please don't hesitate to tell me.

# Answer
It sounds like you have built a class when what you want is a game component. A game component overloads the Game1.cs Draw and Update loops with the code contained in the component's draw and update loops. To create a component just right-click on your project and select -\>Add New Item and then select game component from the XNA options.

You also may want to look at the XGPA tutorial series that shows how to build a 2D RPG from the ground up. Even if you don't want to follow all the tutorials you can download the lesson source code and see how the author built the project:

http://xnagpa.net/tutorials.php
> 1 votes

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


# Question
Title: How to draw only visible models of the game?
Suppose I have an array of models, each having it’s own “position” in the world space (scale\*translation matrix). And I have an orthogonal camera. How can I test if model is “visible”, i.e. is in the range of the camera? Like this:

```
        +--------------+
        |              |
xxxxxxxx|xxxxxxxxxxxxxx|xxxxxxxxx
        |              |
        +--------------+

```

I want to know whether x is in a frame or not. Thank you very much in advance, I know it should be a fairly simple (if not trivial) task :)

# Answer
> 9 votes
Here's one way to do it if you don't mind taking advantage of XNA's API, which should work for every case. I can think of a few alternatives but they would involve doing more calculations manually, by taking advantage of the fact that your camera is orthogonal (i.e. the BoundingFrustum is just a box too).

**Step 1) Store BoundingSphere (or BoundingBox) for each model**

You can create the BoundingSphere using the following helper method:

```
BoundingSphere boundingSphere = BoundingSphere.CreateFromPoints(model.Vertices);

```

Ideally this should be done in the content processor and stored in the model, but you can also do it at load time. Don't forget to also Transform the BoundingSphere whenever you move the model.

**Step 2) Create a BoundingFrustum for your camera**

The constructor takes the ViewProrjectionMatrix:

```
BoundingFrustum frustum = new BoundingFrustum(viewMatrix * projectionMatrix);

```

**Step 3) Check for Intersection**

Draw only the models whose BoundingSpheres intersect (or are contained) by the BoundingFrustum:

```
models.Where(m => frustum.Contains(m.BoundingSphere) != ContainmentType.Disjoint).Draw();

```

---

**Extra Notes (Edit)**

I'd like to add a few notes. First the `BoundingFrustum` check is the simplest way to implement it because it's already provided for you by XNA. But it's not the most *efficient* for this case because, since your camera is orthogonal the frustum could be stored as a normal `BoundingBox`. Unfortunately there's no built in way to get this BoundingBox calculated for you automatically. Personally, I wouldn't bother with it until I noticed any performance issues.

Also, one advantage of using a `BoundingSphere` versus a `BoundingBox` for your models (like I commented on Ciarian's post) is that you can easily "move it along" with the model (even when it rotates or scales). This is because for translation you only need to move the center of the sphere, for scaling you only need to scale the radius, and for rotation you don't need to do anything. It's so simple that XNA already has a method for it, i.e. `BoundingSphere.Transform()`.

The `BoundingBox` class on the other hand, doesn't have this facility because it must remain *axis aligned*. To properly transform an axis aligned bounding box, you need to transform *all of its corners* and then *fit a new bounding box around them*!

Some people may tell you to simply transform the `BoundingBox`'s Min and Max values, but that **is not correct** and you'd run into trouble with transformed models - this is a very common pitfall. **I repeat,don't transform an AABB just by transforming its Min/Max values.** I made this picture that shows this problem in 2D but it's exactly the same thing in 3D:

# Answer
> 3 votes
Another possibility in addition to the boundingbox/sphere techniques given above is to use an occlusion query.

Basically how it works is you render a low quality version (unshaded, untextured, possibly just a bounding box itself) and you check to see if there where any fragments actually written. If there where you go ahead and render the full mesh otherwise you can toss out the mesh.

The advantage to this is that if you have a mesh behind an object but still in your fov then it wont get rendered. Of course in order for that to be really effective you need depth-last sorting of your objects (except the transparent ones which are depth-first unless your using some kind of order independent transparency). Transparency ordering is vastly helped by decent spacial data structures.

OpenGL has dedicated occlusion query api functions. I'm not sure about XNA/Direct3D.

In addition to that if you have your meshes stored in a decent spacial data structure (ie BSPs or Octrees) you will probably find that there are quick ways to throw out entire chunks of areas. For example the regions behind your camera can be pruned. In an Octree you could render the entire cube region as just a cube in an occlusion query and see if that entire region needs to be processed at all which would let you skip even bothering to check bounding boxes.

Finally be careful that very large meshes or ones that cross boundaries don't get cut. You could find that you need to calculate the bounding box of the region itself as being bigger than the actual region if you have a large mesh that's half off the region. A simple hack would be to just add the largest bounding box to the regions size.

So basically you can combine all of the above into the following steps:

1. Cull entire regions from BSP/Octree/Quadtree.
2. Perform quick bound checking for more stuff to drop.
3. Render scene depth sorted with occlusion tests and drop anything not rendered.

You can also look at using different level of detail meshes (LODs) based on the distance from the camera (or generating them at real time using geometry/tessellation sharers.

# Answer
> 1 votes
If its an othogonal projection then the Z co-ordinate can be ignored and you can treat it as a 2D bounding box collision problem. Each object should have a bounding box computed for it. You can do this at startup if the objects don't move. The check for trivial rejection using box to box is faster than box to spheres/circles.

Good empirical test and algorithm shown here:

http://www.h3xed.com/programming/bounding-box-vs-bounding-circle-collision-detection-performance-as3

As Dave rightly comments below, moving and rotating the object is more expensive with a bounding box. However if you are doing more drawing ops than update ops, then the trivial reject test is sure to be faster with the BB. With a circle, there are 3 multiplications to compare the distance between two points with a radius value in 2D.

"Final" edit: Test circle vs bounding box trivial reject on your platform for comparison. On a recent C++ test, the two performed more or less the same.

# Answer
> 0 votes
Just thought of this now, if you have your for loop, and a camera in your draw statement make it like so:

```
for(int y = camera.pos.y -= viewHeight / 2; y < camera.pos.y + viewHeight / 2; y++)
   for(int x = camera.pos.x -= viewWidth / 2; x < camera.pos.x + viewWidth / 2; x++)
         sprite.draw(x, y);

```

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


title: Design of networked Asteroids

text:
# Question
Title: Design of networked Asteroids
I am looking for some advice on what would be a good way for users to play Asteroids over the network.

Its my first game and so far I have it working in 2D using polygons across a scrolling world in single player mode. Zoom in and out is also supported. Its not bad. I really want to develop it as a networked game as a learning vehicle. However, given all the work involved I want it to be a game people will enjoy playing.

My plan is that each player gets their own ship, exists in the same world and can shoot the same asteroids. The world can be big enough for ships to avoid each other. I want the players to also be able to attack other players ships.

Normally when playing in scrolling mode your ship stays in the middle of the viewport. This will limit the distance apart that ships can be if you are to see/shoot your opponent. Will this be a problem for the players or do these 2D multi player shooting games work well?

# Answer
> 0 votes
It will limit the distance - which is OK, when not in combat with other ships at which stage it can be frustrating.

Given that you already have the facility to zoom, what I would consider is the following:

* Add a "targeting" button, that can target a ship in the viewport
* When a ship is targeted, adjust the zoom to ensure (up unto a maximum range) that both the targeted and players ships remain in the viewport
* Set a maximum and minimum zoom to ensure that gameplay stays fluidly.

But - as Byte56 said - there is no distinctly correct answer. The only asteroidy multiplayer 2d shooting game I can think of, if you want to see how another game approached it is the now free and open source "Allegiance".

# Answer
> 0 votes
I would go with a client/server model where the rendering is completely decoupled from the universe state. That is to say, the server maintains the definitive state of the entire game universe, and each client does its own rendering based on periodic (or aperiodic) updates from the server.

---
Tags: 2d, game-design, networking
---