title: video card architecture

text:
# Question
Title: video card architecture
Can anyone point me to some information on what a modern video card architecture looks like? I'm particularly interested in understanding how my rendering engine will be executed by the GPU.

Ideally, I'd get two answers: one related to today's monster video cards and one related to today's mobile GPU's.

-- edit follows

Thanks for the input so far. Considering the proprietary and changing nature of video card hardware, it seems there's not the ideal answer that I was looking for. So I'll clarify and ask a couple very specific questions. (I guess I was hoping to get a resource similar to http://www.realityprime.com/articles/scenegraphs-past-present-and-future which would generally provide me with lots of information on hardware that might be relevant to me.)

First off, I'm quite familiar with the OpenGL pipeline. A google-images search for my question title, "video card architecture," reveals diagrams of various video cards which naturally seem to match the graphics pipeline. While this makes sense, and is helpful, it leaves out some details. I'll try to get at a couple specifics.

1) What happens when a texture change (glBindTexture(), or new sampler specified) is issued? Obviously, the command is queued and later processed by the video card, but is the texture loaded immediately into cache, or not until something attempts to sample that texture? I would expect the latter, partly because the texture may not entirely fit into such caches to begin with. How big are these caches, anyway?

2) Older video cards had hardware dedicated specifically for a given type of shader. Newer video cards reuse the same hardware for all types of shaders. Are these "stream processors" typically shared with other computations throughout the pipeline, such as culling?

3) It seems that progress related to video card hardware has largely been lead by innovation in software. Are there any interesting cases where the opposite is true? I still hope that there might be some resource that gives a detailed history of video card design, similar to the scenegraphs article linked above.

4) Mobile GPU was an ambiguous term. I'm hoping that eBusiness assumed I meant mobile as in laptop when he called me ignorant -- I was rather referring to the GPUs embedded in modern cell phones and tablets.

# Answer
Not all GPU architecture is that hidden, it really depends on the company.

Imagination for example :)

Many mobile devices use the PowerVR SGX, which you can see has a USSE where multiple shader processing units are added as necessary. These take care of your shaders, the culling, etc is generally done elsewhere.

These GPU's often use Tile Based Rendering as it can allow optimizations especially in shader time.

There is also a tendancy to make blending part of the programmable pipeline, where either you reprogram a specific blending chip, or the blending is included in the shaders, see the VR Core.

You can get lots of info about their specific GPU, its definately a good start.

I also found this article about the XBox360 chip layout.

And for your other questions : 1) I don't think it would be easy to see how the data is cached, I would guess the mentality is more 'load things into cache and keep what we think will be needed later', generally caches are small though, because it's very fast, expensive memory.

2) As stated, you generally have many different things going on outside of the shaders (see this). An easy example is the Rasterization & Interpolation getting your from Vertex positions, to thousand of fragments with an interpolated color, which is done on the GPU.

3) Shaders came from Pixar :)

4) I didn't think it was ambiguous, what is also interesting are the Intel HD chips that are directly integrated into the Core ix's.
> 1 votes

# Answer
A lot of architecture information hare hidden behind NDA:s so it might be hard to give a good answer accurate to the current state. You might want to read this nvidia article that describes how the GeForce 6 works.

Of course a lot has changed since, vertex/fragment units have been unified and can be load balanced, but the overall architecture (that you need to know about for writing general apps) is pretty much the same. More shading stages has been added, and a few more fixed function steps (tesselator etc.) These works very much the same way as the steps in the nvidia article, except that they pull computation resources from a pool of units.

As said by seanmiddleditch in his answer, AMD has released a lot of specifications of their chips. You can find them here. Especially the Radeon R6xx/R7xx Acceleration PDF should be of interest to you.
> 1 votes

# Answer
I'm not aware of any hardware-level design documentation, but there's plenty of information publicly available on hardware interfaces and behaviors that might help you out.

AMD has programming information for their GPUs available on their developer portal, which in turn explains how the hardware works in a high level way.

The Direct3D documentation from Microsoft also fairly clearly explains at a high level how the 3D pipeline used by basically all GPUs works.

Finally, you can also look at Mesa3D, which is a complete Open Source implementation of software OpenGL, which basically means an "emulator" for a generic modern GPU. (Plus Mesa includes hardware drivers for many modern GPUs, including most AMD and some NVIDIA GPUs, which you could also study if the public documentation isn't enough for you.)
> 1 votes

# Answer
OK, this is the full blown programmers manual (and I think a dated one) for CUDA which gives a lot of details on the nvidia architecture. It seems overwhelming but if you just start going through it I think you will find that the diagrams along with the explanations of them can be very helpful.
> 1 votes

# Answer
> 1) What happens when a texture change (glBindTexture(), or new sampler specified) is issued? Obviously, the command is queued and later processed by the video card, but is the texture loaded immediately into cache, or not until something attempts to sample that texture? I would expect the latter, partly because the texture may not entirely fit into such caches to begin with. How big are these caches, anyway?

I'm not sure of the size of the caches. However, everything pretty much is load-on-demand for the GPU- after all, what happens if I want to use that cache due to a queued command between now and when the that particular texture change is queued?

> 2) Older video cards had hardware dedicated specifically for a given type of shader. Newer video cards reuse the same hardware for all types of shaders. Are these "stream processors" typically shared with other computations throughout the pipeline, such as culling?

As far as I know, every operation which is not explicitly shadable is implemented in hardware. This is faster, but also, the shaders in modern games can dominate the performance very strongly- you're mostly shader-limited.

> 3) It seems that progress related to video card hardware has largely been lead by innovation in software. Are there any interesting cases where the opposite is true? I still hope that there might be some resource that gives a detailed history of video card design, similar to the scenegraphs article linked above.

Pretty much no. This is because every technique can be implemented in software before it can be implemented in hardware- and indeed, software implementation first would be necessary to learn about relative performance, what data it depends on, and things like that, and the output of compiling programs can be used to determine what kind of hardware is needed, gauging developer demand, that kind of thing. That's ignoring all the time it would take to implement in hardware, of course.

One case that I *can* name, effectively, is concurrency in CPU design, where the necessity of moving to multiple cores in hardware has spawned massive concurrency efforts in software. Of course, software threads existed before, but concurrency was nothing like as it is now.

> 4) Mobile GPU was an ambiguous term. I'm hoping that eBusiness assumed I meant mobile as in laptop when he called me ignorant -- I was rather referring to the GPUs embedded in modern cell phones and tablets.

They're basically just desktop GPUs, but downscaled. This is because desktop GPUs are still very optimized pieces of hardware performing a dedicated function, giving them much implementation experience and optimization, and developer existing knowledge. If you have a mobile GPU that works completely differently, then nobody is gonna figure out how to use it, it's gonna be much slower (relatively to how it would be), etc. Of course, some systems require changing to be mobile-feasible, but in the general case, it's the best idea to downscale what's available for desktop. This is not quite the same for CPUs, as mobile CPUs have also been around for a long time.
> 1 votes

# Answer
> 1) What happens when a texture change is issued?

Most chips simply change where the texture sampler requests memory from. I know of no chip that preloads textures in caches, simply because textures tend to be way bigger than the caches, and with multiple textures, it makes even less sense. Moreover, most PC chips have multiple texture samplers, with dedicated caches. And you certainly don't want to load all the caches with the same data.

To give you an idea, with a back-of-the envelope math: preloading would mean transferring all the texture memory of all the active textures each frame (something along the line of 300MB for a mid-range title, 1GB+ for high-end titles). Whereas just loading the parts of the texture that are effectively used brings that down to about ~30MB-100MB / frame (very broad strokes, thinking 1-2 megapixel, with an average of 30B-50B/pixel texture data). The cost of preloading is higher than not by up to an order of magnitude, ignoring the issue of whether it can fit.

The main issue with not preloading is hiding the latency of the memory fetches. GPUs are built to hide this latency (by typically running many threads at the same time on a single processor)

> 2) Are these "stream processors" typically shared with other computations throughout the pipeline, such as culling?

It depends on the hardware. Some chips are known to do clipping on the processors, e.g. (though culling is easy enough to do in pure h/w). Many mobile chips do the blending et al. alongside the fragment shader, as opposed to dedicate hardware for it. There's even an nvidia extension to do that yourself in the shader as opposed to use the fixed function state: nv\_shader\_framebuffer\_fetch.

> 3) It seems that progress related to video card hardware has largely been lead by innovation in software. Are there any interesting cases where the opposite is true?

I'm not sure what you're after with this question. Hardware vendors do not add features on a whim. They do so because they see value in them being used by software (even if it's not today's software). Can you be more specific maybe ?

> 4) I was rather referring to the GPUs embedded in modern cell phones and tablets.

GPUs in cellphones today are mostly Imagination or Tegra. Those 2 architectures already have very different structures. The Imagination ones (SGX parts) are fairly well documented on their websites (and use a tiled-base architecture. See 3nixios good answer on this). Tegra less so. All I could find was that Tegra 2 is not unified, pointing to a hardware base that is ~DX9.
> 0 votes

---
Tags: architecture, hardware, visualization
---


# Question
Title: Rotate the camera around the model in XNA?
How can I rotate my view around a model? My model has a rotation. If this rotation changed, my view should also change.

The camera should be behind the model everytime.

Thank you very much!

# Answer
> 1 votes
One thing you can do is to position your camera such that the mounting point is 0, 0 relative to the camera. So a camera position of (0, 100, 50) would be up by 100 and back by 50 from the model you want it to follow.

From there, apply the rotation matrix for the model on the camera's position, this will rotate the offset to the proper position given the rotation of the model. From here simply add the model's Position to the camera's and voila, you have the correct new position!

Now your camera is positioned properly, but your camera is still pointing in the same direction it was before. From here you can either set the LookAt to some position based on the model's world position or rotate your LookAt in a similar fashion to the method used on the camera's position.

Make sure when you rotate your camera's Position or LookAt that it is based on a variable separate from the one you will use to construct your assorted camera matrices. If you only store the current value for the position you are at, and you say to rotate 90 degrees, it can continue to spin every frame! You can still change these starting values for camera effects, just make sure that they are relative changes (such as +y to make the camera go up or +x to view over the right side of your mounted model)

# Answer
> 0 votes
The type of camera that keep's a certain point always in focus and can rotate around that focus point and zoom in/out is called an Arc Ball Camera. There are many arc ball camera code samples for XNA. For example, I wrote this sample some time ago: http://roy-t.nl/index.php/2010/02/21/xna-simple-arcballcamera/ .

