title: How does a collision engine work?

text:
# Question
Title: How does a collision engine work?
How exactly does a collision engine work?

This is an extremely broad question. What code keeps things bouncing against each other, what code makes the player walk into a wall instead of walk through the wall? How does the code constantly refresh the players position and objects position to keep gravity and collision working as it should?

If you don't know what a collision engine is, basically it's generally used in platform games to make the player acutally hit walls and the like. There's the 2D type and the 3D type, but they all accomplish the same thing: collision.

So, what keeps a collision engine ticking?

# Answer
> 179 votes
There is a big difference between a collision engine and a physics engine. They do not do the same thing, although the physics engine generally relies on a collision engine.

The collision engine is then split into two parts: collision detection and collision response. The latter is generally part of the physics engine. This is why collision engines and physics engines are usually rolled into the same library.

Collision detection comes in two forms, discrete and continuous. Advanced engines support both, as they have different properties. In general, continuous collision detection is very expensive and only used where it is really needed. The majority of collision and physics is handled using discrete methods. In discrete methods, objects will end up penetrating each other, and the physics engine then works to push them apart. So the engine does not actually stop a player from walking partially through a wall or the floor, it just fixes it up after detecting that the player is partially in the wall/floor. I'm going to focus on discrete collision detection here, since that's what I have the most experience implementing from scratch.

**Collision Detection**

Collision detection is relatively easy. Every object has a transform and a shape (possibly multiple shapes). Naive approaches would have the collision engine do an O(n^2) loop through all object pair and tests if there's overlap between the pairs. In smarter approaches there are multiple spatial data structures (e.g., for static vs dynamic objects), a bounding shape for each object, and multi-part convex sub-shapes for each object.

The spatial data structures include things like KD-Trees, Dynamic AABB trees, Octrees/Quadtrees, Binary Space Partitioning trees, and so on. Each has their advantages and disadvantages, which is why some higher end engines use more than one. Dynamic AABB trees for instance are really really fast and good for handling lots of moving objects while a KD-Tree may be more suitable for the static level geometry that objects collide with. There are other options as well.

The broad phase uses the spatial data structures and an abstract bounding volume for each object. A bounding volume is a simple shape that encloses the entire object, generally with the goal of enclosing it as "tightly" as possible while remaining cheap to do collision tests with. The most common bounding shapes are Axis-Aligned Bounding Boxes, Object-Aligned Bounding Boxes, Spheres, and Capsules. AABBs are generally considered the fastest and easiest (Spheres are easier and faster in some cases, but many of those spatial data structures would require converting the sphere into an AABB anyway), but they also tend to fit many objects rather poorly. Capsules are popular in 3D engines for handling character-level collisions. Some engines will use two bounding shapes, such as an AABB for the first level of detection and then an OABB or Capsule for the second.

The last phase of collision detection is to detect exactly where the geometry is intersecting. This usually implies using the a mesh (or a polygon in 2D), though not always. The purpose of this phase is to find out if the objects really truly do collide, if a fine level of detail is required (say, bullet collision in a shooter, where you want to be able to ignore shots that just barely miss), and also to find out exactly where the objects collide, which will affect how the objects respond. For example, if a box is sitting on the edge of a table, the engine must know at what points the table is pushing against the box; depending on how far the box is hanging over, the box may begin to tilt and fall off.

**Contact Manifold Generation**

Algorithms used here include the popular GJK and Minkowski Portal Refinement algorithms, as well as the Separating Axis test. Because the popular algorithms typically only work for convex shapes, it is necessary to break many complex objects into convex sub-objects, and do collision tests for each individually. This is one of the reasons why simplified meshes are often used for collision, as well as the reduction in processing time for using fewer triangles.

Some of these algorithms not only tell you that the objects have collided for sure, but where they collided -- how far they are penetrating each other and what the "contact points" are. Some of the algorithms require additional steps, such as polygon clipping, to get this information.

**Physical Response**

At this point, a contact has been discovered, and there is enough information for the physics engine to process the contact. The physics handling can get very complex. Simpler algorithms work for some games, but even something as seemingly straight-forward as keeping a stack of boxes stable turns out to be quite difficult and requires a lot of work and non-obvious hacks.

At the most basic level, the physics engine will do something like this: it'll take the colliding objects and their contact manifold and calculate the new positions required to separate the collided objects. It will move the objects to these new positions. It'll also calculate the velocity change resulting from this push, combined with restitution (bounciness) and friction values. The physics engine will also apply any other forces acting on the objects, such as gravity, to calculate the objects' new velocities, and then (next frame) their new positions.

More advanced physics response gets complicated quickly. The approach above will break down in many situations, including one object sitting on top of two others. Dealing with each pair by itself will cause "jitter" and the objects will bounce around a lot. The most basic technique is to do a number of velocity-correction iterations over the pairs of colliding objects. For example, with a box "A" sitting on top of two other boxes "B" and "C", the collision A-B will be handled first, causing box A to tilt further into box C. Then the A-C collision is handled, evening out the boxes somewhat, but pulling A down and into B. Then another iteration is done, so the A-B error caused by the A-C correction is slightly resolved, creating a bit more error in the A-C response. Which is handled when A-C is processed again. The number of iterations done is not fixed, and there is no point at which it becomes "perfect," but rather just whatever number of iterations stops giving meaningful results. 10 iterations is a typical first try, but it takes tweaking to figure out the best number for a particular engine and a particular game's needs.

**Contact Caching**

There are other tricks that turn out to be really handy (more or less necessary) when dealing with many types of games. Contact caching is one of the more useful ones. With a contact cache, each set of colliding objects is saved in a lookup table. Each frame, when a collision is detected, this cache is queried to see if the objects were previously in contact. If the objects were not previously in contact, then a "new collision" event can be generated. If the objects were previously in contact, the information can be used to provide a more stable response. Any entries in the contact cache that were not updated in a frame indicate two objects that separated, and a "separating object" event can be generated. Game logic often has uses for these events.

It's also possible for the game logic to respond to new collision events and flag them as ignored. This is really helpful for implemented some features common in platforms, like platforms that you can jump up through but stand on. Naive implementations may just ignore collisions that have a downward platform-\>character collision normal (indicating the player's head hit the bottom of the platform), but without contact caching, this will break if the player's head pokes up through the platform and then he begins to fall. At that point, the contact normal may end up pointing upward, causing the player to pop up through the platform when he shouldn't. With contact caching, the engine can reliably look at the initial collision normal and ignore all further contact events until the platform and player separate again.

**Sleeping**

Another very useful technique is to mark objects as being "asleep" if they are not being interacted with. Sleeping objects do not get physics updates, do not collide with other sleeping objects, and basically just sit there frozen in time until another non-sleeping object collides with them.

The impact is that all the pairs of colliding objects that are just sitting there doing nothing don't take up any processing time. Also, because there is not a constant amount of tiny physics corrections, stacks will be stable.

An object is a candidate for sleeping when it has had a near-zero velocity for more than a single frame. Note that the epsilon you use for testing this near-zero velocity will probably be a bit higher than the usual floating point comparison epsilon, as you should expect some jitter with stacked objects, and you want whole stacks of objects to fall asleep if they're staying "close enough" to stable. The threshold will of course require tweaking and experimentation.

**Constraints**

The last major bit of many physics engines is constraint solver. The purpose of such a system is to facilitate the implementation of things like springs, motors, wheel axis, simulated soft-bodies, cloth, ropes and chains, and sometimes even fluid (though fluid is often implemented as an entirely different system).

Even the basics of constraint solving can get very math intensive and goes beyond my expertise in this subject matter. I recommend checking out Randy Gaul's excellent article series on physics for a more in-depth explanation of the topic.

# Answer
> 3 votes
The general problem: determine which of all the possible combinations of objects has a nonzero intersect volume.

The naive, general approach is simple: For each possible pair of objects, compute the volume of intersect. This is usually not practical, since it requires O(n^2) relatively expensive intersect operations.

Hence, practical implementations are often specialized, making certain assumptions to allow the avoidance of intersect checks, or reduction of their cost. Spatial partitioning takes advantage of the fact that objects are typically small relative to the total volume, and will typically reduce the number of comparisons to O(n log n). Axis-aligned bounding boxes and bounding spheres provide inexpensive coarse intersect checks, as long as objects obey certain compactness assumptions. And so on.

# Answer
> 2 votes
I think you are a little confused on what you are talking about, and are talking about a few different things.

the ability to say that this item is moved from location X to location Y is based on the physics (this also attacks how they move, and why they move)

the method that is used for collision detection is determined based on the structure of your game. if your game is a large open world then you should greatly consider Space partitioning (quad-tree \[oct-tree for 3D\], BSP, a traditional Grid, or the old fashioned test everything approach)

the best way to implement a collision detection system is to do so in steps.

1. place all objects into a generic bounding volume/shape, and then test those
2. if 1 passed then repeat with a more complex volume/shape repeat until ready to test absolute geometry
3. test absolute geometry the number of time you repeat step 2 is to be determined on the complexity of your shapes, and how accurate those shapes are.

you should consider each of these steps to be early out, and to be for the purpose of eliminating collisions as you go, and only returning true on step3 if they really are touching.

Then for the last part is collision resolution. this determines what happens after you find a collision and have proven that it really is a collision, and what to do about it. this is usually handled by the physics.

the traditional loop looks like this:

```
receive input
update physics
collision detection
collision resolution
render
repeat

```

# Answer
> 2 votes
One "collision engine" I used felt *extremely* easy to grasp.

Basically, API provided a kind of objects having method `collidesWith`, such that

1. its parameters were different kinds of objects that were "eligible" for collision
2. it returned true or false depending on whether collision happened or not
3. there was an option allowing to choose whether all the *bounding rectangles* for the objects trigger collision event or only opaque pixels within these rectangles (pixel-level detection)

In my application, I just periodically invoked `collidesWith` to find out whether collision happened or not.