JUst be sure to set the camera's target at the position where your model is, and you should be good to go.

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


title: GLM: Quaternion SLERP Interpolation

text:
# Question
Title: GLM: Quaternion SLERP Interpolation
I wish to **interpolate two quaternion values**. As I still can not get working results, can I kindly ask you to verify my function calls? The code below supports GLM (OpenGL Mathemathics) library, so this questions might be for those, who know it.

*Firstly*, I perform **Quaternion intialization from Euler Angles**:

```
glm::quat myAxisQuat(pvAnimation->at(nFrameNo).vecRotation);
glm::quat myAxisNextQuat(pvAnimation->at(nFrameNo + 1).vecRotation);

```

*Secondly*, I **interpolate** between the two input quaternions. The variable `fInterpolation` contains value in the range 0.0f - 1.0f.

```
myInterpolatedRotQuat = glm::mix(myAxisQuat, myAxisNextQuat, fInterpolationTime);

```

*Thirdly*, I **convert my interpolated quaternion back to Euler Angles**:

```
vecInterpolatedRot = glm::gtx::quaternion::eulerAngles( myInterpolatedRotQuat) ;

```

At the end, the values in `vecInterpolatedRot` do not represent the interpolated EulerAngles. It is difficult to understand the Quaternion values after conversion from Euler Angles, so I would like to ask you for your help, please.

**What can be wrong, please?**

I double and tripple checked input variables, I tried various approaches, and the only issue, at this moment might be with the third Aplha parameter in glm::mix()

---

## Update:

To provide you with more information, the returned values in `vecInterpolatedRot` are extremely low. At the end of the interpolation, I would expect valid Euler angles.

*This is random sequence of interpolated values, as the object moves according to predefined animation path.*

```
rotX:-1.7451 rotY:1.7993 rotZ-0.854642
rotX:-1.06451 rotY:1.18485 rotZ-0.694015
rotX:-0.254822 rotY:0.437004 rotZ-0.942035
rotX:0.578816 rotY:-0.335103 rotZ-0.716057
rotX:1.53934 rotY:-1.07602 rotZ-1.0182
rotX:2.5582 rotY:-1.87737 rotZ-0.759468
rotX:-2.58259 rotY:-2.47432 rotZ-1.06071
rotX:-1.35049 rotY:3.11548 rotZ-0.81839
rotX:0.0106472 rotY:2.78129 rotZ-1.04353
rotX:1.46636 rotY:2.33968 rotZ-0.879188
rotX:0.0289322 rotY:2.31166 rotZ-0.91746
rotX:-1.47901 rotY:2.37235 rotZ-0.938591
rotX:-2.59482 rotY:2.89469 rotZ-1.15554
rotX:2.47283 rotY:-2.76131 rotZ-0.992493
rotX:1.73065 rotY:-1.53285 rotZ-1.27898
rotX:0.85806 rotY:-0.176976 rotZ-1.03487
rotX:0.452009 rotY:-1.14604 rotZ-0.927788
rotX:0.0604701 rotY:-2.12479 rotZ-1.05684
rotX:0.107648 rotY:-2.07785 rotZ-1.05071
rotX:0.154894 rotY:-2.03083 rotZ-1.04569
rotX:0.809623 rotY:2.14456 rotZ-1.31262
rotX:1.15268 rotY:0.332553 rotZ-0.983604
rotX:2.16299 rotY:-0.545458 rotZ-1.11758
rotX:2.95376 rotY:-1.2008 rotZ-0.846527
rotX:-2.94892 rotY:-0.892473 rotZ-1.17334
rotX:-1.89716 rotY:-1.30162 rotZ-1.53247
rotX:0.804938 rotY:1.93659 rotZ-1.37281
rotX:0.653453 rotY:1.73722 rotZ-1.14364
rotX:2.24713 rotY:0.658935 rotZ-1.03684
rotX:2.97528 rotY:0.508203 rotZ-0.559124
rotX:-2.49988 rotY:0.640482 rotZ0.0117903
rotX:-1.57379 rotY:1.16303 rotZ0.288639
rotX:-1.4928 rotY:1.17794 rotZ0.902059
rotX:-0.667796 rotY:1.94995 rotZ1.49074
rotX:2.12971 rotY:-1.85782 rotZ0.904871
rotX:2.36951 rotY:-2.03682 rotZ0.189242
rotX:1.5574 rotY:-2.92156 rotZ-0.450418
rotX:1.6256 rotY:2.29519 rotZ-1.46659
rotX:2.85414 rotY:2.11303 rotZ-0.42888
rotX:-2.48503 rotY:2.96942 rotZ0.189887
rotX:-1.55656 rotY:3.00852 rotZ0.675669

```

# Answer
The posted values seem to be radians, but GLM uses degrees.

**Edit**: Also make sure you use the same rotation order. If you dont understand why that matters see the different results for different orders here at Wolfram Alpha. Play a bit with the "Euler rotation sequence" box and watch the different outputs.

Here and here are some more links that explain the rotation-order-problem
> 1 votes

# Answer
I never used GLM until now (it seems interesting through) but are you sure about your "glm::mix" call ?

In the documentation I can find two mix functions :

* glm::core::function::common::mix

```
genTypeT glm::core::function::common::mix (
       genTypeT const & x,
       genTypeT const & y,
       genTypeU const & a
)

```

If genTypeU is a floating scalar or vector: Returns x * (1.0 - a) + y * a, i.e., the linear blend of x and y using the floating-point value a. The value for a is not restricted to the range \[0, 1\].
* glm::gtc::quaternion::mix

```
detail::tquat<T> glm::gtc::quaternion::mix (
       detail::tquat< T > const & x,
       detail::tquat< T > const & y,
       typename detail::tquat< T >::value_type const & a
)

```

Returns a SLERP interpolated quaternion of x and y according a.

I think **glm::mix** is an alias to the first one (I'm still searching informations to confirm it through, as I can't find it in the documentation) and as you need the second one, you could try to call it directly.
> 1 votes

---
Tags: opengl, mathematics, interpolation, quaternion, glm
---


# Question
Title: XNA Automatic Collision detection from model?
This is going to be a rather vague question xD

In XNA is there a way of working out if a point or rectangle is colliding with a 3D .x object? It is a big model, and would take a long time to map out all the rectangles for collision detection so I was wondering if there was a easier way of doing it :)

# Answer
If you don't mind the collision being somewhat rough, you can use the bounding sphere of the individual mesh parts for basic collision.

This will result in a small to large area for false positives (depending on the design of the model and the individual mesh parts), so be warned. However this will work well, and quickly, in situations where you don't need particularly fine grained checking or if you wish to know when you should employ a higher resolution collision check.
> 2 votes

---
Tags: xna, 3d, collision-detection, models
---


# Question
Title: Where can I find good (well organized) examples of game code?
Where can I find good (well organized) examples of game code? I'm hoping that I can pick up some organizational tips. Most examples in books are too short and leave out lots of detail for the sake of brevity. I'm particularly interested on how to group your variables and methods so that another programmer would know where to look in the code. For example initializers at the top, then methods that take input, then methods that update views.

I don't care about a particular language, as long as its OOP. I looked at the Quake 2 and 3 sources, but they're straight C and not much help for getting tips on organizing your objects.

So, have you seen some good source? Any pointers to code that makes you say "wow, that's well organized" would be great.

# Answer
> 19 votes
Several commercial games have had their source code released. Some of the games are listed here. There's no guarantee that the code in these is well organized, but by looking at some source code from games that were commercially successful you might get a good idea what works in practice.

Also, while not a game, OpenSceneGraph has many of the components of a game and is well architected in C++, using different design patterns, plug-ins, etc. It's a big enough code base and has been around long enough that you can learn a lot from it.

# Answer
> 7 votes
**Battle for Wesnoth** is a:

> Free, turn-based tactical strategy game with a high fantasy theme, featuring both single-player, and online/hotseat multiplayer combat

Free as in open-sourced, under GPL. I *just* found/downloaded it, so can't say what the gameplay is like yet, but it's gotten great reviews. Nor do I know if their code is "well-organized" :) But hey, it's *open-source*.

# Answer
> 5 votes
I'm pretty meticulous about my code, so you might find my in-progress roguelike Amaranth useful to skim over.

# Answer
> 4 votes
If you're looking for good OOP - I quite liked the object model of the Doom3 SDK.
Ogre3D is a heavy OOP design but I emphasise heavy as i think it's quite bloated with lots of examples and plug ins.

Let me know what you think.

# Answer
> 2 votes
I have source code to libraries and full games on my site Another Early Morning you can also find some projects on my GitHub page. Not all of it is a shining example of quality, but then that tends to happen when you want to ship something.

# Answer
> 0 votes
Prototype, winner of one of the Shmup-Dev competitions:

http://xout.blackened-interactive.com/ProtoType/Prototype.html

And the source code:

http://xout.blackened-interactive.com/dump/new/ProtoType\_src.zip

Since I'm a code newbie I can't say much about the quality, but just skimming over it gave me some insights. Have fun.

# Answer
> 0 votes
I've got the source for a simple one we're using for a code war competition at Windward Wrocks. I think it's well organized and it is pretty simple. But certain parts were created quickly, not well. With that said, even in the largest game development teams, there are parts in those that are written quickly, not well.

---
Tags: architecture, open-source
---


# Question
Title: Ultimate beginner's tutorial to 3d game dev using XNA Framework?
I'm looking for a tutorial that starts at square 1 for game development and moves up through intermediate/expert levels of 3D game development. I really want to get into 3D game dev and I've been trying to for awhile in my free time, but I know so little at times that I'm not even sure what terminology to use in order to phrase a question properly.

Ideally, I'm hoping to find tutorials for the XNA Framework, what little experience I have is XNA.

I've been developing for years and don't really need help with the language. What I know I need help on is stuff like rendering, what exactly a Matrix represents, and other things in the framework's library. I don't even know what all is available in the library.

# Answer
The MSDN tutorial is pretty decent, actually. I assume you've got a decent understanding of gamedev in general (else you're kind of stuck).

A book which I think is pretty good is Learning XNA 4.0. It starts off with 2D stuff for the first few chapters, but quickly progresses into 3D - cameras, models, shaders, et al. It's not much of a tutorial to making a game to a decent overview of XNA, 3D in light detail, and knowing the useful things.