Pretty simple isn't it?

---

Maybe the only thing that required a minor stretch of imagination was when plain bounding rectangles were not sufficient to simulate geometry of colliding objects. In this case one would simply have to use several collidable objects instead of one.

Generally, when you find out that single collision rectangle doesn't do what you need, you invent a way to decompose things to more rectangular sub-elements so that when combined, these elements simulate / approximate desired behavior.

* End users just don't care how many objects are there behind the scene. They're happy as long as end result feels about like they expect, eg like a house with a backyard fence around it:
>

# Answer
> 1 votes
At the graphics-card level (where you're dealing with usually triangles), the general idea is to partition your scene in some way so you don't have to check all N triangles (this can be done as a pre-processing step), and then figure out where you are in the scene and check only those 10-50 triangles in that partition.

See BSP and Kd trees for more info. There are also other partitioning approaches.

# Answer
> 0 votes
Firstly, I think a collision engine's most important job is to determine what doesn't need to be checked for collision in any particular situation on a frame by frame basis and cull those objects from further checks.

Secondarily, but also important, check in a more detailed (accurate) fashion against the remaining objects that weren't culled in that first step.

Thirdly, utilize the most efficient/appropriate methods to perform the checks.

---
Tags: collision-detection
---


# Question
Title: Android Loading Screen: How do I use a stack to load elements?
I have some problems with figuring out what value I should put in the function:

```
int value_needed_to_figure_out = X;
ProgressBar.incrementProgressBy(value_needed_to_figure_out);

```

I've been researching about loading screens and how to use them. Some examples I've seen have implemented `Thread.sleep()` in a `Handler.post(new Runnable())` function. To me, I got most of that concept of using the Handler to update the ProgressBar, while pretending to do some heavy crunching work. So, I kept looking.

I have read this thread here: How do I load chunks of data from an assest manager during a loading screen?

It said that I can try using a stack it needs to load, and adding a size counter as I add elements to the stack. What does it mean? This is the part where I'm totally stumped.

If anyone would provide some hints, I'll gladly appreciate it. Thanks in advance.

# Answer
> 1 votes
The answer in the another thread is pretty straight forward. But a step by step guide:

> ```
> Make a stack of resources
> Fill the stack, as you fill it, count the size of each object and put in the fullSize var
> in loop, when still have resources in stack, do:
>     pop stack top item
>     load this resource
>     get the loaded resource size and put it on the currentLoaded var
>     update progressbar to currentLoaded / fullSize
>
> ```

As you saw, you get the size of all resources together, this will be the fullSize. And keep another variable together to count what have already been loaded, this will be currentLoaded. Just increase currentLoaded with the last resource loaded size, and get the final percentage with currentLoaded / fullSize.

Was this explanation fine for you?

---
Tags: java, android, assets, loading, preload
---


# Question
Title: SDL and software/hardware rendering. How to go about it?
I know that SDL 1.2 does software rendering (CPU) and not hardware rendering (GPU). My question is, how do I use SDL but with hardware rendering? How do I not use its rendering API (software) and rather a hardware rendering API like OpenGL?

# Answer
SDL supports OpenGL outright. There is a guide in the SDL documentation on how to use OpenGL (This is mainly a SDL tutorial, not an OpenGL one \[it uses a lot of deprecated functionality\]).

You probably also want to change the `SDL_GL_SetAttribute( SDL_GL_RED/GREEN/BLUE_SIZE, 5 );` from `5` to `8` bits per pixel, and also add an alpha channel (`SDL_GL_ALPHA_SIZE`).

After that, you can start using OpenGL like you normally do. Here's a good tutorial - you only need to replace the `glutSomething` functions with their SDL equivalents.

Note that if you use OpenGL with SDL, you can't blit onto the screen surface anymore (it works if you use the right flags, but even then it's deprecated functionality). But you can still use `SDL_image` to load images and use the `SDL_Surface` data to create textures.
> 1 votes

---
Tags: c++, rendering, sdl, hardware, software-rendering
---


title: Smoothing found path on grid

text:
# Question
Title: Smoothing found path on grid
I implemented several approaches such as A\* and Potential fields for my tower defense game. But I want smooth paths, first I tried to find path on very small grid ( 5x5 pixels per tile) but it is extremly slow. I found nice video showing an RTS demo where paths are found on big grid but units dont move from each cell's center to center. How do I implement such behavior? Some examples would be great.

# Answer
There's actually a pretty nice article about this at Gamasutra (7 pages!). While Beizer curves will smooth a path, it won't cut across grid spaces like in your video example.

For example (from the article):

* (a) is the result of a standard A\* search, while
* (b) shows the results of a postprocess smoothing operation.
* (c) shows the application of a turning radius for curved turns.
* (d) illustrates an A\* modification that will enable searches to include curved turns that avoid collisions.
> 5 votes

# Answer
Note that while the Bezier curve answer given by Gajet will smooth the individual links on the path, it won't result in the smoothest or simplest path on its own.

You will need to remove unnecessary nodes from the path first, simplifying the overall path, and then build a curve from that.

Simplifying the path can be done several different ways. The naive way is to just do a line of sight between nodes and remove any needs between them of the line of sight passes. However, this can and will cause the generated paths to occasionally run too close to the corners of walls, causing agents to run into or clip through them.

You can use the line of sight tests from the outer edges of the nodes based on the agent's radius. That is, take the vector between the two nodes, then take the positive and negative normals to that vector, normalized, and add the agent's radius. Add those vectors to the original two nodes' positions, and ray cast between those modified points.

Another option that will fail in more cases but can be cheaper is to just take the box formed by the two nodes and check to see if any walls are in that area.

After you have the simplified path, you can smooth it with a curve if you want. You may not need to, depending on how you want the agents' movement to look.
> 2 votes

# Answer
In addition to approaches mentioned above answers to smooth out paths with some **post-processing**, another approach is to use a grid geometry other than square tiles to get a closer approximation of the optimal path to begin with. Picture below shows the path approximated using square Tiles, Hex, Octal (meaning Tile + diagonal) in comparison to actual optimal path (linear distance).

You can see that Hex and Oct grids give better approximations than square tiles. The picture was take from Peter Yap's paper Grid-based Path Finding. Note that the paper actually recommends Hex over Oct because of performance reasons. The paper also addresses the difficulty of implementing Hex grids (since they can't be treated like simple AABBs), by proposing a new scheme called Tex grids. Tex grids are topologically equivalent to Hex grids (meaning they generate the same 6 degrees per node graph), and thus give same performance in terms accuracy in representing optimal path. Shown below is a typical Tex grid:

Note that the main focus of that paper was actually to improve performance of IDA (Iterative Deepening A\*) search, which will definitely be important in an RTS game I'm sure. It was shown in the paper both from empirical results and math using Hex grids makes IDA exponentially faster than Tiles (square grid).

Downside is, like many papers I've read, it does not give you implementation details.
> 2 votes

# Answer
Try finding a normal path using A\* or BFS or Dijkstra on the grid. Later use a beizer curve and make units move on it. This will generate a smoother path.
> 1 votes

---
Tags: algorithm, path-finding, optimization
---


# Question
Title: Any good web frameworks for asynchronous multiplayer games?
I'm trying to craft a site for web-based (original) board games, and my client (currently written in Actionscript, but that's highly fungible) works fine - I can play solitaire games in the client - but it has nothing to connect to.

What I'm looking for is a server framework for handling accounts/authentication and game tracking: something that would let players log in, show them a list of their current games, let them invite friends to new games, let them make moves in the games they have open, etc. I'm flexible on language; obviously I'm going to have to write a lot of server code to handle the actual game logic, but that should be straightforward enough. I'm more concerned with how to handle the user (and game) DBs, though suggestions for a good server framework for communicating with the DBs (and serving up, most likely, JSON for client communications) are also welcome. Right now my leaning is towards Ruby (probably with Rails) but as far as I can determine it would be a pretty good chunk of effort to set up the necessary databases, so having something automagically handle that - or even just having a good example project that I can check out for a how-to - would be really useful to me.

# Answer
Service Stack for services and serves up XML, JSON etc. Amazing in general for setting up the services. Also cross platform.

As far as 'DB communication', if you are able to use Windows Server for hosting, Entity Framework works well, and very easy to use and code against. There might be alternatives like DbLinq (Linq To SQL for Mono), but haven't tried it so not sure on how easy it is to use. OrmLite is another option and you can get it as a part of ServiceStack framework. **Update**: Entity Framework now works under Mono so windows hosting would be optional for all of the above. See here

Obviously, this is only really an option if you don't mind coding all this in C# and doesn't take care of all the database design you'll have to do, but that kinda goes with game logic.

Hope that helps.
> 2 votes

---
Tags: networking, actionscript
---