As for the framework itself, it isn't **that** difficult to just pick it up as you go along. Pick a simple game to try for and search out what you need (of course, the book is really good for this).
> 9 votes

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


# Question
Title: Game Publishing & Income : Quality vs Quantity
As a casual flash gamer, I see lots of "games" released that are ... terrible. And that's an overstatement. But I'm wondering, are these developers onto something? Is this a comparatively good source of income, considering how much time a quality game takes to make?

I'd like to consider it from a developer's perspective, though the concept may extend to all games and not just flash. Someone who wants to earn money - say, via sponsors (Amor Games, Crazy Monkey) or flash gaming sites (Kongregate, NewGrounds). (I don't think sponsors will sponsor a half-baked game, though).

# Answer
> 4 votes
There has always been, and always will be, a market for schlock.

REALLY terrible games will only appeal to the naive who get "suckered" ... not a good business model really.

"Low technical quality" but fun little games can be good if they're priced right, a sort of "how good does it have to be for a quarter" (or whatever).

Games that go beyond will do much better, imho. There's enough schlock on the market that we have no need to go out of our way to generate any more ;-)

In general ... in the iPhone app (etc) world especially I've found word of mouth to be one of the biggest drivers for popularity, and I've never recommended a "terrible" game. To anyone. Ever.

# Answer
> 4 votes
As a game developer who has published a casual game on BigFishGames.com I speak from experience when I say that the highest quality games bring in the greatest amount of money. In any given day, a number 1 game there will be bringing in 2x as much as the number 2 game. And a number 1 game will be making about 10x more than a game which is ranked 5-10.

So with that in mind, you would have to create 10 'average quality' games (by BFG standards) to make the same amount of money as one really high quality game. **A high quality game will receive much higher profits than many low quality games which take the same amount of time to develop.**

Big Fish Games has a minimum quality standard, such that they won't accept really poor games. This means that for your game to be accepted you have to have worked on it for quite a while to make sure it's polished and actually fun. So if you assume some sort of 'polish/making game fun' time overhead, then your time is better spent developing a high quality game, otherwise if you're polishing bad games then the amount of time taken to polish them won't be worth the return.

Having said this, it is however possible to have a series of lower quality games and make a good income. The catch is that you have to release them in appropriate places.

Every time you publish a game, it's another source of residual income (from continual sales). So as long as it's "sort of fun" then there will be people who will play it and you. If you release games independently from portals (such as on your own website), then you can set your own quality standards. And if you're able to make a game which is both fun and of reasonable quality in a **reasonable** amount of time, then you **can** make money from making a lot of lower quality games.

An example of this is Apple's Appstore. It's flooded with crappy apps as well as good ones. A lot of the time, the good apps can be overshadowed by so many bad apps that it doesn't really seem worth it. However, due to the shear volume of users of iOS products, you are basically guaranteed to get sales, even if it's just a trickle. And so, by coincidence, I am currently conducting an experiment of your very question. I actually released a game of 'acceptable' quality yesterday and got 8 sales overnight - which is **absolutely nothing**, but the game only took me **3 days** to make, as opposed to my casual game on BFG which took **6 months** and was of very high quality. However that game is there forever (until Apple closes the AppStore), and it will hopefully continue to have money trickle in. So if I made 10 of these, it would have taken me a month... and may be getting me 100 sales a day from all of them combined.

If you're selling games to flash portals (through FlashGameLicense for example) and getting a flat return, then you're not going to see this residual income unless you also have additional licenses in place. Here is a good example of residual income with a Flash Game: http://www.andymoore.ca/2010/03/steambirds-by-the-numbers/

# Answer
> 1 votes
Polish is important, just don't polish a turd.

If your making a game that has a new mechanic, or is not easily comparable to another game, it would be a mistake to polish it for too long. There is no telling if anyone will like your game.

On the opposite end of the spectrum, if you are copying an existing style, like a football simulation game, well, if you can do a good job you will make money. That is known. So you can get a clearer picture of how much you should spend on making the game better then competition.

I think Portal is a good example for what I am trying to convey. Portal had a novel mechanic. The first rev was a student project and wasn't that great, but it proved the hypothesis that the mechanic could be fun. For the first commercial release Valve felt comfortable investing in polishing it up, because the rough prototype had proved it could be fun. The case for polish was even easier in the second (commercial) release.

Before you think of a game, think of mechanic. The first rev is the test of the mechanic. When you find a successful mechanic, model how much you can make by polishing, and go from there.

---
Tags: flash, monetization, development-speed
---


# Question
Title: Is it a good idea to render many textures into one texture?
I'm making a 2D game with OpenGL. In order to avoid changing the state machine and binding at runtime, I want to make consolidate my textures into bigger textures,

for example, taking 4 128x128 textures and making 1 big 512x512. I could then just render part of the texture rather than binding a new one.

Is this a good idea? Could my newly created texture get lost, or are there major faults in doing this?

Thanks

# Answer
> 3 votes
Yes, in general, to it being a good idea. OpenGL generally has transparent loss mechanisms, that is, if a texture is lost, you won't notice it.

The idea of making multiple textures into one large texture has been explored. This is called "Texture Atlasing". There are faults with it if you try to make an atlas that is greater than the maximum texture size of the graphics card (which on modern cards is quite large, 8Kx8K or so).

There are pathological cases where texture atlasing will not improve performance, but with discrete graphics cards offering \>\> 512MB of video memory on low end cards, I don't think you'll run into any of these type problems. I wouldn't concern yourself too much with performance optimizations if you are developing for the desktop systems until it is clear that they are needed -- and what an epic title it must be then! ;)

---
Tags: opengl, c++, 2d, textures
---


title: Framerate independence

text:
# Question
Title: Framerate independence
I'm building a physics engine in OpenGL, and I'm a little bit confused on how framerate independence is achieved.

At the moment I'm using glutTimerFunc to cap the framerate at 30 FPS. Is there a way to do this without capping it but not have my objects running around like crazy when I run the application at a higher framerate?

I'm thinking that I need some sort of measure of distance relative to the rendering speed. Are there any articles/tutorials you may know that would help me out?

# Answer
You have to measure the time that elapsed between two frames, and multiply that with every movement calculation that you do.

Computer A runs the game at 22FPS. Computer B runs it at 35FPS.

Therefor, the average time between frames on computer A is about 45ms, and the average time between frames on Computer B is about 28ms.

Now let's say you move players on both of the computers in one direction every frame, depending on the time elapsed between the frames:

On Computer A:

```
//let t bet the time between frames
player.move(t)

```

The same on Computer B:

```
//let t bet the time between frames
player.move(t)

```

On Computer A, the function will (on average) get called 22 times, and t will have a value of 45.

On Computer B, the function will be called 35 times, and t will have an average value of 28.

Therefor, after one second, the player on computer A will have moved 22\*45 = 990 units. On computer B, the player will have moved 35\*28= 980 units.

The difference in here is there because I rounded the numbers of milliseconds between frames on both computers. Usually, it will be exactly the same.
> 7 votes

# Answer
This Gaffer on Games article will explain more than you ever need to know. (great article on timesteps)

At a very simple level, you want to calculate how long since the last frame and use that in your movement calculations. If you attempt to cap it at, say, 60fps, you're not going to be able to check every 16.6666ms exactly. You may end up with an update call at 16.7 ms after the last frame. You multiply your velocity vectors by 0.0167 or whatever and move the object.

If you ran it on a slow computer, maybe getting only 10 fps - so one update per 100ms, you would instead multiply the velocity by 0.1 - the objects may be jerkier, but they will move at the same speed. The last code example in the article shows how to do this (it's very simple).

Also check out:
Frame Independent Movement (duplicate?)
Time based vs frame based
Fixed step vs variable step
> 4 votes

---
Tags: opengl, frame-rate
---


title: 2d game tools , what to work on first?

text:
# Question
Title: 2d game tools , what to work on first?
My friend and I would like to program a 2D game. We were discussing about tools needed, so while I am working on the tools, he will work on game logic and stuff. Probably I will put our tools into the open source circuit once finished, so in your experience what kinds of tools are really needed, but don't already exist for free? I was thinking about what to work on first, so far my list is:

* Texture generator
* Path editor
* Path finder
* Grid visibility calculator (sort of PVS but for 2D)

# Answer
> 2 votes
A simple 2D shader editor would be pretty awesome. NVIDIA's FX Composer is very good but also very overblown for what you need for 2D games.

While Tile and Map editors are usually needed, you don't need to make them yourself. There are tons and tons of freeware and opensource editors out there (for example: http://www.mapeditor.org/ ) with easy-to-parse map formats, and most of them will be better than what you'll be able to do.

Other than that, your tools will probably be game-specific. For example, you might want to program a tool which lets you create and maniuplate new types of objects in your world easily. Or you might need a tool that enables you to create and cut cutscenes in your engine. The sky is the limit.

# Answer
> 1 votes
With the exception of the "path finder" (which is generally not a tool and usually something built in to the game logic, unless you are doing pre-baked navigation through a search space), **the items you listed sound like potentially viable tools in general**. Whether or not they will be useful for your game depends, of course, on the kind of game your making and its specific design. If you need all those kinds of tools, then by all means build them. But build them because your game needs them, and then consider if you should release them as open source projects -- you may find that they end up being far too specific to your personal game to be that useful to others.

**Tile and map editors tend to be very commonly needed**. It's quite hard to make a suitably general-purpose one, but for your game, it may be something to consider building.

If your goal is to make a game, you shouldn't be focusing your tools development around "what tools don't exist for free that I could make and release," but instead "what tools do I need for this game?" It will be a far more productive line of inquiry.

Not all 2D games require the same kind of assets or technology -- for example, not all games require path data that is complex enough to warrant a custom tool to author that path data. Many games that *do* could get away with using existing vector image editing programs to author the path and massaging the output format from the image editor. Likewise with "texture generator" -- by which I assume you mean a tool for tweaking inputs to various procedural texture generation algorithms or something.

---
Tags: xna, opengl, 2d, maps, procedural
---


title: Should I use Events in a XNA Game?

text:
# Question
Title: Should I use Events in a XNA Game?
I created a button class which draw a button on the screen. When I click on it, I want to see something happening. In WinForm, I would simply use the event OnClick of the button. What about XNA?

Should I add an OnClick event to my button class? Is that a good practice? Otherwise, how do you handle events in your game loop?

# Answer
> 7 votes
The only reason against using `event` in a game is that creating a delegate to attach to the event handler creates a heap object that can cause a garbage collection which can cause a frame-rate hiccup on on Xbox 360 (and possibly WP7, haven't tested it).

In general, this should not be relevant to a game UI that you set-up once and simply let run.

Also, calling an event handler is a *tiny, tiny, tiny* bit slower some other available methods. And this is also absolutely irrelevant for a UI. (It only comes into play for micro-optimised number-crunching).

So, as long as you're not running around assigning event handlers all willy-nilly, then the choice of using an `event` in a game is no different to the choice of using one in a regular application.

Copying the design of WinForms for your game UI is perfectly fine.

(It's worth pointing out one caveat of events is that they are "hidden" strong references that can unintentionally keep objects alive if you don't remove the handler. This is relevant to both games and regular applications)

# Answer
> 4 votes
It's perfectly acceptable to use events to handle things like clicks and other interaction with your button interface; it's certainly a superior method to the one that involves subclassing the `Button` type to implement customized behavior.

Another uncommon alternative is to attach scripts to buttons and other UI elements, but this is more involved (unless you already have a robust scripting system in place) and not neccessarily better anyhow.

You may also want to look into the concept of "immediate mode GUIs," which provide for another way of handling input.

# Answer
> 3 votes
There are three common approches I saw in game engines, I'm not sure about XNA supporting all three but here they are :

1. you can inherite a class from your button class and override OnClickFunction in your CustomButton class. The benefit is you don't have to check if the button is pressed it informed you whenever it's clicked but it may cause to overuse of inheritence.
2. you can define some function OnClick and pass it to OnClickEvent butten class (just like normal c# event handleing). this has the same benefit as the previous one and you don't need to worry for inheritence overuse.
3. you have to check in your main loop if this button is clicked or not. in this method it's not realy event. so the disadvantage is you have to check yourself whenever you have to do somthing based on button inputs but it has a advantage that you can control where the buttons really are checked and take effect.

# Answer
> 2 votes
I stopped using .net events and started to store all my events and changes in buffer:

```
public sealed class GameStateData
{
    public bool IsEmpty = true;
    public List<EventData> EventDatas = new List<EventData>();
    public List<ChangeData> ChangeDatas = new List<ChangeData>();
    ...//your additional data

    public void Reset()
    {
        IsEmpty = true;
        ManifoldDatas.Count = 0;
        ChangeDatas.Count = 0;
    }
}

public struct ChangeData
{
    public Node Sender;
    public short PropertyIndex; // predefined property index (f.e. (short)MyIndexEnum.Life)
    public object OldValue;
    public object NewValue;
    public object AdditionalData;
}

```

Pros:

1. For multithreading support the only thing you need is to swap buffers and process all events and changes in render thread.
2. Every gamestep change will be saved, so any game logic can be based on combination of events. You can even implement time reversing.
3. You don't need to create event fields increasing size of single object. Game logic in most cases require only single rare subscriber.
4. There is almost no additional memory allocation (excluding boxing cases) (WP7,XBox and other micro framework critical).
5. You can have different event sets handling a predefined GameStateData to object.

Cons:

1. More memory spending, although you need only 3 buffers (game, swap and render).
2. Writing additional code at start to implement needed functionality.

BTW sometimes I use both: event model and buffer model.

---
Tags: xna, xna-4.0, .net, events
---


title: Creating Projectiles (Beam)

text:
# Question
Title: Creating Projectiles (Beam)
I am making a simple shooter game for Android where the player is a human and is being attacked by aliens. How would I make a laser beam, so that when the user touches the screen or presses the trackball the laser just fires in a straight line?

# Answer
> 5 votes
Just yesterday someone asked almost exactly the same question over on stackoverlow.com. I'm going to quote my answer from there and edit it a little to fit your post:

https://stackoverflow.com/questions/6300169/moving-objects-help/6300303#6300303

I don't know what kind of library you're using to draw all of your things, but that basically doesn't matter since you only need to know two things in order to do this:

You'll probably want to set up a vector class in order to deal with these kinds of things more comfortably. I'm going to assume that you already have one. In case you don't know about vector math, there's this very useful tag page on here with links to two excellent articles on the topic: https://gamedev.stackexchange.com/tags/vector/info

You need to calculate the direction that the beam moves in depending on the touch's position. You get this direction by simply subtracting the position of the touch from the position of the player:

```
Vector2 direction = Vector2.subtract(touchPosition,playerPosition);

```

In order to just get a direction instead of adding a velocity component to this vector, you need to normalize it (so it has a length of 1):

```
direction.normalize()

```

The normalize code inside Vector 2 would look something like this:

```
public void normalize()
{
    float length = this.length();
    this.x /= length;
    this.y /= length;
}

```

And the length code like this:

```
public void length()
{
    return math.sqrt(this.x*this.x + this.y*this.y);
}

```

You then need to update the beam position by adding the product of the direction and the speed that you want the beam to travel with.

```
projectilePosition.add(Vector2.multiply(direction,speed));

```

If you have some way of measuring the time between two frames, the speed variable should depend on the elapsed time between those frames, in order to create smooth movements on different platforms. Then, the code would simply add another multiplication:

```
projectilePosition.add(Vector2.multiply(direction,speed*t)); //t = elapsed time

```

---
Tags: java, android
---


# Question
Title: Recreating retro/NES style physics with intentional imprecision
**Background:**

I'm having a problem getting the jump curve correct for a retro platformer remake project of mine. The original game is for the NES, and the player's velocity is stored in two separate parts: one byte for the whole number and another for the fractional part.

Gravity is added to the player's Y speed at a rate of 0.25/frame.

When the player jumps, his Y speed is set to -4.64453125. The rest of the jump curve is left to gravity.

As the player ascends his vertical velocity converges to 0 at a rate of 0.25/frame. When the player's velocity reaches a value less than zero, however, the velocity changes following a different pattern. Instead of decreasing steadily by 0.25 every frame, it follows this pattern:

```
[1.75, -0.25, -0.25, -0.25, 1.75, -0.25, -0.25, -0.25, 1.75, ...]

```

It appears to have something to do with integer overflow.

**Data:**

Here is a dump of the data from the original. It's a table of the velocity.

```
Jump Curve

Y-Hi Y-Lo    Decimal        Change/Frame
4    165     4.64453125     ?
4    101     4.39453125     -0.25
4    37      4.14453125     -0.25
3    229     3.89453125     -0.25
3    165     3.64453125     -0.25
3    101     3.39453125     -0.25
3    37      3.14453125     -0.25
2    229     2.89453125     -0.25
2    165     2.64453125     -0.25
2    101     2.39453125     -0.25
2    37      2.14453125     -0.25
1    229     1.89453125     -0.25
1    165     1.64453125     -0.25
1    101     1.39453125     -0.25
1    37      1.14453125     -0.25
0    229     0.89453125     -0.25
0    165     0.64453125     -0.25
0    101     0.39453125     -0.25
0    37      0.14453125     -0.25
-1   229     -1.89453125    1.75
-1   165     -1.64453125    -0.25
-1   101     -1.39453125    -0.25
-1   37      -1.14453125    -0.25
-2   229     -2.89453125    1.75
-2   165     -2.64453125    -0.25
-2   101     -2.39453125    -0.25
-2   37      -2.14453125    -0.25
-3   229     -3.89453125    1.75
-3   165     -3.64453125    -0.25
-3   101     -3.39453125    -0.25
-3   37      -3.14453125    -0.25
-4   229     -4.89453125    1.75
-4   165     -4.64453125    -0.25
-4   101     -4.39453125    -0.25
-4   37      -4.14453125    -0.25
-5   229     -5.89453125    1.75
-5   165     -5.64453125    -0.25
-5   101     -5.39453125    -0.25
-5   37      -5.14453125    -0.25
-6   229     -6.89453125    1.75

```

**Problem:**

In my game I haven't been able to achieve this effect. When the velocity is less than zero it continues to decrease regularly by 0.25 rather than the pattern described above. Rather than storing the whole and fractional parts separately, I am storing them together in a single float.

How can this effect be achieved?

# Answer
> 16 votes
```
one byte for the whole number and another for the fractional part

```

Basically you just have to subtract 64 from `low` in order to subtract 0.25, because an 8 bit value can have 256 values, so 256 * 0.25 = 64 When there is an underflow in `low` also subtract 1 from `high`.

**Disclaimer:** This code is intentionally wrong when it comes to negative numbers, it is supposed to model the numerical anomalies described in the question. For comparison reasons the implementation of a proper negative numbers handling fixed point class can be found at the bottom of this answer.

```
struct velocity
{
    char high;
    unsigned char low;

    // fall -0.25
    void fall()
    {
        if(low < 64) --high;
        low -= 64;;
    }

    // convert to a float
    float toFloat() const
    {
        float ret = high;
        float frac = (float)low / 256.0f;
        if(high >= 0) ret += frac;
        else ret -= frac;
        return ret;
    }

    // convert from float
    void fromFloat(float f)
    {
        high = (char)f;
        float frac = f - high;
        low = (unsigned char)(frac * 256.0f);
    }
};

velocity v;
v.high = 4;
v.low = 165;
for(int i = 0; i < 30; ++i)
{
    printf("%2d     %3d   %f\n", v.high, v.low, v.toFloat());
    v.fall();
}

```

**EDIT**: I also added the conversion to float and from float and the output

The generated output is the same as in your table:

```
 4     165   4.644531
 4     101   4.394531
 4      37   4.144531
 3     229   3.894531
 3     165   3.644531
 3     101   3.394531
 3      37   3.144531
 2     229   2.894531
 2     165   2.644531
 2     101   2.394531
 2      37   2.144531
 1     229   1.894531
 1     165   1.644531
 1     101   1.394531
 1      37   1.144531
 0     229   0.894531
 0     165   0.644531
 0     101   0.394531
 0      37   0.144531
-1     229   -1.894531
-1     165   -1.644531
-1     101   -1.394531
-1      37   -1.144531
-2     229   -2.894531
-2     165   -2.644531
-2     101   -2.394531
-2      37   -2.144531
-3     229   -3.894531
-3     165   -3.644531
-3     101   -3.394531
-3      37   -3.144531
-4     229   -4.894531
-4     165   -4.644531
-4     101   -4.394531
-4      37   -4.144531
-5     229   -5.894531
-5     165   -5.644531
-5     101   -5.394531
-5      37   -5.144531
-6     229   -6.894531

```

In contrast this fixed point class handles the negative numbers properly:

```
#include <iomanip>
#include <iostream>

struct fixed_point
{
    union
    {
        struct
        {
            unsigned char low;
            signed char high;
        };
        short s;
    };

    float toFloat() const
    {
        fixed_point tmp;
        if(high < 0) tmp.s = ~s;
        else tmp.s = s;

        float ret = tmp.high;
        float frac = (float)tmp.low / 256.0f;
        ret += frac;
        if(high < 0) ret = 0 - ret;
        return ret;
    }

    void fromFloat(float f)
    {
        float tmp;
        if(f < 0.0f) tmp = -f;
        else tmp = f;

        high = (char)tmp;
        float frac = tmp - high;
        low = (unsigned char)(frac * 256.0f);

        if(f < 0.0f) s = ~s;
    }

    fixed_point operator+(const fixed_point &fp) const
    {
        fixed_point ret;
        ret.s = s + fp.s;
        return ret;
    }

    fixed_point operator-(const fixed_point &fp) const
    {
        fixed_point ret;
        ret.s = s - fp.s;
        return ret;
    }

    void print(const char *msg) const
    {
        std::cout << msg << ":" << std::endl;
        std::cout << std::hex << std::uppercase;
        // cout'ing the hex value for a char is kind of a pain ..
        unsigned int _high = 0;
        memcpy(&_high, &high, 1);
        std::cout << "  high : 0x" << std::setfill('0') << std::setw(2) << _high << std::endl;
        unsigned int _low = 0;
        memcpy(&_low, &low, 1);
        std::cout << "  low  : 0x" << std::setfill('0') << std::setw(2) << _low << std::endl;
        std::cout << "  all  : 0x" << std::setfill('0') << std::setw(4) << s << std::endl;
        std::cout << "  float: " << toFloat() << std::endl;
        std::cout << std::endl;
    }
};

```

---
Tags: mathematics, physics, platformer, fixed-point
---


# Question
Title: Should an object in a 2D game render itself?
I'm making a 2D street fighter-like game that is not tile based. Usually people recommend that entities be given to a renderer that render them, not them render themselves, but it seems the inverse is better,

Why is one better over the other?

Thanks

# Answer
An couple of considerations :

* as you mentionned, each sprite would have to "hint" about which bitmap to use, but if the entity has to render itself. What would that 'hint' be ? If it is a reference to a different bitmap, sprite sheet, etc... for each sprite, then you might end up using more memory than necessary, or having troubles managing that memory. An advantage of a separate renderer is that you have only one class responsible for any asset management. That said, in a SF2-like fighting game, you might only have two sprites ;)
* as mentionned elsewhere, whenever you want to change your graphical API, you have to change the code for all your sprites.
* rendering is rarely done whithout a reference to some graphical context. So either there is a global variable that represent this concept, or each sprite has an interface with render(GraphicalContext ctx). This mixes the graphical API and the logic of your game (which some people will find unelegant), and might cause compilation issues.
* I personnaly find that separating the rendering from the individual entities is an interesting first step in the direction of viewing your game as a system that does not necessarily need graphics at all. What I mean is that when you put rendering out of the way, you realize lots of the gameplay happens in a "non-graphic world" where the coordinates of the entities, their internal states, etc... is what matters. This opens the door to automated testing, more decoupled system, etc...

All in all, I tend to prefer systems where rendering is done by a seperate class. That does not mean your sprites can not have some attributes that are "graphically related" (animation name, animation frame, height x width, sprite id etc... ), if that makes the renderer easier to write or more efficient.

And I don't know if that would apply to 3D (where the notion of meshes, and the coordinates variable you would use would maybe be tied to your 3D API ; whereas x,y,h,w is pretty much independant of any 2D API).

Hoping this helps.
> 13 votes

# Answer
You want the rendering system to be in control of what gets drawn when. If instead the sprites are in control of the rendering you loose on lots of efficiency gains and flexibility. I'm of the opinion that having the render system in control results in cleaner code.

Some advantages of centralized rendering:

* z-ordering:
If the game objects themselves are responsible for rendering you'll have to make sure you call them in the correct order. Otherwise background objects may be drawn over foreground objects.
With the render system in control, it can choose to sort all render objects, detect overloaps at render-time and just render those, or just forego ordering all together. The point is that decision can be made easily now.
* batching:
The other obvious advantage of allowing the render system to be in control is batching. Here again the render system has to option to batch sprite renders the share a texture. It can use triangle slicing to render *everything* with one call. It may be able to cache some render calculations. Or it could just render each sprite in turn with none of that fancy stuff. (Note: it is possible batch when each object renders itself, but the problem is less efficient and more complex).

The way I implement this in my games it to have game objects register the sprites they want drawn with the render system. When the object no longer wants the object drawn it unregisters the sprite, or marks it inactive.

All that said. If it's easier to have your game objects render themselves by all means do it that way. It's much more important to make progress and get something / anything drawn than it is to have a perfect architecture.
> 11 votes

# Answer
Disclaimer: your question doesn't give much detail so I'm responding with a general principle. Please excuse me if I misunderstood your use or 'render'.

I generally use an external object to render various actors in a scene as a way of encapsulating scene level properties and methods outside of the individual 'actor objects.' Objects in the scene should only contain internal methods and properties; they should only know about what they themselves are and what they do. Presumably, they will be influenced by other objects in the game as well as user input. This will effect how/whether they are rendered on the screen. A 'director object' can, for example, translate the 'w' keypress to jump, then tell the actor object .jump(). Such director level logic can also tell actors to enter or exit the scene entirely.

Cheers, David
> 3 votes

# Answer
What if someday you want to port your game to a different resolution (ie iPhone and friends). Thus, a global property about rendering changes, how do you easily update your code?
> 3 votes

# Answer
What I used was an observer-based design. When I created an instance of a class I wanted to render, then a pointer to it was stored in the central Renderer class. When you call `RenderFrame()`, then the renderer already has all the existing objects it needs to render and accessed their properties to do it. The classes themselves had no idea that they were going to be rendered at all. This API was nice and clean and easy to use.
> 3 votes

# Answer
In general it's always about how easy it is to maintain and expand your code. Tomorrow you figure out that you don't like the graphics API you're using currently, and want to switch. Will you now have to go through all of your objects classes and change everything, or do you still just need to change your code in one central point of the project?

It depends on what your objects are really doing when you call render(). As long as they just wrap method calls around your graphics engine, it's completely fine, since logics \<-\> graphics distinction will still be given.

For example, if your render() methods are basically convenience-methods and look something like this:

```
void MyClass::render(const Graphics &g)
{
    g.draw(this);
}

```

or

```
void MyClass::render()
{
   mySprite->render();
}

```

or

```
void MyClass::render()
{
    mySprite->UseShader(thatshader);
    mySprite->render();
}

```

or close to that, I don't think it's a problem whatsoever.
> 2 votes

---
Tags: c++, rendering
---


title: terrain grid rendering problem

text:
# Question
Title: terrain grid rendering problem
I'm using DirectX 9 and attempting to write a simple terrain generation object.

I'm running into trouble with the rendering - I'm hoping that this is a common problem, and someone could spot the problem by the output:

I've generated vertices, indices and I'm attempting to render a triangle strip (as it's supposed to be the most efficent way to do a grid.

It looks like I've made some kind of error in vertex or index generation, although I can't see what. I've posted my terrain class here. Can someone have a look and suggest what I've done wrong?

# Answer
> 1 votes
Don't bother with the triangle strip - it's going to be much harder to reason about than a triangle list and the graphics driver can perform the conversion automatically anyway. It looks to me like your indices are off, at least- every triangle is drawn connected to vertex 0.

What you should mainly consider is that you don't actually have X many triangles- you have the same triangle repeated X times. Generate one triangle or two triangles, then transform it using the D3DX mathematical library into the positions that you want. Here's some example code.

```
void GenTriGrid(int numVertRows, int numVertCols,
    float dx, float dz,
    const D3DXVECTOR3& center,
    std::vector<D3DXVECTOR3>& verts,
    std::vector<DWORD>& indices)
{
    int numVertices = numVertRows*numVertCols;
    int numCellRows = numVertRows-1;
    int numCellCols = numVertCols-1;

    int numTris = numCellRows*numCellCols*2;

    float width = (float)numCellCols * dx;
    float depth = (float)numCellRows * dz;

    //===========================================
    // Build vertices.

    // We first build the grid geometry centered about the origin
    // and on the xz-plane, row by row and in a top-down fashion.
    // We then translate the grid vertices so that they are
    // centered about the specified parameter 'center'.

    verts.resize( numVertices );

    // Offsets to translate grid from quadrant 4 to center of
    // coordinate system.
    float xOffset = -width * 0.5f;
    float zOffset =  depth * 0.5f;

    int k = 0;
    for(float i = 0; i < numVertRows; ++i) {

        for(float j = 0; j < numVertCols; ++j)
        {
            // Negate the depth coordinate to put in
            // quadrant four.  Then offset to center about
            // coordinate system.
            verts[k].x =  j * dx + xOffset;
            verts[k].z = -i * dz + zOffset;
            verts[k].y =  0.0f;
            // Translate so that the center of the grid is at the
            // specified 'center' parameter.
            D3DXMATRIX T;
            D3DXMatrixTranslation(&T,
                center.x,
                center.y,
                center.z);
            D3DXVec3TransformCoord(&verts[k], &verts[k], &T);
            ++k; // Next vertex
        }
    }
    indices.resize(numTris * 3);

    // Generate indices for each quad.
    int k = 0;
    for(DWORD i = 0; i < (DWORD)numCellRows; ++i)
    {
        for(DWORD j = 0; j < (DWORD)numCellCols; ++j)
        {
            indices[k]     =   i   * numVertCols + j;
            indices[k + 1] =   i   * numVertCols + j + 1;
            indices[k + 2] = (i+l) * numVertCols + j;

            indices[k + 3] = (i+l) * numVertCols + j;
            indices[k + 4] =   i   * numVertCols + j + 1;
            indices[k + 5] = (i+l) * numVertCols + j + 1;

            // next quad
            k += 6;
        }
    }
}

```

On an only somewhat tangental note, I haven't understood your code- it's totally illegible. It's a fairly incredible feat that *you* can read it.

No way can I decode 400 lines of redundant error checking (never heard of resource-managing classes?), HRESULTs, references to non-posted classes, variables declared about six million billion miles away from where they're used, global variables and *fixed function pipeline*, horrific Hungarian notation, some really crazy indentation, etc.

I'd suggest that you learn some more about coding. Here's an unfortunate lesson- the Windows API, DirectX, etc are all C APIs, designed 20 years ago (or more!) for inter-process communication and do not reflect at all good practice for in-application use.As such, it's actually really a bad idea to learn from their example. You should not return error codes- you should throw exceptions, and if you must return an error code, grab an enumeration for it- do not use a weak error code like HRESULT. Hungarian Notation is quite worthless in modern C++- the compiler will tell you the type and scope of any variable, at any time. CString is so bad, it's implementation is mandated to be illegal for the C++ Standard string class- which should always be preferred. You should not use new/delete directly, but rather favour the use of `std::vector` for dynamically allocated arrays- it's vastly safer and no less performant. These `Initialize` functions? That's what a constructor is for, buddy.

Also, fixed-function pipeline (that is, FVF and stuff) is deader than a dodo- even phones have shaders these days.

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


title: OpenGL ES Framebuffer creation problem

text:
# Question
Title: OpenGL ES Framebuffer creation problem
I'm having some problems porting my D3D code to OpenGL ES. I have a Graphics Device class that encapsulates all rendering commands. The code below is in an ObjC++ file.

The problem code is the called to get the render buffer width and height. It doesn't actually return any value in the w or h GLints.

It should be noted that the code below is from an older iPhone project, and it works there. Am I missing something really stupid?

Checking the framebuffer status returns a value of complete, since OpenGL ES seems quite happy to initialize a depth buffer with the garbage w and h values I pass to it!

```
bool GraphicsDevice::Initialize(id<EAGLDrawable> eaglLayer)
{
   EAGLContext *context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
   if(context == nil)
   {
      return false;
   }

   [EAGLContext setCurrentContext:context];

   this->eaglContext = context;

   glGenFramebuffers(1, &frameBuffer);
   glBindBuffer(GL_FRAMEBUFFER, frameBuffer);
   glGenRenderbuffers(1, &renderBuffer);
   glBindBuffer(GL_RENDERBUFFER, renderBuffer);
   [eaglContext renderbufferStorage:GL_RENDERBUFFER fromDrawable:eaglLayer];

   GLint w, h;
   glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &w);
   glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &h);

   SetWidth(static_cast<unsigned int>(w));
   SetHeight(static_cast<unsigned int>(h));

  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER,    renderBuffer);

   glGenRenderbuffers(1, &depthBuffer);
   glBindBuffer(GL_RENDERBUFFER, depthBuffer);
   glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, w, h);

   glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer);

   GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
   if(status != GL_FRAMEBUFFER_COMPLETE)
   {
      System::Log("Framebuffer not complete");
      return false;
   }

   return true;
}

```

# Answer
> 0 votes
I was trying to create a framebuffer from an EAGLLayer that already had a framebuffer created from it. I don't know why OpenGL ES was saying the framebuffer was complete and not setting an error right away, but there you have it.

# Answer
> 0 votes
In the book "iPhone 3D Programming" there are examples of this. The author uses the OES extensions. Like

```
glGenRenderbuffersOES(1, &m_renderbuffer);
glBindRenderbufferOES(GL_RENDERBUFFER_OES, m_renderbuffer);

```

or

```
glGenFramebuffersOES(1, &m_framebuffer);
glBindFramebufferOES(GL_FRAMEBUFFER_OES, m_framebuffer);
glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
                             GL_COLOR_ATTACHMENT0_OES,
                             GL_RENDERBUFFER_OES,
                             m_renderbuffer);

```

I've tested these commands:

```
GLint w, h;
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &w);
glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &h);

```

and the width and height are correct.

You can download the book examples here

See the "HelloArrow" project. Within the class RenderingEngine1

---
Tags: c++, opengl-es, objective-c
---


# Question
Title: Tetris style game in java (for now) will I need to use threads?
I'm looking at developing a puzzle game, it might be like tetris or something similar, perhaps more like bejewelled in that the player will select objects with the mouse to manipulate them.

I've been studying java part-time in college for the past year, really beginner stuff, but I've decided to build a game over the summer to keep the brain active :-D

So far I've animated some primitive shapes moving around the screen using the timer from the utilities package. This is all good, they're behaving the way I want. So now I've decided to try manipulate the shapes with the mouse. Just some really simple stuff, maybe change the colour of an object when I click on it.

To test the mouse functions I've successfully completed the MouseEvent and MouseListener tutorials on The New Boston. However, I can't get these events working in my code. I suspect I'm going to have to re-write my classes.

Will I need separate threads within the game, for example, one thread to animate the objects and another to listen for and handle mouse events.

My understanding is that I should implement runnable on my classes when using threads in Java games. Am I thinking on the right lines?

# Answer
> 2 votes
For simple games you won't need separate threads. Threads are usually used in games to calculate things that take longer than 1 frame.

For example: in your puzzle game it takes 5ms to update your logic, and 10ms to draw everything to screen. This gives you a frame time of 15ms, which gives you about 60 frames per second. This is perfect :).

Now for some reason you sometimes need to do an expensive path-finding algorithm that takes between 10 and 50ms to complete. To not have your frame rate drop to 20 frames per second you calculate the path finding in a separate thread so that your game just runs at 60 frames per second, but the path finding data is only available a few frames after it was requested. (You just have your avatar stand still until the data is available for example, 20ms wont be noticed).

In some applications input handling is done in separate threads, but again this is only relevant if there are other tasks that could cause your game not reading input fast enough. As long as your total frame time is lower than 16 ms or something like that then you won't need threads.

---
Tags: java, multithreading
---


title: Learning XNA 3.1 Vs XNA 4.0

text:
# Question
Title: Learning XNA 3.1 Vs XNA 4.0
I am starting out learning XNA and its going smoothly. However I wonder if I am shooting myself in the foot by learning 3.1 not 4.0?

I am also aware Microsoft obviously has a conflict on interest in the matter: the more times we update the more copies of Visual Studio they sell (I know express is free but some will go pro). So one has to read between the lines of the "MASSIVE NEW FEATURES UPGRADE NOW" type blogs from MS employees.

I am aware of whats new: http://msdn.microsoft.com/en-us/library/bb417503.aspx, and that mostly seems to be phone, interfaces and video features - which I am not so interested in - I am more doing the core 3D stuff.

The sticking point is: I have Visual Studio 2008 professional already and do not want to get VS 2010 if there is little difference in the game programming in 4.0.

Has the world moved on? Is what I am learning in 3.1 going to be come redundant?

There are also code differences in libraries, but they are not major, many of them can be seen here: http://www.nelxon.com/blog/xna-3-1-to-xna-4-0-cheatsheet/, for instance this one which I had to figure out compared to Riemers Tut:

XNA 4.0

```
 protected override void Draw(GameTime gameTime)
 {
     device.Clear(Color.DarkSlateBlue);

     RasterizerState rs = new RasterizerState();
     rs.CullMode = CullMode.None;
     device.RasterizerState = rs;

     effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];
     effect.Parameters["xView"].SetValue(viewMatrix);
     effect.Parameters["xProjection"].SetValue(projectionMatrix);
     effect.Parameters["xWorld"].SetValue(Matrix.Identity);
     foreach (EffectPass pass in effect.CurrentTechnique.Passes)
     {
         pass.Apply();

         device.DrawUserPrimitives(PrimitiveType.TriangleList, vertices, 0, 1, VertexPositionColor.VertexDeclaration);
     }

     base.Draw(gameTime);
 }

```

XNA 3.1

```
protected override void Draw(GameTime gameTime)
{
    device.Clear(Color.DarkSlateBlue);

    device.VertexDeclaration = new VertexDeclaration(device, VertexPositionColor.VertexElements);
    device.RenderState.CullMode = CullMode.None; // TODO only for testing!
    device.RenderState.FillMode = FillMode.Solid;

    effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];
    effect.Parameters["xView"].SetValue(viewMatrix);
    effect.Parameters["xProjection"].SetValue(projectionMatrix);
    effect.Parameters["xWorld"].SetValue(Matrix.Identity);

    effect.Begin();
    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
        pass.Begin();
        device.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.TriangleList, vertices, 0, 5, indices, 0, indices.Length / 3);
        pass.End();
    }
    effect.End();

    base.Draw(gameTime);
}

```

# Answer
I recommend to use XNA 4.0.

Sure you can probably do everything with 3.1 what you can do with 4.0, but it has advanced quite a bit. Additionally to your references you might also want to take a look at Shawn Hargreaves' blog, for example at this post: Breaking Changes in XNA Game Studio 4.0.

Or basically you can just check out the months March, April and May 2010 in his blog, they are full of XNA 4.0 changes.

Also keep in mind that with 3.1 you will be stuck with old technology. Eventually you will want to upgrade to XNA 5/6 for DX11 support or whatever. Depending on how large/complex your program is by then, it may take some time to upgrade it to 4.0 as you have to make several changes.
> 8 votes

# Answer
To the programmer 3.1 and 4 are nearly the same. The major changes are creating a device and spritebatch. And where the Content Manager is, its moved into its own project inside the solution. Everything else is pretty much the same. These changes are only a few lines of code different. Behind the scenes though its using different directx api calls.

So to answer you question you are not shooting yourself in the foot at all. Using XNA has not changed that much from the programmers point of view from even the 1.0 versions.

There are lots of cheat sheets on the net to look at for quick answers on converting 3.1 - 4.0 like this one http://www.nelxon.com/blog/xna-3-1-to-xna-4-0-cheatsheet/ .
> 2 votes

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


# Question
Title: Writing a minimalistic server for vanilla WoW
This is about a personal project I've been longing to do for some time now. Since a while now I have stopped playing WoW, but as I'm quite experienced in C++ I thought I'd try the following:

* Write a minimalistic server for vanilla WoW for experimental, personal purposes

All it would feature is being able to login with a fixed character, and being able to travel around in the standard maps (non-instance; Kalimdor, eastern kingdoms, etc.) I also don't want to use / modify existing projects such as Mangos in this case, as this would be all about the development process and trying it on my own

My questions to you:

* Is the above a realistic objective?
* How much work would such a project require? (Boilerplate code excluded, just the basic stuff to make the client "happy")
* Do you have any other recommendations for me regarding this?

# Answer
As a former developer for MaNGOS and project founder for ScriptDev2 I would say your objective is not realistic.

The basics to make the game happy are actually pretty complex. If you tried to do this without pulling code from an existing project you will be asking questions about specific op codes for months. World of Warcraft seems like a simple game but there are a lot of minute details. Look at MaNGOS' authentication for a small example.

And then you need to think about why you want to rewrite an existing emulator? I'd assume you want specific functionality but without all of the extras. In that case you might be better off just tearing down an existing system.

If you want to write a new emulator that can handle 5,000 players at once I'd urge you to rethink why you are doing this. I would also highly suggest looking for another source of self-fulfillment. You'll probably be happier in the long term working on something that you can call your own and/or possibly sell.
> 10 votes

# Answer
Fundamentally, the problem was never about the game- it's about the scale. If your server only has to support one client, or a few clients, then it's just Minecraft server but in higher resolution better graphics on the client side, effectively. All you'd have to do is transfer the player's location and the location of anything interesting (read: dynamic) around him. The client can then render as is normal. The problem is doing this in a reasonable time when you have fifty thousand players, and possibly hundreds of thousands of interesting things.
> 7 votes

# Answer
Take a look at the mangos project to get started in WoW developement

http://getmangos.com/
> 0 votes

---
Tags: c++, networking, mmo, server, world-of-warcraft-modding
---


title: Advice on rendering a 2D scene

text:
# Question
Title: Advice on rendering a 2D scene
My game will be made up of objects. Essentially the level editor will give me a bunch of objects to choose from and I can drag them in and thus a level is made. The objects could have animation in which case they are responsible for knowing which frame and layer they are on.

So then I can have these:

```
Animated non-movable objects
Unanimated non-movable objects
Animated movable objects
Unanimated movable objects

```

So first I was thinking of, when the level starts, build a quadtree for all non-movable objects.

This way I can easily avoid rendering ones which are not in view.

Then from there I can do bounding box check on dynamic objects (or maybe if I add something like Box2D it can do it).

But then comes the rendering.

At first I was thinking of each object rendering itself, but then I cannot do atlasing.

I'd like to do atlasing. I was thinking that animated objects can just use their own frame sheet. But objects which are not animated should use atlasing.

I know this can be categorized as premature optimization, but I don't want to eventually find out that it is horribly slow.

Any design suggestions / comments would be welcome. Does it seem like a good idea to try to atlas in the sort of game I'm making, which is a platformer that is not tile based.

# Answer
Make a rough guess on how many objects you will need in your game. Put 10 times that amount in the engine.

If it doesn't run slow you are fine. If it runs slow, you might need to optomize, or you might still be fine.

I would be more concerned with the logic having to iterate through a lot of objects than the a 2d render being slow.

The only kind of culling that will be worth rendering is culling anything that is outside of the screen.
> 3 votes

# Answer
For a modern 2d game I would really look at Aquaria. http://www.bit-blot.com/aquaria/

They have some pretty modern principles they apply to a fairly normal 2d engine. Their basic idea is just massive stacking of objects on different layers. Take a look at this video by the guys from Wolfire analyzing technical details.

http://www.youtube.com/watch?v=1BpRsjF7QTM&feature=channel\_video\_title

I'd assume that when in non-editing mode static objects are combined into larger objects which are stored in a single surface but that is just a guess by me.
> 1 votes

---
Tags: opengl, c++, 2d
---


# Question
Title: Sorting cube depth correctly with an isometric engine
> **Possible Duplicate:**
> How should I sort images in an isometric game so that they appear in the correct order?

I'm starting work on a simple isometric engine. Everything thing is going great at the moment, but I think I've hit an issue everyone hits. I'm having difficulty getting sorting the depth of a cube.

This image shows the default view (character not near a cube)

This image shows the character behind a cube

The issue is here, when the character goes in front of the cube.

Is there a common solution to this? How would i go about it? Would i need to give a depth to EVERY cube, then somehow work out the current tile the character is on then apply the depth to him? I'm using game maker on a mac and I'm happy to upload the project somewhere if you need to check it out.

Thanks for any input.

# Answer
> 2 votes
I made an isometric game in flash once. Never finished it (unreliable artist) but for me, sorting was simply a matter of organizing according to y coordinate. The further down on your screen the block is, the closer to the top layer it should be.

Your character, for example, in the stuffed up picture. The Y coordinate of his foot is greater than the y coordinate of the block that overlaps him. Therefore, he should be in front of it, not behind.

Then if you start having multiple layers in your world, each individual layer of the world is sorted individually. Then drawn bottom upwards.

Just comment if you need more/better explaining

---
Tags: game-mechanics, isometric
---


# Question
Title: How should one handle positions in a tile-based world?
I have a simple Tower Defense game using a tiled world. Creep and towers are on a tile at all times.

How should I represent the position of creeps in code? (Do creeps know their current tile and position on said tile or are they aware of their absolute world position?)

I'm basically looking for best practices, design pattern-type tips or general insight about how one manages positioning in a tile-based world.

Thank you.

# Answer
In my experience, the best way to handle positions in a tile-based world is to ignore that you're in a tile-based world. That is, keep your entities stored in world-positions, keep the path(s) which your entities will be travelling on stored in world-space, and if at all possible, don't let your entities or other game logic know about tiles at all.

The problem with considering tiles is that they introduce corner cases into your game code; lots of new places where your code can misbehave in subtle ways. Not only do (for example) towers need to be able to tell how close they are to entities on their own tile, but also to the entities on other tiles. And as soon as you're thinking about tiles, you start thinking about finding the neighbours of tiles, which is also easy to introduce bugs into (particularly along the edges and corners of the playfield).

Tile-based worlds are really convenient for level editing. But my advice is to only use the tile structure for editing; don't let the way the level is built spread into the game logic itself.
> 6 votes

# Answer
I would use world-positions for your entities. That will work just fine as long as the world doesn't become really huge (where world positions become impractical due to precision, so that you'll have to divide the world into chunks).

You can easily calculate the current tile from your *x* and *y* coordinates. Also having world coordinates makes comparing entities much easier (eg. *is entity X in the range of tower Y?*).

Using the other approach works too, but you'll have to deal with 2 sets of coordinates all the time (tile index(es) and position within said tile).

So in conclusion: Both approaches work, but using world coordinates seems much more practical (less coordinates to deal with, fewer calculations necessary). For your convenience, your entities could even have a getter method for their *x* and *y* tile index which will calculate the current tile position on the fly.
> 3 votes

---
Tags: tiles, tower-defense
---


# Question
Title: What is wrong with my vertex declaration?
What is wrong with my vertex declaration below? I am using it with instancing. After adding TextureInformation to it, it renders weird and has an epileptical seizure.

```
    public struct VertexInstance : IVertexType
    {
        public Matrix World;
        public Color Color;
        public Vector3 TextureInformation;

        // I use arithmetic here to show clearly where these numbers come from
        // You can just type 28 if you want
        public static readonly int SizeInBytes = sizeof(float) * 23;

        // Vertex Element array for our struct above
        public static readonly VertexElement[] VertexElements = {
            new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0),
            new VertexElement(sizeof(float) * 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1),
            new VertexElement(sizeof(float) * 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
            new VertexElement(sizeof(float) * 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
            new VertexElement(sizeof(float) * 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4),
            new VertexElement(sizeof(float) * 20, VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5)
        };

        public static VertexDeclaration Declaration
        {
            get { return new VertexDeclaration(VertexElements); }
        }

        VertexDeclaration IVertexType.VertexDeclaration
        {
            get { return new VertexDeclaration(VertexElements); }
        }
    }

```

# Answer
The offset of the last VertexElement is wrong:

```
public static readonly VertexElement[] VertexElements = {
    new VertexElement(0, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 0),
    new VertexElement(sizeof(float) * 4, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 1),
    new VertexElement(sizeof(float) * 8, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 2),
    new VertexElement(sizeof(float) * 12, VertexElementFormat.Vector4, VertexElementUsage.TextureCoordinate, 3),
    new VertexElement(sizeof(float) * 16, VertexElementFormat.Color, VertexElementUsage.TextureCoordinate, 4),
    new VertexElement(sizeof(float) * 16 + sizeof(uint), VertexElementFormat.Vector3, VertexElementUsage.TextureCoordinate, 5)
};

```
> 7 votes

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


title: Alpha in model XNA

text:
# Question
Title: Alpha in model XNA
OK been googling nonstop for ages...

My problem is, i need transparent models in my game. After a lot of annoying fiddling around with my code, i changed the blendstate to alphablend. This allowed me to start having transparency in my models.

However now i face another problem. Any other part of the same model that is meant to be view THROUGH the transparent part of the model, is not shown.

Basically it is only showing the outermost part of the model, even though an inner part is meant to be seen through the transparent part.

Any help? Thanks

# Answer
> 3 votes
In order to get proper blending you will probably have to break the object up into multiple models. And even then you are still limited since from certain angles you will be able to break the transparant blend again. Transparancy is actually quite difficult to get correct without using some cool but fairly exotic solutions. One that comes to mind is Order Independant Transparancy, unfortunately it requires DX Capabilities that XNA doesnt have yet. My recomendation is to go back into your 3d editor and break your mesh apart so you can sort the transparant and non transparant parts into a correct order.

# Answer
> 0 votes
Folow this workflow:

* Sort your model parts by depth, from the furthest one to the nearest one.
* Enable depth-writing and draw the opaque ones in order.
* Disable depth writing and draw the transparent ones in order.

---
Tags: xna, xna-4.0, transparency
---


title: Good Tutorial For Lua and LÖVE

text:
# Question
Title: Good Tutorial For Lua and LÖVE
I want to make a very simple 2D game, and have been reading a lot of good things about LÖVE, so I want to try it out. However I can't seem to find any good tutorials. The ones on the LÖVE page are rather unstructured, and the other one I found by Mathew Casperson is not very useful. Does anyone know of a better tutorial?

# Answer
> 7 votes
Disclaimer: I've created the two tutorials I'm going to link here

I've done two tutorials. None of them is complete, but will get you from 0 to 80% quickly.

The first one is a LÖVE-centric one called love-tile-tutorial:

https://github.com/kikito/love-tile-tutorial

It's about 50% done. Starts with the basics, and deals with Images & Quads, as well as an introduction to Lua.

love-tile-tutorial is on hold at the moment, though - I'm doing other projects, such as the second tutorial.

The second tutorial concentrates in Lua itself - this is, not for LÖVE specifics, but for Lua in general; it actually works entirely from the console. It's a series of exercises for learning the language itself better. It's called Lua Missions:

https://github.com/kikito/lua\_missions

I realize this is not exactly what you wanted (since not all LÖVE is covered), but I'm putting it here in case anyone finds it useful.

# Answer
> 2 votes
I started using Lua and Löve a couple of weeks ago, I didn't find any good resource on getting started, I just used the wiki, it covers the very basics and then you can just use the documentation for the rest. It's not very different from any other 2D graphics API out there.

---
Tags: lua, love2d
---


# Question
Title: Is nVidia's CUDA suited to performing pathfinding calculations?
I want to know if it would be worth executing pathfinding on the GPU (using nVidia's CUDA, or an equivalent) in certain situations, or whether it would be a wasted effort. The situation I imagine would be a headless multiplayer server responsible for finding paths for bots.

I'm specifically interested in A\* pathfinding using navigation meshes, but if there is another pathfinding algorithm that would benefit more from GPU execution I'd love to hear it.

# Answer
> 8 votes
Path finding is essentially a graph problem, in which a lot of parallelism takes place. There are a lot of papers out there on how to implement and optimize graph based algorithms for CUDA.

I found some papers that might interest you (although these are quite academic):
http://cvit.iiit.ac.in/papers/Pawan07accelerating.pdf
http://ppl.stanford.edu/papers/ppopp070a-hong.pdf

So short answer: yes :).

However I don't know if the hassle of writing an A\* CUDA implementation together with the overhead of calls to a headless server is going to make this worthwile. Be sure to just make a small prototype first! (Also this would make for an interesting blog post, so be sure to write up what you're doing ;) ).