# Question
Title: E_FAIL: An undetermined error occurred (-2147467259) when loading a cube texture
I'm trying to implement a skybox into my engine, and I'm having some trouble loading the image as a cube map. Everything works (but it doesn't look right) if I don't load using an ImageLoadInformation struct in the ShaderResourceView.FromFile() method, but it breaks if I do.

I need to, of course, because I need to tell SlimDX to load it as a cubemap. How can I fix this?

Here is my new loading code after the "fix":

```
public static void LoadCubeTexture(string filename)
{
    ImageLoadInformation loadInfo = new ImageLoadInformation()
    {
        BindFlags = BindFlags.ShaderResource,
        CpuAccessFlags = CpuAccessFlags.None,
        Depth = 32,
        FilterFlags = FilterFlags.None,
        FirstMipLevel = 0,
        Format = SlimDX.DXGI.Format.B8G8R8A8_UNorm,
        Height = 512,
        MipFilterFlags = FilterFlags.Linear,
        MipLevels = 1,
        OptionFlags = ResourceOptionFlags.TextureCube,
        Usage = ResourceUsage.Default,
        Width = 512
    };
    textures.Add(filename, ShaderResourceView.FromFile(Graphics.device, "Resources/" + filename, loadInfo));
}

```

Each of the faces of my cube texture are 512x512.

# Answer
The ImageLoadInformation struct does not have sane defaults. You need to make sure they're all set to an acceptable value. You can use the ImageLoadInformation.FromDefaults() function to get a starting value with more appropriate defaults.

EDIT: You don't mention in your post whether you're loading from a DDS file. I don't think D3DX knows how to load a cube texture from any format besides DDS.
> 3 votes

---
Tags: c#, directx11, slimdx, cubemap
---


# Question
Title: New way of integrating Openfeint in Cocos2d-x 0.12.0
I am trying to implement OpenFeint for Android in my cocos2d-x project. My approach so far has been creating a button that calls a static java method in class Bridge using jnihelper functions (jnihelper only accepts statics).

Bridge has one singleton attribute of type OFAndroid, that is the class dynamically calling the Openfeint Api methods, and every method in the bridge just forwards it to the OFAndroid object.

What I am trying to do now is to initialize the openfeint libraries in the main java class that is the one calling the static C++ libraries. My problem right now is that the initializing function

```
void com.openfeint.api.OpenFeint.initialize(Context ctx, OpenFeintSettings settings, OpenFeintDelegate delegate)

```

is not accepting the context parameter that I am giving him, which is a "this" reference to the main class. Main class extends from Cocos2dxActivity but I don't have any other that extends from Application.

Any suggestions on fixing it or how to improve the architecture?

**EDIT:**

I am trying a new solution. Make the bridge class into an Application child, is called from Main object, initializes OpenFeint when created and it can call the OpenFeint functions instead of needing an additional class.

The problem is I still get the error.

```
03-30 14:39:22.661: E/AndroidRuntime(9029): Caused by: java.lang.NullPointerException
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.content.ContextWrapper.getPackageManager(ContextWrapper.java:85)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.validateManifest(OpenFeintInternal.java:885)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.initializeWithoutLoggingIn(OpenFeintInternal.java:829)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.internal.OpenFeintInternal.initialize(OpenFeintInternal.java:852)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at com.openfeint.api.OpenFeint.initialize(OpenFeint.java:47)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at nurogames.fastfish.NuroFeint.onCreate(NuroFeint.java:23)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at nurogames.fastfish.FastFish.onCreate(FastFish.java:47)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1069)
03-30 14:39:22.661: E/AndroidRuntime(9029):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2751)

```

# Answer
The problem was in the Android manifest. My main class inheriting from Application was not added as the main application class in the description.

Once added, the app called a new object and the OnCreate method where I could initialize OpenFeint. As OpenFeint is open you can now statically call the OpenFeint functions to open the different views.
> 1 votes

---
Tags: android, cocos2d-x, jni, openfeint
---


# Question
Title: About online game servers and how to handle data
So my question isn't about what technology to use or how to do this or that, but a more general question.

I'm currently developing a action third person shooter. With elements of RPG - weapon,armor upgrades and items.

Players will be able to create new games or join old ones. So my question is how to create the game server that players will play in. I have two ideas on my mind.

1. The player who made the game is the server. All data passes trough him and he send this data to the server updating the database of the players with their XP points kills/deaths score and other.
2. Or my host machine is the server, the player who made the game just will open new instance on my host and will be like client. And all players send their input data to the host, the host updates the game and send response back to client for any new changes like where is the enemy and other.

And if i choose option 1 is there a chance the host to change the game content and manipulate the game results? (I think there is but i'm not sure)

And if i choose option 2 isn't that raising the response time and potentially the game lag?

or maybe there is another option?

# Answer
> 0 votes
This actually falls to a more complex analysis of your game. In the terms of what needs to be sent across the wire, what needs to be kept on each machine, and what is a system not to be trusted with?

once you answer those questions then you can start to ask the questions of where does the data get held.

In the context of your direct question: a case where the hold machine was the server, and responsible for receiving validating, and updating the other systems is Halo 1 for the PC. This had no checking for connection to that host, and so the host system could be unplugged, and the game would still be going, and then the system would be reconnected, and that system would update the others. To hilarious results of score.

An example of the server simply being a client that started the instance of the game would be more in line with an MMO.

Though this all follows from what you want your data security/validation to act like.

EDIT: it should be mentioned that in some instances letting the player update some of their characters information before validating can still be perfectly fine. For example the player should be able to update their own position (trying to do this all server side can get expensive), but still have it check in with the server every X seconds.

To avoid similar to Halo 1 for PC have the connection tested every X seconds. in terms of expense pinging every 20 seconds is a small price to pay to stop any entity from cheating.

again it is a complex analysis of your game to determine what gets determined where, and if some things are even worth sending.

---
Tags: server, online
---


# Question
Title: What are the pros and cons of a non-fixed-interval update loop?
I am studying various approaches to implementing a game loop, and I have found this article.

In the article, the author implements a loop which, if the processing falls behind in time, skips frame renderings and just updates the game in a loop (the last variant called "Constant Game Speed independent of Variable FPS").

I do not understand why it is acceptable to call `update_game()` in a loop without making sure the update function is called at a particular interval. I do not see any value in doing this. I would think that, in my game, I would want to be sure that the game is updated periodically with a known period.

Maybe it is worthwhile to have two threads, where one would call the update function, periodically, and the other one would redraw the game, also periodically. Of course, I would need to synchronise the threads. Would this be a good and practical approach?

# Answer
> 2 votes
The reason is without custom hardware there is no way to be absolutely sure that the function is called at the exact same interval each time. If it's a PC game, what happens if someone has a slower computer than you expected? Or a faster computer than you expected? Or just Alt-tabbed? If it's a phone game, what happens when a new version of the OS comes out? etc...

Instead you follow the guidelines there, determine a target frame rate, if you've fallen behind update now, if you're ahead, sleep until the targeted frame rate is reached. The update functions take a delta time so that you can interpolate between the desired time and the actual time.

# Answer
> 0 votes
Well, generally things are time sensitive in games, not frame sensitive, so, update is called as often as possible to make sure better (more frequent) times can be achieved. however, the draw call is generally at a specific interval. And, generally games (more complex ones) use threading for specific tasks like managing physics, etc. However, you could have a specific render thread just so the game doesn't lock up. Also, some games do have a fixed/locked timestep for update, but its not required.

# Answer
> 0 votes
This distinction can be based on a lot of factors.

How is your physics going to function? will it be based on a variable frame rate for smoothness to the frames, or will it be based on a fixed frame rate for accuracy of calculations.

How complex will your collision system be, or how many objects might be colliding each frame? (this can be a major bottle neck for variable frame rate let alone bottle neck period)

variable frame rate is the easiest (assuming that your keeping a clock to give to physics, and maybe collisions) in that you just have a loop with a defined break on exit command

for a constant frame rate I have seen, and done it a few different ways.

1. have the same loop as a variable frame rate, and just don't enter it until a minimum amount of time has passed.
2. have a threaded system with physics working on its own, but only wake the physics thread at given increments.

though I would have to mention that if you want a fixed frame rate have some debug write displaying the frame rate to make sure that your not getting to low of a rate. (then start optimizing), and realistically test your game on more then just one system even if you have min requirements.

---
Tags: game-loop
---


# Question
Title: Importing a windows project into android using cocos2d-x
What I am trying to do today is to import a full project to Android, but no tutorials are available for that that I have seen. My approach was to create a new android project, copy all the classes and resources in the folders and calling ./build\_native.sh but I get an error because most of the files are not being included in the project. I tried opening the Android.mk and I can see why "LOCAL\_SRC\_FILES := AppDelegate.cpp \ HelloWorldScene.cpp" are the only files linked.

Should I manually modify the make file or can it be automated by some way I don't know?

Thank you.

**UPDATE:**

I manually added all files and headers to the make file and I get errors linking Box2D or cocosdenshion libraries.

# Answer
The problem was the library naming, as the standard Android project has the library names as "cocos2d" (my project had cocos2dx) and "cocosdenshion" (case sensitive into "CocosDenshion")
> 0 votes

# Answer
just add every file with cpp extention in your project into "LOCAL\_SRC\_FILES list", and of course if you don't have a file named "HelloWorldScene.cpp", remove it from that list.

**UPDATE**

I'm not sure this time but I'm guessing from what I can see inside test project: there are two file with name "android.mk"

1. jni\android.mk
2. jni\tests\android.mk (or equivalent address based on your project name)

in the first file add

```
subdirs := $(addprefix $(LOCAL_PATH)/../../../,$(addsuffix /Android.mk, \
    Box2D \
    cocos2dx \
    CocosDenshion/android \
    ))

```

note that `$(LOCAL_PATH)/../../../` should point at cocos2dx root folder change it if it is not correct

and in the second file this line should do the trick

```
    LOCAL_SHARED_LIBRARIES := cocosdenshion_shared box2d_shared

```
> 1 votes

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


# Question
Title: How to add a sound that an enemy AI can hear?
Given:

* a 2D top down game
* Tiles are stored just in a 2D array
* Every tile has a property - dampen (so bricks might be -50db, air might be -1)

From this I want to add it so a sound is generated at point x1, y1 and it "ripples out". The image below kind of outlines it better. Obviously the end goal is that the AI enemy can "hear" the sound - but if a wall is blocking it, the sound doesn't travel as far.

Red is the wall, which has a dampen of 50db.

I think in the 3rd game tick I am confusing my maths.

What would be the best way of implementing this?

# Answer
It seems like a reasonable idea, do remember though, this is a gameplay feature, don't make it more complicated than what is required for gameplay.

I'd change your scheme to have the sound spread immediately, as that is probably easier to program and seems more consistent with the fast spread of real sound.

This is essentially a pathfinding problem, and it's probably best solved using Dijkstra's algorithm. This a one to many point search (one sound source, multiple enemies), and can as such be solved efficiently by starting at the single point.

You start out by doing a spread from the source, and mark all neighbours that have not yet been marked and have a calculated volume above 0, each of those neighbours you add to a list. That list must be sorted by calculated volume. Then you repeat the process for the highest volume entry on the list, adding new entries to the list as necessary, and removing the one you have handled. Repeat until the list is empty.

Whenever you during this process reach a tile with an enemy you know what volume that enemy hears.
> 7 votes

# Answer
I don't think a path finder is necessary, just ray cast to each AI in the area, if there's a wall in the way, they don't hear it. This would work best with some sort of scene graph + spacial partitioning
> 9 votes

# Answer
I think your implementation assumes that the sound level in a cell is cumulative, and that the amplitude simply moves outwards evenly in all directions. Sound doesn't spread out, frame by frame, it's either playing or it isn't, and you want to find out the amplitude to play it at for any given point.

Raycasting through the tiles is one way (and probably the most effective way) of doing it. Just draw a line between emitter and receiver, and subtract the dampening value of each cell along the way. If the number is positive, you play the sound.

If you want to model indirect sound, then you'll have to path-find. Treat the emitter as the root of your tree, and model each adjacent cell as a linked node. Each link has a cost, subtracted from the current volume. Keep traversing through the graph until either you find the receiver or your volume drops below zero (if it does, backtrack and try another path). If there are no paths to the receiver with a positive volume, your emitter can't be heard. NB: you can't just give up traversing when you find the receiver, because there may be multiple paths from emitter to receiver, and you need the one with the highest volume.

If you're modelling AI that care about where the sound came from, the latter approach will help - an AI would be 'hearing' the sound come from direction of the last segment on the path. Nicely, if there are two audible paths to the receiver, they AI could be confused about the multiple sounds and which direction to take.
> 0 votes

---
Tags: ai, game-mechanics, data-structure, sound
---


# Question
Title: Why shouldn't templates be used on video game consoles?
I have overhead, several times, that templates should not be used on video game consoles; however, I never heard why, or understood why. Why shouldn't templates be used on video game consoles, and if they are to be used, what are some ways to avoid the negativity?

# Answer
> 8 votes
There's nothing really specific to consoles that make templates *uniquely* a bad choice on them. They can certainly be used as a force for good, in appropriate situations. And different people have different reasons to disparage templates. Here are some of the reasons that come to my mind:

**Templates can bloat compile times and executable sizes.** When you include a standard library header, under traditional C++ compilation models *every single file* that needs to include that header will end up parsing and instantiating all the templates in it. And that instantiated copy of the template is stored in every object file that uses it. This is less of a big deal in modern times, thanks to our tools—precompiled headers can speed up compilation for massive headers, and linkers can remove duplicate instantiations. Modern compilers can even take separate instantiations that have identical code (`vector<A*>` and `vector<B*>`, for instance) and merge them. But templates *can* still bloat executable sizes, and *can* lead to absurdly long compilation times. (This may be one of the cases that is more specific to consoles: the compilers used on consoles can often be less mature than the ones used for PC development.)

**Templates are often overused, and lead to overgeneralized code.** So you're thinking of writing a vector class. What design choices are you going to make? Well… we're going to need at least 2-vectors, 3-vectors, and 4-vectors. Mostly `float` vectors, but we'll probably use a few `int` vectors, and I can't say for *sure* that we won't need `double`s in some cases. So let's make this a `vector<T, Size>`. Now how about matrices? Well, that's easy: `matrix< vector<float, 4>, 4 >`. Now one of the most fundamental types in your engine is one of the most complex. Sure, you've got a lot of "power" behind it, but if 99% of the code uses 4x4 `float` matrices and 4-vectors of `float`s, you've actually come out behind, because you don't have simple obvious code for the primary case. And if you want to make your `vector<float, 4>` use SIMD intrinsics, for example, suddenly you have to partially specialize, and *write a full 4-vector of `float`s anyway*.

**Templates make your error messages incomprehensible.** Both compilation errors and linker errors become orders of magnitude more fun to sort through when templates are involved. As a bonus, templates needing to be in headers (sans explicit instantiation) means that any change to a template means that every piece of code that uses that template needs to be recompiled when it changes. Sure, you can compile only *one* file that uses the template to speed up your compile-test-fix cycle, but you can't be sure that you've caught all the errors with only one instantiation of the template, since many template errors are deferred to the point where they're instantiated.

**Templates purport to be future-proof, but rarely are.** Properly designing a template to be future-proof is extremely difficult, and by some metrics impossible without being prescient. The standard library containers and algorithms are very carefully designed and are a cut above most templates, but even the standard library is discouraged in most console game engines. Standard library containers have immensely complicated implementations, don't support alignment well, use exceptions everywhere, are difficult to get to work with external allocators, and are difficult to debug. And they're working in a problem space that is usually cited as a *good* reason to use templates (container types).

**Templated code is complicated.** Doing the "right thing" when making a template leads to extremely complicated code, as anyone who has browsed a C++ standard library implementation knows. And complicated code is harder to understand, harder to optimize, harder to change, and atrophies more quickly. Templates are huge part of the language with very, very weird corner cases (pop quiz: what's strange about ADL with template functions with explicitly provided template arguments?). Simplicity is huge.

I've probably missed some and overstated others. There *are* good reasons to use templates, even in console games, but they are frequently (and for good reason) approached with an attitude that starts with suspicion and may eventually work around to grudging acceptance if good reason is provided. But the average console game simply isn't generic enough for templates to be a necessity (console games typically aren't libraries of code, for instance, expected to be used out-of-house), and there are very good reasons to avoid them.

# Answer
> 5 votes
The answer to your question is one thing, but I think you probably meant something slightly different, so I'll answer both.

**Using Templates**

There is absolutely no reason to avoid templates on a console any more than anywhere else.

Templates by definition only really affect compile time, not runtime. There is an opportunity for templates to be abused in such a way as to result in bloated machine code, as John Calsbeek's answer describes in some detail. However, nothing is console specific about any of the potential problems with templates.

To put it bluntly, your choice to use a template or not should be 100% based on whether a template is the correct way to solve the design problem you're working on. The target platform is entirely irrelevant. There are numerous AAA engines targeting consoles that make heavy use of templates, in fact.

The problems that are solved well by templates are any pieces of code you write that need to be generic to types. Containers are an excellent place to use templates. Utility code that applies to many types -- algorithms, smart pointers/handles, and so on -- are excellent places to use templates. Even some template meta-programming can come in massively useful for handling script binding, serialization, editor GUI property sheet binding, messaging, and even network packet formation (done right, these techniques will have zero or very near-zero runtime overhead and again, being on a console or not will just not matter).

**Standard Template Library**

The C++ STL is a somewhat different matter to templates in general. What you probably heard was that the STL should be avoided on consoles. In fact, even many PC games avoid much of the STL as well. While the STL is a very good library for general purpose programming, it has various weaknesses for games.

The STL containers are often poor fits for games as they're designed to be rather broadly applicable rather than targeted at specific needs. The std::vector container and *maybe* the std::deque are acceptable as-is, but the majority of the other containers are problematic.

Many implementations of std::map for instance are basic binary trees, and your worst case times with them hence don't suit real-time applications like games. You're usually better off writing your own red-black tree container since that way you can know for sure you're getting a data structure with an acceptable worst-case lookup/insertion/removal time.

The worst offender of the containers is the std::unordered\_map (hash table), whose implementation is defined by the standard to have various properties which are not really all that useful in most real code I've seen (including all game code I've seen). Those properties basically mandate a suboptimal implementation. In particular, std::unordered\_map is required to not invalidate references to objects on insert/removal, which means that the map cannot use open-addressing, and hence is going to have sloppy memory usage. The implementation is designed under the assumption that you might be storing expensive to move/copy objects, but in games you'll very rarely be storing anything besides numbers or cheap pointers/handles in these kinds of data structures.

Algorithms like std::sort are implemented in ways that work well in general cases, but which again have abysmal worst-case performance, and honestly just unacceptable average-case performance for the kinds of things that games sort. Most games will only very rarely sort strings or such, but will sort plain integers very often. Hence using a radix sort algorithm is quite likely going to be a much better choice.

The normal STL implementations also tend to make Debug builds abysmally slow due to the abstract nature of their implementation and the excessive debugging checks. EA has an in-house STL implementation that goes out of its way to avoid every unnecessary method call in its internal implementation, so that even in non-inlined debug builds the containers will remain at least reasonably fast. They submitted a paper to the C++ committe on the topic (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2271.html) and apparently published it to GitHub (https://github.com/paulhodge/EASTL).

The allocator model of the STL is also a pain (for games or any other application), and games in general want to have very explicit control over memory. Doubly so for consoles. While this can be worked around with the STL allocator model, it's so painful and obtuse and difficult to use correctly that most games end up using custom container libraries that have non-STL-compliant (but vastly superior for their needs) allocator APIs.

So, it *may* be desirable to avoid using any normal STL implementation for console games. Using a template library that is written with games, real-time simulation, and constrained platforms' needs in mind is a very different proposition, however.

# Answer
> 2 votes
John mentioned some interesting points but I'd like to clarify some points as I feel some points are biased.

**Compile time**

I agree that templates can **increase compile times**. Sometimes it becomes bad enough that you have to take some measures to keep the compile times down (inherit from base code \[in a private namespace\] that uses void\* for data types which the derived template classes then cast to the appropriate type).

You can also force the template to instantiate. This is really useful if the template code is in a library, because then you can instantiate the most common types when compiling the library (which is compiled once) which are ready to use when using said code. Another benefit is that you can now have template code in your source files and not the headers (assuming you know all the types that the code is going to work with... this is usually true with game code as we almost always know what we are working with... it is a closed system). This is great when you know about the types but still want genericity because otherwise you may end up using costly runtime techniques.

> As a bonus, templates needing to be in headers

I disagree with this. For one, the above template instantiation will negate that. Another technique is to split up your functions just like you with a `header` and `source` file but instead name the source file `inl`. Commonly, the `inl` file is included in the header which, after much experience with long compile times and recompile after every small change, I believe is bad practice for all but trivial template classes. What you should do is include the header in the `inl` file, so it looks exactly like a `cpp` file, and then include the `inl` file in your source files. This will reduce the compile times drastically.

**Overuse**

Templates, like any other technique can be overused. You get a hammer, everything becomes a nail. Although I don't see anything particularly wrong with the `Matrix` code John mentions.

**Error Messages**

I agree with John here, that the error messages become hard to read. I also think that that should not be the reason for you to *not* use templates where they make sense. The error messages from the standard containers are very hard to decipher because of the absolutely awful names that they have chosen. For proof, try to follow the standard vector header and then try to read EASTL's vector header. There is a world of a difference. Next, try EASTL in your code and force an error. The errors no longer seem as daunting as they usually are.

**Standard containers**

Don't use them (use EASTL instead). Most of the mentioned problems with containers disappear just by doing this. The common reason for not using standard containers is that games generally do not use exception safety and then there is alignment, both of which are solved by using EASTL.

**Templated code is complicated**

Yes it is. Then again, so is C++ to a programmer who just started using it. There are some corner cases, and some weird areas (not so weird when you understand why it is like that - e.g. when to use `typename`) but that is any language. C++ template meta-programming is a compile time turing complete language (sublanguage). It is extremely powerful and thus requires quite a bit of learning to do it right.

**Static Polymorphism**

You can avoid polymoprhism and its runtime disadvantages (memory usage, cache misses by extra indirections) by using templates and the curiously recurring template pattern.

**Conclusion**

Many will recommend to use templates when they make sense. That is a vague statement. How do you know when it makes sense? Only when you practice it will you start learning when it makes sense and when you went overboard.

Any relatively complex feature of a language goes through the same process. How do you know when to use composition over inheritance or vice versa? There are some rules but mostly it is experience. If you don't use it, you won't gain experience.

My suggestion is that if you are a younger developer (not age wise, but experience wise) then don't shy away from using techniques just because of the bad stigma attached to them. You will not learn how to use the techniques properly down the road, which is very important.

I will give you one last example about multiple inheritance and the diamond problem. I never used multiple inheritance because I was *told* that there is almost always an alternative and multiple inheritance has quite a few complex issues that result is bad code. Were they right? Yes! But should I have never used them? No! Because once I used it, I ran into issues that made me understand the language even more and the technique even more. Multiple inheritance has its uses (especially in meta-programming) and now I know where to use them.

# Answer
> 1 votes
While I have not heard the 'do not use templates on a console', I can maybe give a personal experience as to why people may say this.

Working on a very memory limited console, you of course want the compiler to strip out unused code to compact the exe as small as possible. This actually gave us issues on one platform where the compiler would improperly strip out (or just never compile to begin with) pieces of the templates used for the objects. It did not naturally see that those methods were needed so when the run time would execute, it would crash.

We fixed the issue, but this did cause us a bit of code bloat as we had to forcibly declare the template classes. This added a bit more to the code but it ensured that the code we did need would still be there but allow us to still run code stripping as a compilation option.

Hope this helps.

---
Tags: design-patterns, console
---


title: Drawing lines in 3D space

text:
# Question
Title: Drawing lines in 3D space
When attempting to draw a line in 3D space with `D3DPT_LINELIST`, then Direct3D gives me an error about an invalid vertex declaration, saying that it cannot be converted to an `FVF`. I am using the same vertex declaration and shader/stream setup as for my `D3DPT_TRIANGLELIST` rendering which works absolutely correctly.

How can I use `D3DPT_LINELIST` to render some lines in 3D space?

Edit: Here's my raw Draw call.

```
D3DCALL(device->SetStreamSource(1, PerBoneBuffer.get(), 0, sizeof(PerInstanceData)));
D3DCALL(device->SetStreamSourceFreq(1, D3DSTREAMSOURCE_INSTANCEDATA | 1));
D3DCALL(device->SetStreamSource(0, LineVerts, 0, sizeof(D3DXVECTOR3)));
D3DCALL(device->SetStreamSourceFreq(0, D3DSTREAMSOURCE_INDEXEDDATA | lines.size()));
D3DCALL(device->SetIndices(LineIndices));
PerInstanceData* data;
std::vector<Wide::Render::Line*> lines_vec(lines.begin(), lines.end());
D3DCALL(PerBoneBuffer->Lock(0, lines.size() * sizeof(PerInstanceData), reinterpret_cast<void**>(&data), D3DLOCK_DISCARD));
std::for_each(lines.begin(), lines.end(), [&](Wide::Render::Line* ptr) {
    data->Color = D3DXColor(ptr->Colour);
    D3DXMATRIXA16 Translate, Scale, Rotate;
    D3DXMatrixTranslation(&Translate, ptr->Start.x, ptr->Start.y, ptr->Start.z);
    D3DXMatrixScaling(&Scale, ptr->Scale, 1, 1);
    D3DXMatrixRotationQuaternion(&Rotate, &D3DQuaternion(ptr->Rotation));
    data->World = Scale * Rotate * Translate;
});
D3DCALL(PerBoneBuffer->Unlock());
D3DCALL(device->DrawIndexedPrimitive(D3DPRIMITIVETYPE::D3DPT_LINELIST, 0, 0, 2, 0, 1));

```

Here's my vertex declaration:

```
D3DVERTEXELEMENT9 BasicMeshVertices[] = {
    {0, 0, D3DDECLTYPE_FLOAT3, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION, 0},
    {1, 0, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 0},
    {1, 16, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 1},
    {1, 32, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 2},
    {1, 48, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD, 3},
    {1, 64, D3DDECLTYPE_FLOAT4, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR, 0},
    D3DDECL_END()
};

```

The `LineIndices` are just `0, 1` and the `LineVerts` are just `{0,0,0}` and `{1,0,0}`, to represent a unit 3D line along the X axis.

# Answer
Turns out I just forgot to set the shader to the device.
> 1 votes

---
Tags: c++, directx9
---


# Question
Title: Objective - Gestures while finger touches screen
I'm creating a space cocos2d game with objetive-c. I have in the bottom left 2 arrows to move the sprite left or right. I also implemented a swipe gesture to change weapon, however it only happens when I'm not touching the screen.

I would like the player to change weapons while he's moving the sprite and not have to lift the finger from the arrows and stop moving the sprite to change weapons.

Is there any way I can detect Gestures while having a finger pressed un a buton in thes screen?

# Answer
> 0 votes
If you want to rely just on `UIGestureRecognizers` you will have to use a `UIPanGestureRecognizer`, it will be able to recognize when the user is moving the finger without having to lift it. It does recognizes every movement done after starting holding the finger on the screen.

Of course you will have to cheat a little bit to manage both it and the movement but it will be feasible.

---
Tags: cocos2d-iphone, objective-c
---


# Question
Title: Cocos2d: Adding a CCSequence to a CCArray
I have a problem with an action performed by a sprite. I have one CCSequence in a CCArray and I have an scheduled method (is called every 5 seconds) that make the sprite run the action. The action is performed correctly only the first time (the first 5 seconds), after that, it does not.

Here is the code:

In .h -\>

```
@interface PowerUpLayer : CCLayer {
    PowerUp *powerUp;
    CCArray *trajectories;
}

@property (nonatomic, retain) CCArray *trajectories;

```

In .mm -\>

```
@implementation PowerUpLayer

@synthesize trajectories;

-(id)init
{
    if((self = [super init]))
    {
        [self createTrajectories];
        self.isTouchEnabled = YES;
        [self schedule:@selector(spawn:) interval:5];
    }

    return self;
}

-(void)createTrajectories
{
    self.trajectories = [CCArray arrayWithCapacity:1];

    //Wave trajectory
    ccBezierConfig firstWave, secondWave;

    firstWave.controlPoint_1 = CGPointMake([[CCDirector sharedDirector] winSize].width + 30, [[CCDirector sharedDirector] winSize].height / 2);//powerUp.sprite.position.x, powerUp.sprite.position.y);
    firstWave.controlPoint_2 = CGPointMake([[CCDirector sharedDirector] winSize].width - ([[CCDirector sharedDirector] winSize].width / 4), 0);
    firstWave.endPosition = CGPointMake([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);

    secondWave.controlPoint_1 = CGPointMake([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);
    secondWave.controlPoint_2 = CGPointMake([[CCDirector sharedDirector] winSize].width / 4, [[CCDirector sharedDirector] winSize].height);

    secondWave.endPosition = CGPointMake(-30, [[CCDirector sharedDirector] winSize].height / 2);

    id bezierWave1 = [CCBezierTo actionWithDuration:1 bezier:firstWave];
    id bezierWave2 = [CCBezierTo actionWithDuration:1 bezier:secondWave];

    id waveTrajectory = [CCSequence actions:bezierWave1, bezierWave2, [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil];

    [self.trajectories addObject:waveTrajectory];
    //[powerUp.sprite runAction:bezierForward];

    //        [CCMoveBy actionWithDuration:3 position:CGPointMake(-[[CCDirector sharedDirector] winSize].width - powerUp.sprite.contentSize.width, 0)]
    //[powerUp.sprite runAction:[CCSequence actions:bezierWave1, bezierWave2, [CCCallFuncN actionWithTarget:self selector:@selector(setInvisible:)], nil]];

}

-(void)setInvisible:(id)sender
{
    if(powerUp != nil)
    {
        [self removeChild:sender cleanup:YES];
        powerUp = nil;
    }
}

```

This is the scheduled method:

```
-(void)spawn:(ccTime)dt
{
    if(powerUp == nil)
    {
        powerUp = [[PowerUp alloc] initWithType:0];

        powerUp.sprite.position = CGPointMake([[CCDirector sharedDirector] winSize].width + powerUp.sprite.contentSize.width, [[CCDirector sharedDirector] winSize].height / 2);

        [self addChild:powerUp.sprite z:-1];

        [powerUp.sprite runAction:((CCSequence *)[self.trajectories objectAtIndex:0])];
    }
}

```

I don't know what is happening; I never modify the content of the CCSequence after the first time.

# Answer
You can safely copy and autorelease the action everytime you execute it, so that it doesn't get consumed.

Yes, a `CCAction` can't be used twice without duplicating it. Try with:

```
[powerUp.sprite runAction:((CCSequence *)[[[self.trajectories objectAtIndex:0] copy] autorelease])];

```
> 1 votes

# Answer
As far as I know `CCAction` classes are designed to run only once. You cannot re-use them.

The only way I'm aware of is to call the `init` method (eg. `initWithDuration`) of the action again, but this is bad practice, because `init` should only be called once after construction of the object and might lead to memory-leaks or other issues if called multiple times.

In your case I suggest you modify your `createTrajectories` function to build and return a new `CCSequence` every time (so simply return `waveTrajectory` instead of adding it to the array). Then in your `spawn` function, you could do something like:

```
[powerUp.sprite runAction:[self createTrajectories]];

```
> 1 votes

---
Tags: cocos2d-iphone, cocos2d, objective-c
---


# Question
Title: How do I consolidate the differences between iOS and Android update loops?
I'm currently working on moving some Android-ndk code to the iPhone.

From looking at some samples it seems that the main loop is handled for you and all you've got to do is override the render method on the view to handle the rendering. Then add a selector to handle the update methods. The render method itself looks like it's attached to the windows refresh.

But in android I've got my own game loop that controls the rendering and updates using C++ `time.h`. Is it possible to implement the same here bypassing Apple's loop? I'd really like the keep the structures of the code similar.

# Answer
Short answer is no, although you are allowed to use `pthreads` for all your dirty work I discourage you from doing it just because of multithreading issues that can occur.

Unfortunately all mobile platforms have constraints related to the fact that all the things must be correctly paused and resumed in any moment so it's better to rely on GCD of iOS without wanting to go too much beyond edges (I personally had big troubles with similar issues).

In any case I don't see why you should have to change so much code, you should be able to encapsulate your update functions easily so that your custom scheduler manages them in Android while on iOS you let the OS call them through callbacks. You shouldn't need to change almost anything.
> 1 votes

# Answer
I don't have any serious iOS experience, but this article looks like it might be useful to you. It's basic around using CADisplayLink's ability to help you synchronize your code with the screen's refresh rate.

Like Jack said, the answer seems to be no. Write the system once for both systems and recycle it.
> 1 votes

---
Tags: iphone, game-loop
---


title: Global keyboard states

text:
# Question
Title: Global keyboard states
I have following idea about processing keyboard input. We capture input in "main" Game class like this:

```
protected override void Update(GameTime gameTime)
{
    this.CurrentKeyboardState = Keyboard.GetState();

    // main :Game class logic here

    base.Update(gameTime);

    this.PreviousKeyboardState = this.CurrentKeyboardState;
}

```

then, reuse keyboard states (which have `internal` scope) in all other game components. The reasons behind this are 1) minimize keyboard processing load, and 2) reduce "pollution" of all other classes with similar keyboard state variables.

Since I'm quite a noob in both game and XNA development, I would like to know if all of this sounds reasonable.

**UPDATE:** If someone is interested, actual utility class, as suggested by *David Gouveia*, I've created can be found here.

# Answer
> 12 votes
Yes it's perfectly reasonable, and I could leave it at that!

... but personally I prefer having a bit more encapsulation. So instead of managing the state inside the `Game` class and providing global access to it, I prefer wrapping it in its own class instead.

Here's an example from memory. Not sure if I missed some detail but what's important is the general idea:

```
public static class InputManager
{
    public static void Update()
    {
        _previousKeyboardState = _currentKeyboardState;
        _currentKeyboardState = Keyboard.GetState();
    }

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

    public static bool IsKeyUp(Keys key)
    {
        return _currentKeyboardState.IsKeyUp(key);
    }

    public static bool OnKeyDown(Keys key)
    {
        return _currentKeyboardState.IsKeyDown(key) && _previousKeyboardState.IsKeyUp(key);
    }

    public static bool OnKeyUp(Keys key)
    {
        return _currentKeyboardState.IsKeyUp(key) && _previousKeyboardState.IsKeyDown(key);
    }

    private static KeyboardState _currentKeyboardState;
    private static KeyboardState _previousKeyboardState;
}

```

Then at the top of `Game.Update` I simply call Update on the manager:

```
InputManager.Update();

```

And finally everywhere else on the game I can use the wrapper directly:

```
if(InputManager.OnKeyDown(Keys.Space))
{
    // Shoot once
}

```

Some advantages:

* Like in your solution, there's only one place in the application that needs to manage the current and previous keyboard states.
* But instead of polluting the game class with keyboard processing, it's encapsulated in its own class just for that.
* The class is static making it globally accessible, so that if you don't want you don't need to provide global access to your game class.
* It's also easily reusable - if you start a new project, you can just drop that class in and you're good to go.

---
Tags: xna, architecture
---


# Question
Title: Using XNA's XML content pipeline to read arrays of objects with different subtypes
Using XNA's XML content importer, is it possible to read in an array of objects with different subtypes?

For instance, assume these are my class definitions:

```
public abstract class MyBaseClass
{
    public string MyBaseData;
}

public class MySubClass0 : MyBaseClass
{
    public int MySubData0;
}

public class MySubClass1 : MyBaseClass
{
    public bool MySubData1;
}

```

And this is my XML file:

```
<XnaContent>
    <Asset Type="MyBaseClass[]">
        <Item> <!-- I want this to be an instance of MySubClass0 -->
            <MyBaseData>alpha</MyBaseData>
            <MySubData0>314</MySubData0>
        </Item>
        <Item>  <!-- I want this to be an instance of MySubClass1 -->
            <MyBaseData>bravo</MyBaseData>
            <MySubData1>true</MySubData1>
        </Item>
    </Asset>
</XnaContent>

```

How do I specify that I want the first Item to be an instance of MySubclass0 and the second Item to be an instance of MySubclass1?

# Answer
I managed to answer my own question by hand creating an instance of my object array and then following the instructions in this article to write the array to xml: http://msdn.microsoft.com/en-us/library/ff604982.aspx

Looking at the output, it appears I needed a Type attribute on each Item node to specify the type. So my modified XML file looks like this:

```
<XnaContent>
    <Asset Type="MyBaseClass[]">
        <Item Type="MySubClass0">
            <MyBaseData>alpha</MyBaseData>
            <MySubData0>314</MySubData0>
        </Item>
        <Item Type="MySubClass1">
            <MyBaseData>bravo</MyBaseData>
            <MySubData1>true</MySubData1>
        </Item>
    </Asset>
</XnaContent>

```
> 3 votes

# Answer
Are you writing your own XML importer/exporter, or using the built-in IntermediateSerializer? If you're writing your own, then you have the answer to your own question since you're the one implementing it.

Otherwise, I believe that the built-in IntermediateSerializer just knows to treat deserialized collections as collections and assumes that the named members of your top level objects that contain these collections are able to accept these objects as collection items, otherwise it'll bork. It'd be a pretty lame serializer if you couldn't instantiate subclasses to stick in a base class collection from XML.

I say "believe" because I haven't tried to examine the IL or anything like that. Just going based on my own futzing with it.

I put my first whack at a component system on github just recently, and this is what IntermediateSerializer (should be XNA 4, if not it's 3.1 and 4 likely exports similar data):

https://github.com/michaelbartnett/DaHooch\_XnaComponentArchTest/blob/master/Project%20Da%20Hooch/xmlTest.xml

Here's a snippet:

```
<Level xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Entities>
    <Entity>
      <Enabled>true</Enabled>
      <UpdateOrder>0</UpdateOrder>
      <Name>PLATFORM1</Name>
      <Aspects>
        <Aspect xsi:type="RenderingAspect">
          <Name>renderer</Name>
          <DrawOrder>0</DrawOrder>
          <Visible>true</Visible>
          <CoordinateType>World</CoordinateType>
        </Aspect>
        <Aspect xsi:type="SpriteAspect">
          <Name>sprite</Name>
          <Scale>
            <X>1</X>
            <Y>1</Y>
          </Scale>
          <LayerDepth>0.2</LayerDepth>
          <ImageFile>Sprites/platform</ImageFile>
          <OrientationAspect>collider</OrientationAspect>
          <CoordinateType>World</CoordinateType>
          <DrawOrigin>
            <X>256</X>
            <Y>32</Y>
          </DrawOrigin>
          <Tint>
            <R>255</R>
            <G>255</G>
            <B>255</B>
            <A>255</A>
            <PackedValue>4294967295</PackedValue>
          </Tint>
          <FlipEffects>None</FlipEffects>
          <ImageFrame>
            <X>0</X>
            <Y>0</Y>
            <Width>512</Width>
            <Height>64</Height>
            <Location>
              <X>0</X>
              <Y>0</Y>
            </Location>
          </ImageFrame>
        </Aspect>
        <Aspect xsi:type="BoxCollisionAspect">
          <Name>collider</Name>
          <Position>
            <X>300</X>
            <Y>350</Y>
          </Position>
          <Rotation>0</Rotation>
          <Dimensions>
            <X>256</X>
            <Y>32</Y>
            <Width>512</Width>
            <Height>64</Height>
            <Location>
              <X>256</X>
              <Y>32</Y>
            </Location>
          </Dimensions>
          <Mass>100</Mass>
          <IsStatic>true</IsStatic>
          <CollisionGroup>0</CollisionGroup>
          <Enabled>false</Enabled>
          <UpdateOrder>0</UpdateOrder>
        </Aspect>
      </Aspects>
      <IsTemplate>false</IsTemplate>
    </Entity>
  </Entities
</Level>

```

You'll notice that IntermediateSerializer doesn't even bother specifying the type of `<Entities>` or `<Aspects>`, presumably the Content XML importer knows what to do when it sees a collection.

This is an XML file I generated using the IntermediateSerializer documented on Shawn Hargreaves' blog. The solution is split up into the Content project, and Engine project, a Game project and one Editor project. The only difference between Editor and Game is some #ifdefs that determine whether to export the current state of the scene as as an XML file, or to load an XML file from the Content project so I could see exactly how it was getting serialized and deserialized.

Here's the stripped down game class to illustrate what I'm talking about:

```
class Game1 : Microsoft.Xna.Framework.Game
{

    private Level level; // Level class contains Entities, which are built out of Aspects (component system)

    /// <summary>
    /// LoadContent will be called once per game and is the place to load
    /// all of your content.
    /// </summary>
    protected override void LoadContent()
    {
#if EDITOR
            FirstLevel.LoadFirstLevel(level, this); // Static class method that instantiates game objects
#else
        level = Content.Load<Level>("xnaXmlTest2");
#endif
        level.Load(this);
    }

    /// <summary>
    /// Allows the game to run logic such as updating the world,
    /// checking for collisions, gathering input, and playing audio.
    /// </summary>
    /// <param name="gameTime">Provides a snapshot of timing values.</param>
    protected override void Update(GameTime gameTime)
    {
        currentGameTime = gameTime;
        var keyboardState = Keyboard.GetState();

        if (keyboardState.IsKeyDown(Keys.Escape))
        {
#if EDITOR
            if (levelMode == SAVE_MODE)
            {
               Entity player = Entity.GetEntityByID(FirstLevel.PlayerID);
               string filePath = Content.RootDirectory + @"\..\..\..\..\Content\xnaXmlTest2.xml";
               FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
               IntermediateSerializer.Serialize<Level>(XmlWriter.Create(file), level, filePath);
            }
#endif
            this.Exit();
        }

        level.Update(gameTime);

        base.Update(gameTime);
    }
}

```
> 0 votes

---
Tags: xna, c#, xna-4.0, xml, xna-content-pipeline
---


title: Early Z culling - Ogre

text:
# Question
Title: Early Z culling - Ogre
For Ogre experienced people, but also experts in the field: Early Z culling is sometimes quite desirable, and that's what I tried to do in Ogre by using a two pass material. The first one is writing to the Z Buffer, but not to the frame buffer. This is how it looks like:

```
 pass EarlyZ
    {
        texture_unit TU0
        {
            //ambient diffuse texture
            texture $TU0_TEXTURE
            tex_coord_set 0
            filtering trilinear
        }
        //cull_software none
        //cull_hardware none
        lighting off
        colour_write off
        shading flat
        //scene_blend alpha_blend
        alpha_rejection  greater_equal 200
        depth_bias  -5 -5 // ugly hack - without it, objects tend to flicker
    }

```

The biggest problem I get is with alpha objects and shadows. For example, now I can't get tree impostors to cast correct shadows instead of blocks. Although they are rendered correctly, the PSSM isn't working correctly, so the shadows tend to look like stencil shadows. Any ideas on how to fix it? **As many people said: is it possible to perform early Z culling and still have transparent objects in the scene? If yes, some hints to do it in Ogre?** Here are some screenshots:

# Answer
> 6 votes
Your alpha-blended objects should not participate in a depth pre-pass. For a given final pixel, its color will be a number of colors blended together at different depths: the portion of the color furthest away from the camera will either be the sky/background or an opaque object, and all the other contributions will be from semi-transparent objects. And if you draw *everything* in a depth pre-pass, then the depth in the depth buffer will always be the **closest** contributing object (a semi-transparent object), not the **farthest** contributing object (an opaque object or sky/background element).

Note that alpha-*tested* objects are fine, as long as the pixel shader that performs the testing is actually being run on the depth pre-pas.

---
Tags: shaders, ogre, shadows, depth-buffer, transparency
---


# Question
Title: How to load a text file from a server into iPhone game with AS3 in Adobe AIR?
Im creating an iPhone game with Adobe AIR, and I want to be able to load a simple text msg into an dynamic text box on the games front screen from my server (and then be able to update that text file on the server, so it updates automatically in the game after the game is on the app store) How would I go about acheiving that? is it as simple as using a getURL? are there any specifical issues with trying to do this on the iPhone via AIR that I should be aware of?

Thanks for any advice.

# Answer
You could just use an `URLLoader` as you would with a classic flash application.

Something like that:

```
var request:URLRequest = new URLRequest("url to load");
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE,
    function(event:Event)
    {
        _myTextField.text = URLLoader(event.target).data as String
    }
);

```

There's no restriction on iOS regarding loading external URLs (as long as you ain't loading and interpreting code), but you should check if your user has an internet connection before trying to load the URL and handle it. You might also want to cache the returned file.
> 1 votes

---
Tags: iphone, ios, server, file
---


# Question
Title: .NET WCF as backend server for iPhone games
I'm planning to develop an iPhone game. Is it possible to use .NET WCF as a backend? The server would be windows 2008 and MS-SQL database.

# Answer
> 0 votes
SOAP has a lot of XML overhead! And parsing XML is always slow. Especially on mobile devices. Use REST and JSON. There even is something like JSON-RPC, just google for it.

---
Tags: iphone, .net
---


# Question
Title: How to render a retro-like pixel graphics from 3d models?
I was wondering if there's a possibility to render a retro-pixel-like graphics from 3d model in real time?

I'm talking about the Starfarer-like graphics. I know it's hand drawn, and it's 2d. But if I need a 3d objects with the same aesthetics?

I'm currently working with Flash. But I don't need any ready-solutions, I just want to understand the principle from any other platform if there is one. So if anybody met anything like this I would appreciate your help. (If it's not possible to do in real time, I could at least pre-render a sequence of sprites. It would be much better than creating hundreds of hand-drawn ones)

# Answer
> 1 votes
In 3D those kind of aesthetic effects can be done via a combination of shaders and textures. From the photos you provided, you could probably replicate the effect in 3D using cel-shading (essentially a toon-shader). Cel-shading basically defines hard-cutoffs for colors when computing lighting, giving the object a hand-drawn look. Here's a few examples.. The most important part of getting the effect you're looking for though would be in the texturing of the models. I would say texture them with the same art style and it would look great.

Definitely something you can do in real-time :)

# Answer
> 5 votes
Firstly the main thing would be to render them at a lower resolution and scale them up without anti-aliasing for the pixelated effect. Old dos style games where often at resolutions like 320x240. 640x480 would have been fairly high res back then. Just doing that would give you a Quake 1 played on a 486DX graphics style. I would recommend doing them at 1/2, 1/4, 1/8 or whatever the resolution of the final screen to ensure that pixels are doubled exactly so you don't end up with any half pixels. Otherwise you can just choose an old dos resolution and scale it up, you might get some half pixels but since you are dealing with the whole screen it shouldn't matter.

The rest of it will depend how 3D your game needs to be and exactly what retro effect you want. Exactly what movements/rotations you will be supporting for your objects/world, full 3D? restricted 3D? or just 2D (in which case why bother with 3D at all). Also it will depend on your game content, are you creating it from scratch in which case you can ensure your models are built for the retro style graphics you want or are you trying to process normal models.

Another way would be to limit the colour pallet to something like 256 colors. Some games used index colour pallets where they could pick any RGB color they wanted but could only draw 256 unique colours on the screen at once. The problem with doing that automatically is it tends to give ugly results and since the pallet is for everything that could possibly be on the screen at once generating it live would mess up the chosen colors. Maybe if you specify the pallet manually but let the programming pick the best available color. If you know your ship is beige then you would force you pallet to have 2 or 3 possible beige colours and hope that your algorithm picks the correct beige based on the shading. Or course you don't have to actually restrict yourself to a pallet like that, you could just try faking it with toon shading.

Lighting will also be an issue. For pixel art it's generally artists interpretation of lighting. It can involve ray-traced like effects such as soft shading, soft shadows, light scattering, light reflection and so on. Or perhaps no lighting at all. For the Starfarer-like effect the best choice would be to look at SSAO to get that soft shading. You would need to combine that with shadows.

In retro games lights might rotate with the object as you only have 1 sprite that gets rotated (although it would probably be better to leave off that and light them properly since you can).

Fix your objects to pixel positions, stop 'half' pixels. Don't draw an object at pixel coordinates 539.4 x 480.0. Force it to be at either 540x420 for 539x420. Try and ensure that your 3D model's vertex coordinates are snapped to a grid.

Objects would have been made up from a sheet of sprites. Since they are hand crafted and memory was limited the number of positions and object could be in would have been fairly limited. When you rotate the sprites, maybe rotate them and specific fixed rotations so they jump from 1 rotation to the next rather than a smooth rotation. For example allow only 8 possible directions (maybe more directions depending on how good you want your graphics. An older top down game might have only included 2 images for all possible rotations vertial/horizontal and a diagonal.

If you require depth you will have to do something similar with objects effectively jumping from 1 depth level to the next, objects coming closer would have originally either been the original image redrawn by hand to get bigger over multiple frames or possibly just the original image scaled up. Animation would be yet another example with jumping between different keyframes rather than a smooth transition from 1 state to the next.

That kind of thing will stop pixel 'twinkling' and 'popping' into existence as some threshold is passed, making it look less like you took 3d content and ran it through some kind of pixelation filter and more like the retro games. As your sprite moves across the screen it should be pixel by pixel identical for each position it is in. Perhaps pre-render your objects into 2D sprites.

Depending on your game style, Try and turn off or limit any kind of perspective transformation too. If you have a top down of a guy running down a corridor you will either want the sides of the walls to not be visible or isometric walls (in which case you might do perspective but with specific angles (ie 45° angles and ensuring that pixels at the top of a wall are on the same pixel grid at the bottom. Or maybe you will just get flat front facing walls).

You might want to have outlines around things (for example the detailed components of the ships in the linked images such as the weapons/engine pipes seemed to). They could be soft or hard. There are various shaders that give outline effects. I would recommend manually tagging the bits of your mesh that will be outlined. Some of it seems to be done to give an appearance of depth (which as a pipe going under another) it does seem like there should be a way to do it based on the sudden change in depth, I would recommend looking at applying a sobel edge filter to your Z-Buffer.

---
Tags: 3d, graphics, flash, models
---


# Question
Title: Simple thruster like behaviour when rotating sprite
I'm prototyping some 2D game concepts with XNA and have added some basic keyboard inputs to control a triangle sprite.

When I press key up the sprite accelerates in it's current facing direction, when I release the key it brakes down.

For rotation, when I press left/right keys I rotate the sprite.

Currently the sprite immedately changes direction when I rotate it. What I want is for it to keep moving in the same direction when I rotate, until I hit key up, adding thrust in whatever direction the sprite is pointing at.

This would simulate thrusters on a classic space shooter like Asteroids.

I'm adding an image to describe the behaviour I'm after and some code samples of how I'm doing things at the moment.

This is my player struct, holding information of the sprite.

```
    public struct PlayerData
    {
        public Vector2 Position;  // where to draw the sprite
        public Vector2 Direction; // travel direction of sprite

        public float Angle;       // rotation of sprite

        public float Velocity;
        public float Acceleration;
        public float Decelleration;
        public float RotationAcceleration;
        public float RotationDecceleration;

        public float TopSpeed;
        public float Scale;
    }

```

This is how I'm currently handling thrusting / braking (when pressing/releasing key up) (simplified, removed some bounds checking etc):

```
player.Velocity += player.Acceleration * 0.1f;
player.Velocity -= player.Acceleration * 0.1f;

```

And when I rotate the sprite left and right:

```
player.Angle -= player.RotationAcceleration * 0.1f;
player.Angle += player.RotationAcceleration * 0.1f;

```

This runs in the update loop, keeps the direction updated and updates the position:

```
Vector2 up = new Vector2(0f, -1f);
Matrix rotMatrix = Matrix.CreateRotationZ(player.Angle);
player.Direction = Vector2.Transform(up, rotMatrix);

player.Direction *= player.Velocity;

player.Position += player.Direction;

```

I am following along various beginner tutorials and haven't found any describing this, but I have tried some on my own without success. Do I need to change my velocity and acceleration fields to Vectors instead of floats to accomplish this type of movement? I realise my `Angle` and the `Direction` vector is currently tied together and I need to disconnect these somehow to be able to rotate freely without changing the direction of the movement, but I can't quite figure out how to do this while keeping the acceleration/decceleration functional.

Would appreciate an explanation rather than pure code samples.

Thanks,

# Answer
You're actually very close to the behavior you want. You just need to decouple the direction the player is facing and the direction he's moving.

The only value the angle of the player should affect is the thruster force. Each frame, you'll calculate the total acceleration vector of the player as the sum of the forces that are acting upon him, in this case, just your thruster:

```
Vector2 up = new Vector2(0f, -1f);
Matrix rotMatrix = Matrix.CreateRotationZ(player.Angle);
Vector2 thrusterForce = Vector2.Transform(up, rotMatrix) * thrusterPower;

player.Acceleration = thrusterForce;

```

Then you can apply the acceleration to the player's velocity:

```
player.Velocity += player.Acceleration * deltaTime * deltaTime;

```

Notice that the acceleration is multiplied by deltaTime (the amount of time that elapsed since the last frame) twice. This is because the units of acceleration are meters per second **squared** (assuming meters are your unit of length).

Finally you can move the player by the velocity:

```
player.Position += player.Velocity * deltaTime;

```

What's important here is that the direction the player is moving is always the direction of the player's velocity, and not the angle the player is facing. The velocity will change over time when the thruster is being used, giving the player the sliding behavior reminiscent of Asteroids that you're looking for.
> 4 votes

# Answer
Something very simple like this should work :

```
//some constants
const float rotation_vel = ...;
const float thrust = ...;

if(keyup)
{
   player.velocity.x += cos(player.angle) * thrust;
   player.velocity.y += sin(player.angle) * thrust;
}

if(keyleft)
{
   player.angle -= rotation_vel;
}

if(keyright)
{
   player.angle += rotation_vel;
}

player.position += player.velocity;

//draw player sprite at position player.position and with angle player.angle
...

```
> 1 votes

---
Tags: xna, sprites, rotation
---


# Question
Title: Why does calling CreateDXGIFactory prevent my program from exiting?
I'm using CreateDXGIFactory to get the graphics adapters and display modes. When I call it, it works fine and I get all the data. However, when I exit my program, the main Win32 thread exits, but something stays open because it keeps debugging. Does CreateDXGIFactory create an extra thread and I'm not closing it? I don't understand. The only thing I would suspect is that in the documentation it says it doesn't work if it's called from DllMain. It is in a DLL, but it's not called from DllMain. And it doesn't fail, either.

I'm using DirectX 11.

Here is the function that initializes DirectX. I haven't gotten past retrieving the refresh rate because of this problem. I commented everything out to pinpoint the problem.

```
bool CGraphicsManager::InitDirectX(HWND hWnd, int width, int height)
    {
        HRESULT result;

        IDXGIFactory* factory;
        IDXGIOutput* output;
        IDXGIAdapter* adapter;
        DXGI_MODE_DESC* displayModes;
        DXGI_ADAPTER_DESC adapterDesc;

        unsigned int modeCount = 0;
        unsigned int refreshNum = 0;
        unsigned int refreshDen = 0;

        //First, we need to get the monitors refresh rater
        result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
        //if(FAILED(result))
        //{
            //MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to create DXGI factory\nError:\n%s"), DXGetErrorDescription(result));
            //return false;
        //}

        /*//Create a graphics card adapter
        result = factory->EnumAdapters(0, &adapter);
        if(FAILED(result))
        {
            MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to get graphics adapters\nError:\n%s"), DXGetErrorDescription(result));
            return false;
        }

        //Get the output
        result = adapter->EnumOutputs(0, &output);
        if(FAILED(result))
        {
            MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to get adapter output\nError:\n%s"), DXGetErrorDescription(result));
            return false;
        }

        //Get the modes
        result = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &modeCount, 0);
        if(FAILED(result))
        {
            MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to get mode count\nError:\n%s"), DXGetErrorDescription(result));
            return false;
        }

        displayModes = new DXGI_MODE_DESC[modeCount];
        result = output->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &modeCount, displayModes);
        if(FAILED(result))
        {
            MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to get display modes\nError:\n%s"), DXGetErrorDescription(result));
            return false;
        }

        //Now we need to find one for our screen size
        for(unsigned int i = 0; i < modeCount; i++)
        {
            if(displayModes[i].Width == (unsigned int)width)
            {
                if(displayModes[i].Height == (unsigned int)height)
                {
                    refreshNum = displayModes[i].RefreshRate.Numerator;
                    refreshDen = displayModes[i].RefreshRate.Denominator;
                    break;
                }
            }
        }

        //Store the video card data
        result = adapter->GetDesc(&adapterDesc);
        if(FAILED(result))
        {
            MemoryUtil::MessageBoxError(TEXT("InitDirectX"), 0, 0, TEXT("Failed to get adapter description\nError:\n%s"), DXGetErrorDescription(result));
            return false;
        }
        m_videoCard = new CVideoCard();
        MemoryUtil::CreateGameObject(m_videoCard);

        m_videoCard->VideoCardMemory = (unsigned int)(adapterDesc.DedicatedVideoMemory);
        wcstombs_s(0, m_videoCard->VideoCardDescription, 128, adapterDesc.Description, 128);*/

        //ReleaseCOM(output);
        //ReleaseCOM(adapter);
        ReleaseCOM(factory);
        //DeletePointerArray(displayModes);

        return true;
    }

```

Also, I don't know if this means anything, but this is some of the output log when the function is commented out:

```
//...
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\msvcr100d.dll', Symbols loaded.
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\imm32.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\msctf.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\uxtheme.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Program Files (x86)\Common Files\microsoft shared\ink\tiptsf.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\ole32.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\oleaut32.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\clbcatq.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\oleacc.dll', Cannot find or open the PDB file
The program '[6560] LostRock.exe: Native' has exited with code 0 (0x0).

```

And when it isn't commented out...

```
//...
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\cfgmgr32.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\devobj.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\wintrust.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\crypt32.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\msasn1.dll', Cannot find or open the PDB file
'LostRock.exe': Unloaded 'C:\Windows\SysWOW64\setupapi.dll'
'LostRock.exe': Unloaded 'C:\Windows\SysWOW64\devobj.dll'
'LostRock.exe': Unloaded 'C:\Windows\SysWOW64\cfgmgr32.dll'
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\clbcatq.dll', Cannot find or open the PDB file
'LostRock.exe': Loaded 'C:\Windows\SysWOW64\oleacc.dll', Cannot find or open the PDB file
The thread 'Win32 Thread' (0xb94) has exited with code 0 (0x0).

The program '[8096] LostRock.exe: Native' has exited with code 0 (0x0). //This is called when I click "Stop Debugging"

```

---

P.S. I know it is CreateDXGIFactory because if I comment it out, the program exits correctly.

# Answer
> 0 votes
I figured it out. For some reason the project was set to be a console project, I must have accidentally changed it. I noticed the console window flash when I started the game, and I changed it back. Now it works.

# Answer
> 2 votes
No, DXGI doesn't do anything like that. Are you creating threads elsewhere in your program? Are you sure your thread isn't actually getting stuck on some cleanup call and hanging? Step through with a debugger if you can to see if your main thread is actually exiting, and do an audit of any places you create and release threads.

---
Tags: directx11
---