---
Tags: performance, path-finding, gpu, gpgpu
---


title: Manager game questions

text:
# Question
Title: Manager game questions
(Sorry about the bad title, it's the best I could come up with)

I've been planning a gladiator manager game for a while now. Something similar to Blood Bowl (or Football Manager, only with fighting rather than kicking a ball), only with a much larger focus on the actual managerial aspects of running a team. I'm still fairly new to game development, and have only created games with a very narrow focus (i.e. simple first person shooters), so taking on a project with a larger scope is very interesting, but also problematic since I really don't have a grip on how exactly to make the damn thing work.

Basically my two major hurdles are the interface and database. Obviously the interface is incredibly important since the player will spend most of his/her time doing managerial tasks. The game will be team-based, with various leagues in which those teams fight in, so it all relies on a database. I have never done any real work with databases, so this in particular has me stumped.

At this point, my idea is to use XNA in a WPF application, with an XML database. This just seems like a combination that would work well together, and as I have a C#/XNA background, I wouldn't need to learn a new language or graphics framework to work in.

Does that seem like a sensible combination, and if not, why? I have never done anything with WPF, so all of my information on it's uses comes from Google, and that may or may not be a good thing. Would XML be a smart choice? There will likely be a fairly low (think 20-30) number of teams, all of which will have a dozen or so fighters, so it's not a monstrously large set of data.

Thanks in advance, I know I didn't write the most intelligent post ever, but I had to get my ramblings out somehow. ;)

# Answer
> 5 votes
Ignore the Database and even the GUI at the beginning. Make the basic game-play work first. Just one session without saving/loading. That is hard enough at the beginning.

You will find yourself changing the actual data during development a lot. So if you maintain the loading/saving code for such frequently changing data, then you will find yourself 90% of your time maintaining that code, instead of making a fun game.

Take shortcuts on your way (use keyboard input instead of a GUI, create sample data on startup instead of saving/loading), don't go for the full blown game right from the beginning. This will keep you motivated because you actually have a game there and not only a database front-end.

# Answer
> 2 votes
I have no idea about databases either, but I can say now: XML is not a database, and to use it like one would be very painful. You're going to probably want some kind of SQL.

Also, it depends on the UI you want. My assumption for your want of WPF is the GUI part. I do not believe you can alter the graphical style of those parts. As such, you'd have a very bland UI. You may want to check out something like CEGUI# (CEGUI for C# and XNA).

# Answer
> 1 votes
"Database" is where it begins to sound like overkill. Your dataset is small enough that it will fit and run just fine in regular old C# data structures.

You certainly don't want WPF for a game -- all it gives you is bland standard Windows UI controls. Communist Duck's UI suggestion is excellent though!

---
Tags: xna, databases, wpf, interface
---


title: android game - lock_layer timed out

text:
# Question
Title: android game - lock_layer timed out
I'm developing a (scroll) game and i'm getting weird messages in LogCat:

* lock\_layer() timed out but didn't appear to need to be locked and we recovered(..)
* lock\_layer timed out (is the CPU pegged?)...
* executeScheduledBrodcasts() skipped, contention on the client. We'll try again later.

it looks like the rendering takes too long and causes the warning (i'm drawing ~ 50 images every frame), but is this the emulator fault? When i test it on a device (sony ericsson xperia x8), running 1.6, i don't see any lag or any performance drops (i get ~ 60fps). I get this warning only in android 1.6.

Should i ignore it? Could it cause the game to crash? Am i doing something horribly wrong or is it a bug?

Run code:

```
  while(running) {
    try {
       c = holder.lockCanvas(null);
       synchronized(holder) {
           // getElements - returns a Vector of elements to be drawn relative to camera
           elements = collection.getElements(cameraX,cameraY,cameraWidth,cameraHeight);
           for(int i =0 ; i < elements.size(); i++) {
              // draw the element according to camera
              c.drawBitmap(image,elements.get(i).x,elements.get(i).y);
           }
       }

    } finally {
       holder.unloackCanvasAndPost(c);
    }

```

}

# Answer
> 0 votes
You have implemented a fixed time step with frame-skipping. Any devices that cannot run your game are below the minimum requirements.

You should find some users with older devices to test with, and see exactly how old of a system your game can actually run on. Once you are at that point, see if there is any optimization you can do to improve the speed.

# Answer
> 0 votes
The android emulator is much slower than the average modern device.

In a game I was making I easily reached 60fps on my Nx1, but on the emulator I was barely able to reach 15-25fps.

You're correct when you say that this error happens because rendering takes too long, and be warned that you might get the same problem on slower devices, or anyway devices that are running in background many apps while they run yours — so yes, you have to actually solve it.

As @AttackingHobo suggests, you have to implement a system which supports frameskipping.

---
Tags: 2d, android
---


# Question
Title: Slow motion of a spherical object on an blunt slant obstacle
In cocos2d environment and box2D when an spherical object falls on a blunt slant obstacle, it moves really slowly, that's nauseating, if you have coded to not to have any interaction with world while object is in motion. Is there any way to get rid of this slow motion of object?

# Answer
It's possible that your slant really is not steep enough as Aku says, but it's more likely you flagged the object for fixed rotation, meaning it's not rolling down the slope, but rather sliding against friction. This makes it much slower, and if the slope is not steep enough, can halt it entirely.
> 2 votes

# Answer
Physics dictates that when you put a ball on a slant, it tends to roll. If it's a small slant, it rolls slowly. It's a matter of certain physics applied to certain conditions.

To get the effect you want, you have to either change the conditions...

* for example, increase the slope to get it to roll off quicker

... or change the physics...

* for example, add more friction (this could be conditional; only added if the slope is very small).
> 0 votes

---
Tags: iphone, box2d, cocos2d-iphone, cocos2d
---


# Question
Title: Cannot run quake 3 engine compiled from source code
Recently I tried to compile and run the source code of Quake 3 engine. I basically followed this article. However it doesn't work for me.

I am using Visual Studio 2010 on Windows 7, with June 2010 DirectX SDK (I doubt if it is necessary). Here is how I did:

1. Install the original version of Quake 3 Arena to "D:\Quake III Arena", and update to 1.32
2. Download and extract the source code
3. Open `quake3.sln` in "`code`" folder. Visual Studio upgraded it to 2010 format.
4. Build all the 8 projects in Debug mode (in some order). I checked that every project had been built successfully
5. In the properties of quake3 project, in Debugging page, I changed "Working Directory" to "`$(TargetDir)`" and "Command Arguments" to "`+set fs_cdpath "D:\Quake III Arena"`"
6. Set quake3 as the Startup Project and press F5

The game started and could correctly recognize the game folder and parse some options, such as screen resolution. However an exception window popped out before I can see the game main menu, saying "Unhandled exception at 0x053e9938 in quake3.exe: 0xC0000005: Access violation."

I tried to start the game from command line, but it had the same problem.

I followed the code and found that the exception was generated in `int VM_CallCompiled(vm_t *vm, int *args)`, when executing `call entryPoint` in the `__asm` block, located in line 1148 of vm\_x86.c. Since it's assembler code, I don't know how to debug it.

I don't know if anyone here knows about this problem. Could anyone provide some help on this? Thanks gratefully.

# Answer
Add `+set sv_pure 0 +set vm_game 0 +set vm_cgame 0 +set vm_ui 0` in the command line argument.
> 7 votes

---
Tags: quake3
---


# Question
Title: How are the responsibilities and program flow organized, in a graphics engine?
I'm starting up on OpenGL, and want to write a well structured and expandable, yet relatively simple 3D graphics engine for fun and personal knowledge. I'm looking for information concerning the best practices and design patterns related to this sort of code.

Specifically, I'm having issues deciding how classes should be organized, how to divide responsibilities, etc. Right now, I'm at the point where everything is done in the rendering method!

Can anyone give me some advice? How are the responsibilities and program flow organized, in a graphics engine?

# Answer
> 6 votes
I subdivided my classes into three kinds:

1. Central renderer class.
2. Resource class- texture, mesh, font
3. Instance classes- label, sprite, 3D Object

I kept lists of type 2 and 3 classes in the central Renderer class, and when draw time comes, then I already know all the objects to render. When you come to draw, then efficient drawing does not lend itself to drawing each object sequentially- you will want to do things like sort them in certain orders.

Edit: To be more specific, the user manages the lifetime of the resources. They're shared amongst all the instance classes that are using it, and the user. If the caller of the code wants to cache the resource, then that's their problem.

---
Tags: graphics
---