# Question
Title: Dump texture from memory to the original format?
How can you dump GPU memory (images and such that are loaded on it) to the standard format ?

# Answer
> 4 votes
As far as dumping resources from running Direct3D 6.x, 8.x and 9.x applications, you might want to check out 3D Ripper DX.

Here's a quote from the tool's website about its features:

> With 3D Ripper DX you can:
> \- Capture all geometry, textures and shaders, rendered during single frame;
> \- Import captured geometry into 3D Studio Max or Maya;
> \- See what exactly has been drawn by each individual draw call;
> \- See renderstate, textures, vertex streams, index stream, vertex declaration, vertex and pixel shaders (including HLSL source code if available) of each individual draw call.

# Answer
> 4 votes
If you're asking how to dump the texture into the original **file format** from which it was loaded, there is no way to do this. Once the texture is loaded, be it from a JPEG, PNG, BMP, TGA, etc., it is represented as an in-memory bitmap using one of many standard pixel formats. There is often no way to determine what the source file format was. However, you can save it back to any format you choose. Keep in mind that if the texture started out in a lossy format (like JPEG) then there is no way to get that "original" JPEG back once it's been loaded into memory--it would have to be re-compressed to be saved in JPEG format again, and that could very well lead to further quality loss. However, you could save it to a lossless format like PNG to avoid that quality loss.

---
Tags: textures, gpu
---


# Question
Title: How do I query available video memory using DirectX?
How do you query the amount of VRAM available when using DirectX?

# Answer
According to Game Coding Complete 3, there are a few ways:

* DX7's GetAvailableVidMem() - usually pretty good. Doesn't work too well on cards with shared memory.
* WMI (Windows Management Interface) has a similar result to the above.
* DxDiag uses both to give a better result.
* D3D9 has a GetAvailableTextureMemory() function, but can only be used on Windows Vista/7.

Look for a DX sample in March 08 or later SDK called 'VideoMemory'.
> 8 votes

# Answer
For DX9EX on Vista and later:

```
IDXGIDevice * pDXGIDevice;
hr = g_pd3dDevice->QueryInterface(__uuidof(IDXGIDevice), (void **)&pDXGIDevice);
IDXGIAdapter * pDXGIAdapter;
pDXGIDevice->GetAdapter(&pDXGIAdapter);
DXGI_ADAPTER_DESC adapterDesc;
pDXGIAdapter->GetDesc(&adapterDesc);
return adapterDesc.DedicatedVideoMemory;

```

(from http://msdn.microsoft.com/en-us/library/bb174526(v=VS.85).aspx )
> 5 votes

---
Tags: graphics, directx, windows
---


# Question
Title: What data should I use to track the player position on a world at the same size of the earth in a multiplayer game?
I guess this kind of game or simulator already exist somewhere, but I'm not sure...

Let's imagine I'm making a game where the proportions of the planet earth and the humans beings on it are the same as in the reality. I can't only use longitude/latitude with float because when being far away from the origin, precision would be lost: when the float exponent gets too high, the digit at the right would be rounded and thus, not considered. Or to say it simpler, `float` are not precise enough to position an object on earth using longitude/latitude while keeping smooth movements.

Since there is a need to track each player's position in an homogenous way, I'm thinking about dividing the world map into indexed subparts (thus integers), and then precisely position the player using a float or double.

This would look like this:

```
struct position_on_earth
{
int sector_x, sector_y;
float pos_x; pos_y;
};

```

Is it potentially faster to use this kind of data instead of using `double`s ?

# Answer
> 12 votes
Earth's Surface Area ~ 5.1×10^14 square meters

If the world were flat, you would have enough precision from making pos\_x and pos\_y 32bit integers to divide the entire world into a uniform sub-millimeter grid. Depending on the scale of your simulation, this might well be enough precision.

If you're going for a spherical world, however, you're going to need a different kind of coordinate system.

EDIT: In fact, just using a dumb 32bit int grid still isn't all that bad if you move to a sphere! Some more details about earth:

Mean radius 6,371.0 km Equatorial radius 6,378.1 km Polar radius 6,356.8 km

Lets say we put our model earth in a cube with sides 13,000 km in length. If we use 32bit ints for x, y and z coordinates, we still get sub-centimeter precision. As an added bonus, we don't need to handle altitude / depth as a separate special case anymore (although this might be viewed as a disadvantage, since we will need to check the direction to the planet's center when we apply gravity).

# Answer
> 1 votes
Earth-Centered, Earth-Fixed

ECEF

Edit: don't worry about the gravity vector, it's always easy to get a unit vector to the origin. Doubles will do your XYZ units just fine.

# Answer
> 0 votes
As I said in my other answer to your other very similar question, you should read "The Continuous World of Dungeon Siege". He does indeed suggest dividing the world up into a "relational node-based coordinate system, in which each chunk of geometry (Siege Node) has its own coordinate space". Your struct seems to mirror this, so I think you're doing fine.

# Answer
> 0 votes
Your structure is potentially faster as long as nothing which needs a position (this includes path finding or finding out the distance to places halfway across the planet) crosses the section boundaries all that often - in other words, if all your algorithms and procedures have a strong *locality* to them. If your use case is the other way around, I'd suggest storing the position in precise, global uint32 values (which would have about a centimetre precision) and storing a float (or even just float16 if your hardware supports it) *displacement* value from this position for display on screen, local physics simulation and similar cases.

---
Tags: c++
---


# Question
Title: How do I make NPC pathfinding look believable?
Is there an "academic" way to have NPC walking randomly on a map, but having a believable comportment ?

The obvious scenario is a armed guard who is walking around a basement to secure it. It's quite easy to set up a "believable" path.

What I'm looking for is a way to simulation a crowd in a small town, in fact. How can I make their move look like they aren't goalless robots.

# Answer
I suggest you have a look at Craig Reynolds Steering Behaviors. To make things more interesting, you could also switch behaviors depending on the situation the NPC is in.
> 7 votes

# Answer
> aren't goalless robots.

Easy, give them goals. Give each NPC a destination depending on the map you may not even have to path find for them just Steering, or precompute the path between doors in town.
> 3 votes

# Answer
A combination of node-navigation and steering behaviors actually produces some nice results, if you believe research documents (I personally haven't tried this approach): Link to paper:Steering a Virtual Crowd Based on a. Semantically Augmented Navigation Graph
> 3 votes

# Answer
Create goal nodes at logical places of interest in your world and then have the NPCs navigate between these nodes. Ideally you also have animations associated with the goals such as looking at a billboard, throwing trash into a trash can, sitting on a bus bench.

Then as NPCs spawn give them a target to go to and use. Once they've finished the animation at a target, give them a new one.

To break this up further, having some random idle time after finishing a goal, so they don't all go to the next thing immediately. Also spawn some NPCs at their first target so they immediately start playing the goal animation. The more interesting objects you have in the world the more it will feel like a place.
> 3 votes

---
Tags: ai, path-finding, random
---


title: Clipping a SpriteBatch Draw() in XNA

text:
# Question
Title: Clipping a SpriteBatch Draw() in XNA
Is there any way to enable a temporary clipping mask in XNA while using a SpriteBatch? I'm drawing a bunch of Texture2D objects and Sprites in a given rectangle, and I want to make sure that said objects aren't drawn outside of that rectangle. If it's of any help, I'm already drawing my content within a Viewport, I'm not sure if I can draw, for instance, in another Viewport within that Viewport.

Illustrative image of what I'm trying to accomplish:

# Answer
> 10 votes
The scissor rect is a bit easier to use than the stencil buffer. You need to set ScissorRect to your Rectangle and set ScissorTestEnable to true.

```
        // In XNA < 4.0...
        spriteBatch.GraphicsDevice.RenderState.ScissorTestEnable = true;
        spriteBatch.GraphicsDevice.ScissorRectangle = clipRect;
        spriteBatch.Begin();

        // In XNA 4.0, the ScissorTestEnable has moved, so do this instead...
        spriteBatch.GraphicsDevice.RasterizerState.ScissorTestEnable = true;
        spriteBatch.GraphicsDevice.ScissorRectangle = clipRect;
        spriteBatch.Begin();

```

# Answer
> 2 votes
You need to use a Stencil Buffer. This is specified by passing a DepthStencilState into your SpriteBatch.Begin method call.

> For example, to remove an object from a scene, fill a stencil buffer with a cut out pattern (using zeros) for each pixel where the object is visible. This is done by setting the reference stencil value to 0, clearing the stencil buffer, and rendering the object. Then set the reference stencil value to 1, set the compare function to CompareFunction.LessEqual, and render again. The stencil data masks those pixels whose value is non zero but less than 1, resulting in drawing over (or removing) the object.

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


# Question
Title: Making a character move along a curved slope in a World with gravity
I have seen this game

Fancy Pants 2. And the thing I noticed apart from the physics and beautiful animations is that the character is moving along slopes , even curved slopes. I have little experience in Box2d, but this concept of curved slopes is new to me. It would be a great help to me If somebody enlightened me on this concept and its implementation. Even If the implementation is not in box2d, it is welcome.

# Answer
**How do you get curves in Box2D?**

In the unreleased version of Box2D, there are two new shape types, b2LoopShape and b2EdgeShape, which let you build curves out of a sequence of line segments.

In the released version, you can use multiple small boxes set at angles to get a similar effect, but bodies have a tendency to do unstable and unexpected things near connection points. So I'd recommend using the unreleased version.

**How can a character fall down the curve?**

Make the character a wheel! My question about platformer physics has some discussion on this, but the basic idea is to mount your character's body on a rotating wheel, and move by applying rotational force to the wheel. Even though (actually, because) the wheel has friction, the downward force from gravity will cause it to rotate down slopes - like a real wheel. By changing the revolute joint's motor parameters, you can make it resist rotation as much as is necessary to avoid it rolling down small inclines.
> 5 votes

# Answer
Fancy Pants was made in Flash, and Flash has a specific method called 'hitTest' which allows you to test a pixel (in this case, he probably does 2-3 pixel hitTests along the bottom of the Fancy Pants character) against whatever is drawn within a designated movieclip object. It can be a bit tricky to get it feeling right, but this built-in function is why so many Flash games have collisions with curved slopes. The process is much more complicated for most other engines, and usually has to be done manually, but there are a few different methods.

The method I'm most familiar with is if your engine is tile-based (think Sonic the Hedgehog), the tiles designated as curved could each have a formula which determines the 'Y' collision position based on the character's current 'X' position on that tile. You would have to determine the formula based on how steep of a slope and how curved you're looking for. You could use a graphing calculator or graphing program to experiment with the formulas. You can have multiple tiles with different curves and formulas associated with them this way.
> 1 votes

---
Tags: game-design, flash, box2d, physics-engine
---


title: Game Programming

text:
# Question
Title: Game Programming
Are there any major/fundamental concepts that one should know about game programming versus control driven programming?

Game Programming is event based? with a timer? An outer-infinite loop?

I come with a background of C++, Java and Ruby. I'm interested in making a basic 2D Game in Flash. Is there anything else that may be easier for me to jump into? I'm currently interested in only 2D since I don't think I'm ready for 3D.

Any great books that a interested game programmer should read?

Thanks in advance.

# Answer
Ignoring your book question, since that is answered elsewhere...

> Game Programming is event based? with a timer? An outer-infinite loop?

Typically the latter is the case, that you have an "outer-infinite loop", or game loop, which repeatedly updates the game state and renders to the screen.

However, in Flash, I believe they use a timer to simulate this game loop; a function is called repeatedly, and that function should update the state of your game. You don't need to redraw the entire screen in Flash, but instead you move entities and change keyframes and things like that, using ActionScript. The Flash plugin handles drawing things.

The only games that would be event-based would be perhaps puzzle games or card games. For example, Solitaire would not require a game loop rendering the screen at 60 FPS; it can just react to user input actions and draw when necessary.

Flash affords other features you can take advantage of; for example, its timeline nature means that you can implement different game screens as keyframes on the timeline (game screens being the different states of your game - main menu, game, pause screen, credits,...).

It's good that you're aiming for 2D. Flash doesn't really do 3D, and it is indeed an added level of complexity that you shouldn't have to deal with until you are clear about the game loop and other important game programming basics.
> 3 votes

---
Tags: game-mechanics
---


# Question
Title: Where can I find a opengl pixel shader example for smooth SpotLight?
I am using Ardor3D, and find the spotlight is quite bumpy. Anybody has a good pixel shader can smooth the edges of the spot light?

thanks,

# Answer
I think what you're looking for is something similar to soft shadows, only lightening instead. You could have a look at both nVidia and ATI's developer sections for sample shaders to do all sorts of things.
> 3 votes

---
Tags: special-effects
---


# Question
Title: Should the color of a texture be adjusted for display on a television?
If a 24bit RGB image with a range of 0-255 per channel is displayed on a television that displays a range of approx. 16-235 per channel, color detail will be lost, correct?

If so, should images be pre-processed to only store a valid range? I would like to do this with code, not in a picture editing application. I vaguely recall reading that a linear mapping is not the best way to do this, but unfortunately I can't locate the article I was reading! What is this process called? What other details do I need to know?

# Answer
> 8 votes
Some color data will be lost or changed regardless of your texture format. However, a bigger problem will be gamma correction. Gamma correction can be a tricky subject since your game will not appear visually the same across all display technologies and finding a single solution is not going to be easy.

These might help you out:

# Answer
> 5 votes
Linear mapping is probably not the *best* solution (which I believe involves converting your RGB to a CIE colorspace, scaling there, and converting back), but it is very easy to implement, and the range difference is small enough it probably won't matter.

If you use SOIL, it can automatically do this when loading the image, by passing SOIL\_FLAG\_NTSC\_SAFE\_RGB to the load functions.

Microsoft's documentation says to clamp, and recommends doing it in a pixel shader. (Linear scaling should also be easy in one.) It also mentions chroma crawl, which in my experience is a much more annoying phenomenon when working on TV displays.

---
Tags: textures, c, console, image
---


title: Writing a custom model file format

text:
# Question
Title: Writing a custom model file format
I am using Ogre for my rendering engine, and I planned on just using the .mesh format that is setup by default with Ogre. However, I recently purchased a large number of 3d assets from a company, only to find out that they use 7 blend weights where as Ogre has a max limit of 4.

I don't know much about modeling and animation (which is why I purchased the art) but just from thinking, it is probably fairly difficult to change something like this in the model without having to reanimate it.

So this led me to think about a custom model format. I know the basics of what is stored, verts/polygons/etc, but I am wondering if this is something I am right in thinking I probably need to do? If so, are there any good resources on developing a custom model format? Tutorials/samples/anything would be great. So far all I have found is http://www.falloutsoftware.com/tutorials/gl/gl6.htm which is helpful but not complete.

# Answer
In OgreConfig.h you can find the OGRE\_MAX\_BLEND\_WEIGHTS option. It is set to 4 by default and I never tried setting it to anything else myself, but it is worth a try. (You have to recompile Ogre afterwards of course.)

The Ogre mesh file format itself has no limit for the number of bone assignments per vertex. The binary format simply stores bone assignment as arrays of {unsigned int vertexindex; unsigned short boneindex; float weight;}

On the other hand, seven blend weights seems like overkill, so another way is to leave out the three assignments with the smallest weights and adjust the other four bone assignments.
> 2 votes

# Answer
Google returned this result on the GD.Net forums.

Then again, could you use another existing mesh format with Ogre instead?
> 1 votes

---
Tags: c++, ogre, file, models
---


# Question
Title: Where can I see example sell-sheets for a game?
So my long term one-man indie project is turning into a two-man indie project, and I feel I need to take a step back and at least have a "sell-sheet" as a basis for the game design.

Does anyone have any good templates or tips?

# Answer
The basic structure is:

* One liner (aka Logline) - 1 sentence description of your game
* High Level Concept - Short paragraph giving an overview of the world/setting
* Gameplay - Short paragraph of your take on the genre, and 3-5 bullet points of key features

The difference between a 1 pager and a 4-5 pager is that each bullet point then gets a more detailed description explaining how it works. Sprinkle in any art you have where you can.

Unfortunately I can't share any real ones, but if you'd like to see some early documents from actual shipped games you should check out http://www.gamepitches.com. Lots of cool peaks at early pitch and design documents from shipped games.
> 4 votes

---
Tags: game-design, design-document
---


# Question
Title: What do you do when you are at an impasse in the design phase?
I own a small web dev shop, and in our down time, I plan on having my guys work on a game (I will be paying them anyway, right?). A few buddies and I started talking about this game, and have been going through the motions of talking/designing it out.

Only problem we are at an impasse, and can't seem to get passed it. The vote is at 50/50%. Compromising hasn't worked.

I have though about just making an executive decision since I am funding the development/design of the game, but I don't want to lose my friends support for the game, and their other opinions.

I don't know what to do.

# Answer
**Building games by committee is a bad idea, you end up with all the ideas watered down or not implemented correctly.**

From the beginning you should have put yourself in the "Lead Designer" position, but now I think it could be a bit late for that.

You should start by having them work on some different 1 or 2 day prototypes to get some of the base gameplay down and then go from there. A lot of ideas that sound bad or too complicated on paper are actually really fun.

Have each group break off and make a small prototype to test the ideas. Then you have something tangeable to compare, instead of most likely poorly communicated ideas.
> 19 votes

# Answer
Really depends on how central this issue is to the gameplay and how quickly you can get the two options up and running.

**Big Central Issue**

If you are talking something central, like half the team wants to make an FPS and the other half an RTS then there are no easy solutions. Look at the space you are going to be releasing the game in (web/phone/...) and go with the one that's more commercially viable if you plan on selling it.

**Easy to prototype issue**

If the problem is small and can be easily prototyped you can at least try both versions out. Unfortunately if there isn't a very clear winner in the prototyping it will suffer from confirmation bias and both sides will still think their side is right.

**Avoiding in the future**

You need to get out of the design by committee mindset, as mentioned by AttackingHobo, it's not conducive to making quick or coherent decisions. Unfortunately if no one of the team has experience making games it can be difficult to get everyone to follow one person since everyone thinks they can be a designer.

While you are learning the game development process I would suggest looking at other games similar to what you want to make for a lot of solutions. While you don't want to just make a carbon copy of an existing title you only need 1 solid new feature to differentiate your game. Outside of that core feature just copy what the market leader for your genre is doing. You'll learn a lot about what they are doing right and it's easy to justify a design decision by pointing at a successful title and saying we are doing it just like that.
> 4 votes

# Answer
Game design is an empirical science. Not even the world's best designers can design in their head. Slap together a prototype and try it out. In about five minutes of playing the game, you'll be able to tell if the idea works or not.
> 3 votes

---
Tags: game-design
---


title: Tile coordinates

text:
# Question
Title: Tile coordinates
Simple question I have here.

Say my tile map is based on 32x32 tiles for an 800x600 image so let's say 25 tiles across and 19 down.

So now I have that cell 0 of any row contains the first 0-31 pixels, cell 1 contains then 32nd-63rd pixels, cell 2 has 64-96 pixels and so on. If I have my player somewhere and now I want to get the corresponding tile, what can I do? I can't just divide by 32 as this doesn't always work such as here:

Let's say I am testing both 64 and 96 in the x direction and am testing against the range of 64-96 (which should be in cell 2 of any row)

64/32 = 2 (this is the correct column for my tile map for any row) 96/32 = 3 (incorrect, the 96th pixel is still within column 2 for any row of the tile map)

# Answer
> 8 votes
Actually it seems that your calculation is correct - you are just mistaken about pixel 96. Column 3 contains pixels 64-95 inclusive, not 64-96. Dividing by the tile size is in fact the correct method.

---
Tags: tiles, coordinates
---


# Question
Title: Turning layout items invisible in Android layout
I am trying to turn some items visibility off when submitting a high score.

I have the following code but it does not appear to work. Any suggestions?

mSignText = (EditText) findViewById(R.id.sign);

submitBtn = (ImageView) this.findViewById(R.id.submitbtn);

mSignText.setVisibility(View.GONE);

submitBtn.setVisibility(View.GONE);

# Answer
> 1 votes
For visibility, you must use setVisibility as you have done:

* View.VISIBLE
* View.INVISIBLE
* View.GONE

GONE set the view as invisible, and it doesn't take any space for layout purposes.

http://developer.android.com/reference/android/view/View.html#setVisibility

---
Tags: android
---


title: Game platform for .NET

text:
# Question
Title: Game platform for .NET
I near completion of implementing mymultiplayer game (in WPF/.NET). I want to exploit the game commercially. To do so, I compiled a list of requirements:

* .NET/WPF
* Game server (multiplayer)
* Data server (website/ingame info/widgets/etc)
* Website (rules/docs/download)
* Forum
* Rating system (chess-like, but for 4 players)
* OSS is a big pro (or ability to move to OSS in future)

What options do I have to create a platform for hosting the game? Obviously, I can create everything myself, which has advantages and disadvantages. Do you have any experience utilizing exisiting services offering (part or complete) above requirements?

# Answer
> 1 votes
Amazon Web Services might serve as hosting for your game server, database, and website, etc. I believe you could run one instance for your .NET services and a second instance, running linux, for your PHP services. You'd likely want to find open source PHP based forum software. You may have to roll your own rating system.

# Answer
> 1 votes
Windows Azure might serve as hosting for your game server, database, and website. I believe it has support for PHP in addition to .NET meaning you could use any open source PHP forum software.

# Answer
> 0 votes
I'd suggest the multiplayer server run locally on the host's machine. WCF is a great choice if you don't need very high throughput. Otherwise, there is a pretty decent networking library for .NET called Lidgren; it supports TCP as well as reliable UDP-based messaging.

I would try to find a lobby system that you can hook, preferably one with a web service API that your clients could use to locate and advertise multiplayer games. I have no idea what's available in this area, but I suspect you may have to wrap an unmanaged library or roll your own. The lobby application, if you host it yourself, could be hosted on Windows Azure, along with your game's website and forums.

---
Tags: platform
---


# Question
Title: 3DS Max equivalent to vertex weight painting
I'm working in 3ds max on models for an Iphone game project and finding that using the Physique modifier is to general for rigging. When working with so few vertices I want to be able to directly tell how much weight a bone should have on a specific vertex.

Is there a 3ds max equivalent to the Softimage XSI vertex weight painting? As this would be perfect for this job.

Many thanks

# Answer
> 2 votes
Actually you want to use Skin not Physique. It's mainly in there for backward compatibility with character studio from years ago.

Max: Rigging tutorial

---
Tags: 3d-meshes, models, rigging
---


# Question
Title: 2D Real-Time shadows on level on a level made from a Dynamic Bitmap
The Bitmap has transparency, and only non-transparent pixels are solid and used for hit detection for the physics engine and gameplay.

I have seen some versions done with convex hulls, but for multiple reasons I am not using convex hulls to build the levels in my game.

**How can I implement 2d shadows on a level made out of a Dynamic Bitmap?**

*The answer jpaver posted is good, but I am sure there are some other ways to do this. Does anyone else have any more information on this question?*

# Answer
This is only one way to approach the problem.

For each source pixel in your bitmap, ray march towards the pixel that currently represents the light source. If you hit a non-transparent pixel along the way, stop marching and assign a shadow value to your source pixel. If you reach the light pixel, the source pixel is lit.

As you can probably tell, marching and testing every pixel along the way for every source pixel can get expensive, especially when adding multiple lights. Fortunately, there are things that can be done:

* assign a bounding circle to your light. Before marching, test if the pixel is inside or outside of this circle radius. If it's outside, it's considered in shadow by default and there is no need to march. If it's inside, do the ray march. If the ray march yields that the pixel is lit, use a falloff function to determine how bright it is. (side note: interesting falloff functions can be derived to make your lights flicker and animate)
* To avoid marching and testing every pixel, pre-compute a distance field for your static bitmap. The distance field simply stores the distance to the closest opaque pixel for every pixel. Then when marching along a ray, you look at the distance field, and are guaranteed to hit no opaque pixels by stepping that amount. (side note: you can use these distance fields for your physics too).

EDIT: to answer comment about dynamic updating problem:

If you have a dynamic bitmap field, updating the distance field is a bit of a pain. I'm sure there are clever techniques for doing this out there, I'm just not versed in them. Someone else is free to comment here if they are in the know! :)

An alternative technique to accelerate your ray marching is to use an tiled hierarchy that encodes your empty space in a much more efficient way. You can precompute the hierarchy from your original level bitmap, and only need to update parts of it when you add or remove opaque pixels.

So what does the hierarchy look like? If your original data of size MxN is mip0, then:

* mip1 is M/2 x N/2 (ie. half as big as mip0 in each dimension)
* mip2 is M/4 x N/4 (ie. half as big as mip1 in each dimension)
* mip3 is M/8 x N/8 (ie. half as big as mip2 in each dimension)
* etc.

The higher mips store whether there is any opaque geometry in the lower mip level pixels. If you wanted to update mip\[k\] at pixel(i,j), you'd probably do something like this:

```

  mip[k].opaque[i][j] = mip[k-1].opaque[i*2][j*2] ||
                        mip[k-1].opaque[i*2+1][j*2] ||
                        mip[k-1].opaque[i*2][j*2+1] ||
                        mip[k-1].opaque[i*2+1][j*2+1];

```

Once you have the data structure computed, you can march your ray directly to the edge of a tile if that tile contains no opaque pixels. Your algorithm would look like this:

(extreme pseudo-code)

```

void StepOnce(int &x, int &y, int xDir, int yDir)
{
   int k = COARSEST_MIP;
   while (k > 0)
   {
      int x_in_mip = x >> k;
      int y_in_mip = y >> k;
      if (!mip[k].opaque[i_in_mip][j_in_mip])
      {
        // Here we can step (i,j) to the next tile for mip(k)
        // (I'll leave the math as an exercise to the reader)
        return; // exit since we've stepped once
      }
      else
      {
         // go to a finer level tile.
         k--;
      }
   }
   // do the math to step once.
   return
}

```

Updating this structure is simply a matter of tracking a dirty region (ie. rectangle) for level 0 every frame. Once you've accumulated all changes, just update those pixels falling in the dirty region and update higher levels that touch that region too.

Note: if you're doing this on CPU, you may want to:

* rearrange the ordering of pixels in your bitmap data so that a tile of NxN all fall within the same cacheline. This will tend to improve your cache hit rate tremendously when ray tracing vertically.
* also, if you ray march your pixels in tile order rather than screen-width scanline order (one at a time, or 4 at a time using SSE), you will further improve your cache hit rate.
> 4 votes

# Answer
The answer to the following question has a link you might find very useful : How is 2D lighting implemented?
> 0 votes

---
Tags: 2d, actionscript-3, lighting, shadows
---


# Question
Title: Elegant way to simulate large amounts of entities within a game world
Assume you have a game in which there are many (many many) entities serving some functions, not all of which are constantly needed or need to be considered in every frame. The concrete problem I am working on in which this issue is present is a detailed simulation of a body including its organs.

In the game each creature has its own body which is separated into smaller parts (torso, legs etc.) and sometimes these parts contain organs, which serve a specific function within the body. Whether or not an organ currently serves a purpose or is active is never actually clear. After all, an animal might have an empty stomach which therefore does not need to digest anything. It would be quite ridiculous to check or simulate every object in each frame and very costly as soon as you have many creatures in the world. So I was thinking about a way to smartly differentiate between objects that need to be updated and those that don't.

What I came up with seems like an at least ok solution. It creates a simple queue/stack (essential is that each element gets removed as soon as it's read; the order is irrelevant) called the "attention stack" where objects that need to be simulated reside. Objects that need attention would simply put themselves onto the stack *or* are put there by other objects. These objects would probably implement a simple interface with a simulate()-function.

Applied to my previous digestion example this would mean:

The player chooses something to eat (assume it's bread) from the inventory and puts it into the mouth of his character and the mouth is put onto the attention stack. In the next frame the the mouth is taken from the stack and its simulate()-function is called. Since it's a mouth it would be reasonable to simulate chewing here. This could go on for a few frames in which the mouth keeps putting itself onto the stack until it decides the food is ready to be swallowed. In this case the mouth puts the chewed bread into the stomach (I know it doesn't go there directly, but the esophagus is left out for simplification), which is then also put onto the attention-stack. In the next frame the simulation of the digestion-process is started. And so on for the rest of the necessary organs.

A foreseeable problem with this are idling objects. A sleeping animal is a good example of this. It could be done as previously described by keeping the sleeping animal on the stack and checking each time if it needs to wake up, but that seems wasteful since that's the only thing being done. To make idling objects more efficient I was planning to add a sort of schedule which stores jobs to be performed at a specific time. If an animal goes to sleep it would put a job on that schedule which would be scheduled for a certain amount of time after the animal went to sleep. This job would then take care of putting the sleeping animal onto the attention stack again. Now, you could say that a sleeping animal that isn't on the attention stack could miss being attacked by something because its A.I. is not simulated, but this is prevented if the attacking object takes care of putting that animal onto the stack again.

Now, I honestly don't know if this is even close to an elegant solution to this problem due to a lack of experience. Am I close to something usable? How is this usually done or does anybody have any suggestions or better solutions?

# Answer
This is exactly the way we solved this problem in Stendhal. In our case there are lots of things that happen periodically, but not every turn: Healing spells, plants growing a little further, corpse degenerating, items on the ground expiring.

We have a turn number that is increased in every turn. And we maintain a map of future turn numbers pointing to a set of objects that need to be notified in that turn.
> 10 votes

# Answer
Sounds like a similar problem to that of inputs: you have 100+ keys on the keyboard but don't want to check each individual key on every frame, so what do you do?

Two answers: polling or system messages.

Polling = at any point when it would actually matter in the game, query the state of the keyboard keys (or the objects, in your case). The rest of the time, ignore them.

Messages = have each keyboard key (object) put something in a message queue when it's pressed or released (when it needs attention). On each iteration of the game loop it looks through the queue and resolves all messages before proceeding.
> 14 votes

# Answer
So I'm going to take a step back from implementation and review the question from a design perspective. Do you have a solid plan for displaying all the detail you want to include in this simulation?

For example:

* Can the player tell the difference between an animal with an empty stomach and an animal with a full one?
* Does this information matter to them in any way, when they are making interaction choices within your game?
* Could a player watching the animal consistently predict the outcome of your simulated events, or would a random number suffice?

Basically the general rule of thumb is to not make your simulation any more complicated than its outputs. At the end of the day if the only animations you have for sheep are graze, sleep, run away. Then it really doesn't matter how many factors go into the decision about which state to choose. All players are going to see is sheep that sleep at night, run from danger and eat during the day.

Behavior simulation is a ton of fun to work on, but always keep the end users experience in mind.
> 10 votes

# Answer
I had a similar problem on a game I worked on a few years back - the simulation of objects was complex and couldn't really be performed in detail on every object in the world.

The solution was to use the LOD concept to the simulation. Objects within the view of the player would run the full simulation. Objects far away from the player ran a highly simplified simulation periodically. As objects came into the player's view they would transition from course, periodic simulation update to detailed, regular updates.
> 9 votes

# Answer
Solution with a schedule is good. Note that every entity should have a list of pointers to its future actions, which gives possibility to invalidate future actions if necessary. Ie. sleeping animal wakes up instantly when attacked, so you have to invalidate its wake-up action in the future.
> 2 votes

# Answer
There's a design pattern for this. I think it's called Database Objects?

Basically, you keep one "template" sheep that can represent all the non-special sheep in the game world, draw them all the same way, keeping the unique data within the template object, say as a table of sheep locations and/or time-since-shear. Then whenever you need to make a sheep unique, you can create a specific instance to track that unique sheep.

The same goes for animations. If it's an idle animation or event common to every instance, that can reside in the template instance, where more specific animations can be scheduled separately.

A long time ago, I wrote a game for a programming contest whose main loop just called animate() on the entire scene. It used function pointers to replace idle animations with others as required, and used the technique to support inherited animation (eg spinning a character that's standing on a spinning disc).

That's similar in nature to using a delegate for animation.
> 1 votes

# Answer
Would a state machine work? The animal is either in e.g. sleeping state, eating state, running state etc. For each state you associate a list of active organs. So each frame you visit each animal, switch on state, lookup list of organs for that state and execute update on each of the organs.
> 0 votes

---
Tags: architecture, algorithm, simulations, scalability
---


# Question
Title: Thread runs faster on a faster processor... how to control Thread speed
I have a thread that uses TimeUnit.MILLISECONDS.sleep(5);

Problem is when I load my app on a faster phone say with a snapdragon, it runs at lightning speed.

Is there a way to control this speed so processor speed is not an attributing factor?

Thanks!

# Answer
> -3 votes
He'res the class I wrote for this purpose. Use it by first calling start() and then sleepRequiredTime() in your gameloop. call getTimeSinceLastSleep() for elapsed time.

runsPrSecondHint will dictate your wanted FPS. I'm not sure this solution is perfect though, so any input from others is welcome.

```
package com.ngame.spacegame.utils;

public class ThreadSleepManager {

private int m_runsPrSecondHint;
private float m_maxAllowedSleepTime;
private boolean m_running;

private long m_startTime = 0;
private long m_lastSleepTime = 0;

private int[] m_lastRuntimes;
private int m_runtimeToWriteToIndex = 0;
private int m_averageSleepTime = 0;
private int m_timeSinceLastSleep = 0;

private static final int AVERAGE_POOL = 10;

public ThreadSleepManager( int runsPrSecondHint ) {
    m_runsPrSecondHint = runsPrSecondHint;

    m_maxAllowedSleepTime = 1000.0f / m_runsPrSecondHint;
    initLastRuntimes();
}

private void initLastRuntimes() {
    m_lastRuntimes = new int[AVERAGE_POOL];
    for ( int i : m_lastRuntimes ) {
        m_lastRuntimes[ i ] = (int)m_maxAllowedSleepTime;
    }
}

public int getTimeSinceLastSleep() {
    return m_timeSinceLastSleep;
}

public int getAverageSleepTime() {
    return m_averageSleepTime;
}

public void start() {
    m_startTime = System.currentTimeMillis();
    m_lastSleepTime = m_startTime;
}

/**
 * Sleeps an optimal amount of time for trying
 * to have the current thread calling run at m_runsPrSecondHint
 */
public void sleepRequiredTime() {
    assert( m_running == true );
    long currentTime = System.currentTimeMillis();
    m_timeSinceLastSleep = (int) (currentTime - m_lastSleepTime);

    // Update data used for average sleep time calculation
    m_lastRuntimes[ m_runtimeToWriteToIndex ] = m_timeSinceLastSleep;
    m_runtimeToWriteToIndex = ( m_runtimeToWriteToIndex + 1 ) % AVERAGE_POOL;

    // Sleep long enough for the average time since last sleep to stay as close as
    // possible to m_maxAllowedSleepTime
    m_averageSleepTime = calcAverageTimeSinceLastSleep();

    int timeToSleep = (int) (m_maxAllowedSleepTime - m_averageSleepTime);
    if( timeToSleep > 0 ) {
        try {
            Thread.sleep( timeToSleep );
        }
        catch( InterruptedException e ) {

        }
    }

    m_lastSleepTime = currentTime;
}

private int calcAverageTimeSinceLastSleep() {
    int sum_sleep_time = 0;

    for ( int runtime : m_lastRuntimes ) {
        sum_sleep_time += runtime;
    }

    return sum_sleep_time / m_lastRuntimes.length;
}

```

}

# Answer
> 18 votes
You need to **Fix Your Timestep!**

http://gafferongames.com/game-physics/fix-your-timestep/

# Answer
> 5 votes
Instead of sleeping to regulate game speed, use the time elapsed per frame to give everything a consistent speed.

```
myObject.Move(elapsedTime*moveSpeed,0,0);

```

Something to that effect. No matter what speed the processor runs at or the framerate, the object would always move at the same speed. Make sure any movement or rotation that requires a specific speed uses the same idea.

---
Tags: android, timer
---


title: Realistic slow-falling snow algorithm?

text:
# Question
Title: Realistic slow-falling snow algorithm?
Is there a good algorithm that simulates falling snow? I'm particularly interested in snow that falls slowly, so it doesn't quite fall in a straight line but deviates a bit. Maybe even including simulation of flurries (drafts of wind), variable size, etc. Are there any papers or articles on an algorithm that mimics real-life snow movements or simulates it in the context of a game?

I'm particularly interested in a 2D algorithm, but I imagine any algorithm can be taken to 3D easily.

# Answer
> 5 votes
Something like this?

Blurb:

> Realistic-looking rain and snow greatly enhance scenes of outdoor reality, with applications including computer games and motion pictures. We present a novel technique for realistically and efficiently rendering precipitation in scenes with moving camera po- sitions. We map textures onto a double cone, and translate and elongate them using hardware texture transforms.

**Rendering Falling Rain and Snow** \- SIGGRAPH submission of the paper

Actual published paper - **Let It Snow, Let It Snow, Let It Snow (and Rain) - Game Programming Gems 5**

Written by Niniane Wang(*absurdly smart, who gradautes cal tech in CS at 18??!!!@!@!$*) and Bretton Wade

---
Tags: algorithm, physics
---


# Question
Title: When should design give way to marketing and vice versa?
When should a Designer draw the line in design decisions when marketing does step in?

Where should the bounds be set?

(For most part I know this is might mostly be situational. Gut feel like thing. But would like to get some inputs on this as well)

# Answer
This is very contextual, and there is no one right answer.

Upfront it's important to recognize marketing and design have different and sometimes opposing roles. Designers attempt to make a coherent, fun game experience. Marketing attempt to make money off it. Both are crucial to the success of a game and the survival of the folk making it.

Before you fight with marketing folk, it helps to try understand them and try and speak their lingo. Giving clear, rational responses to their concerns and bringing up your concerns in their language can go a long way towards resolving conflicts.

Marketing is typically driven by the current market realities as determined by empirical data. The degree to which they look at new trends in the market may vary depending on who is doing the marketing, but typically marketing folk won't take well to unproved ideas or designs.

When drawing a line in the sand it may be helpful to consider a number of factors:

1\] Can you compete in the market with your current design? If competitor X completely outclasses your game, a marketing driven design changes may actually be helpful!

2\] At what stage are you in development? :

* Early stage: design changes now can make your game more appropriate for your target demographic, make you better able to compete, but can also homogenize your design to such a degree that your game is not differentiated in the market place. The concept of differentiation is one that marketing folk understand so try to explain your ideas in terms of differentiation.
* Mid-\>Late stage: design changes at this stage can yield wasted work (very quantifiable, just take axed features and multiply by number of devs it took and how much it cost the company for each dev). Moreover, design changes at this stage could push the schedule out, forcing you to miss important marketing dates.

3\] Is the marketing requested change reasonable? Is it trivial or is it core to the whole game design thus far? If it's trivial, sometimes it's easier to bite the bullet. If you're dealing with unreasonable requests of a core nature, you're probably out of luck and no attempt to rationalize things is going to get you very far. In these cases, unless you're the boss it's probably best not to expend the effort fighting it - just try to protect yourself against future blame by making it clear this was not your design change.

Given these factors then, the question then becomes: how do I shield myself from the risk of design changes? Almost certainly it involves a whole bunch of cheap upfront work, normally called preproduction, during which a game is prototyped, and it's fun is proved, and market viability is tested *before* it is actually built.

Just to note that despite what I've said here, there are often strict communications channels in game organizations. Designers typically communicate through their leads, as do coders and artists. Also design changes driven by marketing or by design, should strictly go through coder leads, art leads and marketing before they're set in stone. this is important so that all the major stakeholders can review the viability of the design and how it impacts their schedule.
> 3 votes

---
Tags: game-design, marketing, job-hierarchy
---


# Question
Title: Are there any good tools or suites out there that help with building AI/Robots for browser based games?
I've found some HTML/Canvas/Javascript browser based games that I don't particularly enjoy playing, but which I think would be fun to write robots for. Are there any tools out there which help remove some of the tedium of the work, and get me closer to writing the actual AI portion of the code?

# Answer
So it looks like what the author of the question wants is basically to hack server calls of web based games?

If that's the case I'm adding another answer which is very different from my first answer

## Fiddler

**Fiddler** is a web debugging proxy. It will let you setup a proxy between you(*the client*) and the server.
The proxy has a ton of configurations will will let you save sessions, replay sessions, pause AJAX requests and edit them on the fly.

It can log all AJAX requests so you could build a HTTP robot which could simulate playing the game.

Fiddler was originally created by a PM at Microsoft for debugging websites, and web interactions of applications.
> 1 votes

# Answer
Why bother writing the boring interface code and use AI Api's directly? Program the AI not the interaction with the game itself.

## Starcraft 1

The very popular BroodWars API allows for commanding all the units to do anything a real player could. You can even battle against other players or AI's with your AI

http://code.google.com/p/bwapi/

## Super Mario

This API allows for you to control Mario! It was a contest for the best level generation and fastest level completion AI. (A\* actually won)

http://www.marioai.org/

## Galcon

There is currently a contest for the best Galcon AI, a Google AI Challenge. Of course Galcon API is provided.

http://ai-contest.com/
> 1 votes

---
Tags: ai, web, client
---


# Question
Title: Taking Physics into account for AI Planning
What I've seen in most **Game Engines** and game engine design is that the **Physics Engine** is the **be all end all system**.

Basically, **AI** for example may want to travel to some position, but it simply sends that request (*velocity, direction*) to the **Physics Engine**. If the AI really gets to that position is up to the will of the Physics Engine.

Is there some Design or Physics Engine which will let you plan out how Physics will react? Before it will actually occur?

Take for example that you can do Motion Planning by the AI to nearly eliminate foot sliding.

*images from aigamedev.com -* **Motion Planning for Fun and Profit!**

# Answer
Hmm, that's not my experience - the physics system may well implement things at the lowest level but it's equally likely that player motion is done without much recourse to the physics system at all. Either way, the job of the AI system is usually to generate a path such that the act of locomotion is simplified, eg. along a sequence of straight unblocked paths. This means the physics of the player's motion becomes mostly irrelevant for the purposes of making the path. However, if the low level physics or collision handling detects a new obstacle during execution of that plan, it can report that back to the AI system and re-plan the route. (Preferably after trying intermediate recovery strategies, eg. steering around the obstacle.)

To actually plan for the exact detail of what the physics will do would require immense CPU time as you'd really need to simulate every nearby object in the system for many timesteps to predict what would happen. It *may* actually be practical to do this to extrapolate your current position to anticipate any problems, but it's not going to be practical to do this for every node of the planning tree.

If on the other hand by 'physics' you are really just meaning the acceleration and velocity of the player, then that is trivially calculable in the original pathfinding plan - but then that doesn't take into account the other actors in the world, who are ultimately the only ones likely to impede an existing plan.
> 2 votes

---
Tags: game-design, physics, ai, planning
---


# Question
Title: How to "repeat" a sprite in the gameworld in a random fashion?
I have a platform flash game which includes a level with just two backgrounds which are flipped side by side so that a looping background effect is created. In this I have to include Obstacles. Basically, when I designed the level, that was neat and good. But now I want to make the obstacles come randomly . Another factor is that since the player character in the platformer always keeps on running, if two obstacles come almost close together, it results in an impossible condition to win the game. So i need to avoid that too, without losing the factor of making the player think that the game is random.

# Answer
> 4 votes
What you are basically talking about is Procedural Content Generation. Roughly, you want to use a randomizing algorithm to make a "map" of upcoming content, and then run a check over that map to look for problems like "This gap is too small and makes the level impossible."

I found, of all things, a wiki dedicated to the topic, which also has some code samples: http://pcg.wikidot.com/

You might also check out the roguelike development resources here: http://roguebasin.roguelikedevelopment.org/index.php?title=Roguelike\_Dev\_FAQ

The techniques applied to roguelikes can usually apply to most 2D games.

# Answer
> 3 votes
Here is one way to do it.

**Set a minimum distance that things can spawn at, so things can always be winnable, but make this distance almost impossible to win.**

**Have a difficulty variable that that starts out high for easy, and lowers as it gets harder.**

**Set the position of the next object at the minimum distance + difficulty variable + a small random number.**

This will ensure that stuff spawns randomly, but it just has some rules to follow before it spawns.

There are other more complex way to do it, but for what you are describing I think this is the best.

---
Tags: game-design, actionscript-3, logic, platformer
---


# Question
Title: How to smoothly let an object move along a curved line
I'm wondering how to move objects, with rotation taken into account, to follow a curved line

see: http://www.youtube.com/watch?v=iPpO24FeAX4 for an example

In particular I wonder:

1. how to store the points, how many points to store for a smooth line like that
2. how to interpolate the curves
3. how to interpolate between the object and the first "waypoint" along the line

# Answer
> 7 votes
Look into Bezier curves and Hermite curves, both of which you can compose into splines. Both usually take the form of a parametric equation where you input a time `t` between 0 and 1; time 0 would be the start of the spline, time 1 would be the end.

Rotation is a matter of calculating the tangent to the curve.

4 control points for the first segment followed by 3 additional points per additional segment is common for this kind of spline, although some types may want more points.

Note that with parametric splines you often may have difficulty computing position on the spline as a function of distance instead of time, so if you want to answer the question "I've moved X distance, where would I be along the curve" you're in for some integrating. Similarly, instantaneous velocity may vary depending on the density and position of control points.

# Answer
> 2 votes
I've implemented this in my Line-Drawing Game Starterkit and avoided using the over-engineered solutions. You probably need a point every 10 pixels distance, so you can get a decently smooth line without using too much memory or draw calls. Then it's a simple matter of moving the objects from point A to B. To make them appear as traveling smoothly along the path, you simply rotate them to the direction of motion. This is done over time and not instantly, so you get smooth, following a curved line movement without the need to used Bezier curves or similar.

The points are stored in a simple array, inside a Path class that also knows how to draw the path using OpenGL. You can have any number of path points but I would limit them to 50 to 300 depending on the device and required smoothness.

To interpolate the line you should look up the McMaster's Slide Averaging Algorithm (theory).

The object is moving to the first point only when the user has drawn at least two points, to avoid the object spinning wildly. Once moving towards the first point its the same code as moving to the second, third, fourth and so on.

# Answer
> -1 votes
The answer to all 3 is usually splines or some other similar curve.

---
Tags: mathematics
---


# Question
Title: How can I write a Save/Load system for my game?
I'm trying to figure out a way to write a save/load system for my game in C++. As of right now, I'm doing it all using binary flags. Anyone got a clue on how to do it another way? I don't mind using binary, but I want to know my options. I also want something in which it would be easy to check on the status of just one event being complete or incomplete in order to decide certain things (a lot of the items system in this game is dependent on what the player has or has not done throughout the course of the game).

# Answer
> 5 votes
Serialization would be the way to go, and as for the status-checking, you could have logic in the deserializtion method to do so.

# Answer
> 6 votes
I've studied the DOOM source code a bit. I'll tell you how it's done in there.

D\_DoomMain contains all of the open/save/load functions, as well as a slew of other things. As it says at the beginning of the file,

```
// DESCRIPTION:
//      DOOM main program (D_DoomMain) and game loop (D_DoomLoop),
//      plus functions to determine game mode (shareware, registered),
//      parse command line parameters, configure game parameters (turbo),
//      and call the startup functions.

```

Basically, the whole file is full of `M_CheckParm`s from start to finish. That's what the D\_DoomLoop consists of. It's one massive loop (something like 1000-2000 lines long).

Since your question is 'How can I write?' I'm just going to paste some bits of code that refer to gamesaves, from D\_DoomMain:

here are the statements where that stuff gets used, at the very end of the loop.

```
   p = M_CheckParm ("-loadgame");
   if (p && p < myargc-1)
   {
       if (M_CheckParm("-cdrom"))
           sprintf(file, "c:\\doomdata\\"SAVEGAMENAME"%c.dsg",myargv[p+1][0]);
       else
           sprintf(file, SAVEGAMENAME"%c.dsg",myargv[p+1][0]);
       G_LoadGame (file);
   }

   if ( gameaction != ga_loadgame )
   {
       if (autostart || netgame)
           G_InitNew (startskill, startepisode, startmap);
       else
           D_StartTitle ();                // start up intro loop

   }

   D_DoomLoop ();  // never returns

```

Here's the function that accesses the strings, which you find scattered throughout the code:

```
void M_ReadSaveStrings(void)
{
   int             handle;
   int             count;
   int             i;
   char    name[256];

   for (i = 0;i < load_end;i++)
   {
       if (M_CheckParm("-cdrom"))
           sprintf(name,"c:\\doomdata\\"SAVEGAMENAME"%d.dsg",i);
       else
           sprintf(name,SAVEGAMENAME"%d.dsg",i);

       handle = open (name, O_RDONLY | 0, 0666);
       if (handle == -1)
       {
           strcpy(&savegamestrings[i][0],EMPTYSTRING);
           LoadMenu[i].status = 0;
           continue;
       }
       count = read (handle, &savegamestrings[i], SAVESTRINGSIZE);
       close (handle);
       LoadMenu[i].status = 1;
   }
}

```

You've also got a file called p\_savegame.c with stuff that will save all of the user-associated data (which weapons you've got, where you are in which level, etc).

And finally you've got the file which loads savegame data into a game scenario, arguably the most complex of all, because it also loads everything else. That one's called p\_setup.c, and is located in the same directory.

It worked well for me to `cat` these all into a text buffer and `pipe` that text to `sendmail` to my own email address. That way I can read through it at odd moments of the day, and use 'find' when I want to look for stuff like 'how does DOOM load a game'. The code is well-commented.

# Answer
> 3 votes
You could serialize the class or the data to a flat file and then read it back when you load.

# Answer
> -1 votes
I +1:ed the suggestion to use XML/JSON to structure the save games. This way you are very prepared to make the saves "cloud" based. Or at least, you'll have a structure you could use for future projects which might involve the web. As long as the files aren't stored in a way that's too easy to read they should give you loads of benefits. Like metrics! Hooray

---
Tags: c++, loading
---


# Question
Title: Interesting and simple missions for text-based game
Can you give me an idea for a simple and interesting mission for online text-based game that doesn't require much reading? Or maybe link to a website with a list with missions?

I love programming, but I hate when it comes to create things like this, because I am not creative at all.

Thank you.

# Answer
Heres another good list:

http://www.io.com/~sjohn/plots.htm

Also I second what the first poster said. If you like problem solving and programming, you ARE creative.
> 4 votes

# Answer
Might be worth having a read through these common RPG scenarios. Hard to say if they'll apply directly to your game without knowing what you're doing but they should be applicable to any genre really without too much imagination.

(And if you love programming you're at least a little bit creative!)
> 2 votes

# Answer
To get you started without reading too much:

Not so distant future. Person waking up without memories. World is controlled by two huge rivalling corporations. The person (our protagonist) needs to do missions and get too deeply involved with both of the corporations to be able to discover his/her past and why he/she has so many enemies.

Then continue to steal stuff from the matrix, bourne, johnny mnemonic etc and then at least I'll be interested in the story :)
> 2 votes

# Answer
How about exploring a space craft adrift in space? You could start with 15 rooms or areas to explore and throw in puzzles. Maybe the onboard computer has gained self awareness and actively tries to trip up the player to protect itself (remember HAL from 2001: A Space Odyssey?) Throw in some rogue androids, maybe some mercenaries are in the middle of ransacking the craft and the player now has to evade them. There's a bunch of "surprises" you can throw in to this setting and it can grow if you want to expand it. The player used a pod to escape from the mercenaries and has now landed on a planet. Now we enter another adventure. The possibilities are endless!

I'm inspired to create my own adventure game now! I haven't made one of these since I had my Atari 800 as a boy (I'm 40.) Anyway, good luck and have fun!
> 2 votes

---
Tags: mission-design
---


# Question
Title: Huge slowdown when running Lua as statically linked lib versus stand alone interpreter
I'm developing some algorithms in Lua which are run mostly in Lua (few calls to C++) and I'm noticing a huge slowdown when I'm running them from my app rather than the default Lua interpreter. The script returns in about 11 seconds with the interpreter, and about 5+ *minutes* with my program.

I don't think it is a problem with calling the C++ function, overruling that function with an empty function in the script has no noticeable effect for time.

Both Lua and the program are compiled with Visual Studio 2010 (I created a new solution for Lua, with projects for both the interpreter and static library)

I've run a profiler on the code (the Very Sleepy profiler, can't get a Lua profiler working but haven't tried to much) and found that in my application around 50% of the time is spend on malloc.. and 40% on free, both called from the Lua garbage collector (tried disabling that to check, but that crashes with using to much memory (understandably), the Lua interpreter peeks at about 4mb ram usage).

I'm new at Lua, so its very possible I've done something wrong somewhere, anyone got a few hints to try?

# Answer
> 4 votes
As you say, Lua does memory allocations like crazy by default. You should consider writing a custom allocator that has better knowledge of the allocation patterns typically used by your Lua programs, or plugging in something like tcmalloc for better allocation performance all around.

---
Tags: c++, lua
---


# Question
Title: How can I define items in my RPG like Java game?
I am casually working on an RPG type game in Java but I am having trouble figuring out how I can have items that can do many different things without creating a different class for every item.

As an example, how would I create an Axe that could chop trees and attack monsters?

If I extend either the chopping or the weapon class then I can't extend the other class.

If I have chopping and weapon be an interface then I will have a lot of duplicated code when a dagger can also attack monsters and a different axe can cut trees.

I am hoping there is a way to have a single Item class and load the items and their respective abilities from a file. If that is possible how can it be done? If it isn't then what is the best way to have items in a game?

# Answer
Gregory Weir's answer is my favorite for how to structure the item instances in order to perform multiple roles.

To load from a file:

**First, use YAML.** YAML is a featureful data description language; it can be parsed relatively quickly, read and edited by humans, supports binary data, and libraries exist for most programming languages, including Java. This solves the "how do I get data from files into objects?"

**Second, use the flyweight pattern.** Most of the data you read from those files is static. It's not going to change per instance ("axe does 1d10 base damage and breaks wood but not stone" - that's true of all five axes a player has). What you actually read from the YAML files are these platonic definition, and your individual item instances have unowned (and constant) references to these, along with per-instance data like "How many swings before I break?", "Did the player give me a custom name?", and so on.

By sharing the cross-instance data in a single object, you preserve lots of memory, and make it easy to update items without persisted game state (save games or player database).

So your class structure looks something like:

* class Item - One instance per item
    + Owns-a Weapon instance
    + Owns-a Tool instance
    + Has-a custom name, etc.
* class Weapon - (Up to) one instance per item
    + Is-a ItemComponent
    + Refers-to WeaponDef
    + Has-a bonus enchantment level, etc.
* class Tool - (Up to) one instance per item
    + Is-a ItemComponent
    + Refers-to ToolDef
    + Has-a durability, etc.
* class WeaponDef - One instance per kind of weapon
    + Read from a file, fields should be constant.
    + Has-a base damage amount, 1 or 2 hands, etc.
* class ToolDef - One instance per kind of tool
    + Read from a file, fields should be constant.
    + Has-a base durability, materials it can break, etc.
> 15 votes

# Answer
The Component (not Composite) design pattern is great for this purpose: http://gameprogrammingpatterns.com/component.html

Basically, an Axe would be an instance of the Item class that contained a WeaponComponent and a ToolComponent (maybe). To test if something can be used as a weapon, check if it has a WeaponComponent attached, and then talk to that WeaponComponent instance to get the item's weapon info.

Loading from a file is a separate exercise, of course.
> 18 votes

---
Tags: java
---


# Question
Title: Style/technique to focus on for creating visual art assets efficiently
I'm mostly a programmer, but I'd like to be able to do competent work on other parts of games I make when working on solo projects.

What I'm specifically asking here is what sort of techniques or styles for visual asset creation should I study and use to be able to work with the most efficiency? Basically, what would end up being the least work as a whole, taking into account possible changes late on in the development, reuse of assets created for other projects, etc.

What I mean by "technique or style" here is things like vector art, digital painting, pixel art, poly modeling, sculpting, etc.

I'm mostly interested in comparisons of the various techniques as a whole. It's hard to get a good big picture view of the situation not having a lot of experience with doing real work with each technique. Also, obviously if you're making a 3D game you'll need to make 3D assets, but for now, let's talk about techniques for creating assets for a 2D game, where the assets could be either 2D or 3D.

# Answer
So many indies go for the lo-fi pixel art look. While this is great for rapid prototyping and time-limited gamedev competitions, I think it's becoming an overused style, and you'll struggle to make a real stand-out game, unless the gameplay is something truly special.

Digital painting is currently somewhat underused in 2D games, and there's a lot of potential for interesting (and hi-def) 2D game backgrounds if you abandon tilemaps and go for the Braid/Aquaria approach (splatting arbitrary alpha-blended shapes around your level)

But animation is challenging - unless you can come up with a way to (pre-)render 3D characters in a style that fits the backgrounds?

Good quality 'traditional 3D' is always going to be extremely time-consuming, especially when you consider things like animation, or building and UV-mapping large scenes. You won't be able to come close to competing with the quality/scale of big commercail games. However, there are less traditional 3D styles that you could explore - maybe non-photorealistic styles (e.g. Love), or untextured 3D (e.g. Virtua Racing), an interesting style which is currently underused, and could still look impressive with good lighting/post effects/antialiasing.

This is a must-read for anyone starting out on a 2D game project:

http://www.davidhellman.net/blog/the-art-of-braid-index/
> 5 votes

# Answer
Here are some points I came up with myself:

**Digital painting:**

* Flexible for lots of visual styles
* Lots of resources available for learning
* Scales decently

**Vector art:**

* Easy to edit
* Scales very well
* Relatively easy to animate

**Pixel art:**

* Classic "game look"
* Relatively easy to work with at low resolutions
* Very very laborious at higher resolutions
* Does not scale at all. Better have that sprite size locked up by the time you draw it.

**3D in general:**

* More work than 2D
* After the model is created and rigged, making animations is easy in comparison. No redrawing.

**Poly modeling:**

* Specifically suited for angular geometric looking objects

**Sculpting:**

* Easier to create complex models than with poly modeling
* Specifically well suited for smooth organic looking things
> 3 votes

# Answer
Some suggestions:

You could try with minimalistic 2D vector graphics. Look to games like flow, eufloria and limbo for inspiration.

If you want to go for a hand-drawn look you can manage with minimalistic vector 2d + a hand-draw-look-shader which could apply a noise function to all your lines.

I prefer making vector graphics over painting due to the the ability to rescale as I see fit, and the ability to reuse graphics components between sprites.
> 1 votes

# Answer
I feel that small development teams do best when they go by this rule:

1. **Take a look at what all the big studios are doing.**
2. **Head in exactly the opposite direction.**

If EA, Sony, and Microsoft are all going for the hyper-realistic aesthetic, how about something hyper-unrealistic? Indies have, lately, had a lot of success with pixel art (though the resurgence in that style means that (perhaps) that's something to steer clear of as well!). Since you're a programmer, why not leverage that to create something unique? A corrolary to the above rules:

* **If everyone's using one tool, consider using or building a different one.**

So, for aesthetic, we're in the process of developing a surreal, geometric-looking aesthetic for our upcoming title. And since, by and large, we're not artists, the approach is to do this procedurally, so we've been experimenting with math. For instance, we've built a node-based utility so that non-artists can create interesting 3d models.

You've covered a good range of styles, from vector art to pixel art. As you're a programmer first, you might look into creating your own style programmatically. Some examples of this:

* **Structure Synth** uses context free grammar systems to generate visuals.
* **Genetica** uses a graph interface to build textures.
* **Eskil Steenberg** uses really simple 3D models and applies a full-screen shader for a painterly effect for a unique aesthetic in Love.

There's a lot of great stuff yet to be discovered, and I think programmers (or, better yet, a programmer and someone with an artistic eye to consult) are in a great place to find/create/develop it.
> 1 votes

# Answer
Not really an answer, so much as an extended note :

Digital painting requires a lot of learning time to get anything that looks hi-def. If you're already a competent drawer or painting in traditional mediums then it can be quite rewarding, but if you are looking for the easiest way for you to create art assets for yourself, it might not be the best way to go. Something like vectors or pixel art is probably best if you can't put in the needed time to really learn digital painting, since they are more easily manipulated and edited. If you make a mistake on a painting, you need to re-paint it, whereas with vector art you can just edit the shape/line to fix it.
> 1 votes

---
Tags: graphics, 2d, assets, art
---


# Question
Title: Should I go to a University or Trade school to be a Game artist?
Im a senior this year and I'm seriously looking at colleges that can help me get into the game in the Game industry. I've been told countless times it's better if I go to a University(Usc, Becker college, etc) than go to somewhere like Digipen or Full Sail. I'm just really confused about how I should tackle this path. I'd appreciate some help and advice please?

# Answer
If your aim is to become an artist (as opposed to a designer or programmer), I would say a full on fine art degree will be the most useful. The game specific skills, like 3d modeling or texture painting can all be done on your own. There are many websites that you can post your work on to get criticism and pointers from industry artists (forums.cgsociety.org, www.Game-Artist.net, www.polycount.com). The REAL value of the university will be the basics of art: colour theory, composition, form, etc.

There are very few, if any, institutions which can give you a full on, useful, game art education and positions will be quite competitive. I bet you could learn the same things, if not more, on your own with the internet and some hard work in the same amount of time. I would recommend you check out those websites before you make any sort of decision. Many of the regulars have done some sort of formal education, and they are much more qualified to speak on the matter than I am.
> 6 votes

# Answer
The question you need to ask first is "What do I want to do?" From what I understand, if you want to, say, make 3D models for games, or design AAA-style shooty-boom games, trade schools will probably serve you well. However, I remember a story Anna Anthropy told of quitting her tradeschool after they were assigned to make a 3D model of a gun. It had to be a weapon. Trade schools may have narrow views of the nature of games.

If you want to be a programmer and work on the code side, I'd say go for a proper Computer Science (or Software Engineering) degree at a "real university." Note that I'm biased, as I have a BS in CS from an engineering college. The general-purpose knowledge and versatile coding know-how you'll get will be invaluable, and give you something to fall back on if gaming jobs are thin.

If you want to design artsy games or really stretch the nature of the form, you might want to check out a school that's got a good New Media or Interactive Media program; Georgia Tech comes to mind, but there are tons of others. Note that this usually comes at games from a humanities perspective, so if you like English better than Math or Art, this is probably the approach for you.

So, in short, what subject most appeals to you?

* Art, Architecture, Shop: Trade school.
* Math, Science: CS or SE program at a university.
* English, History: Humanities-focused program (harder to find).

I can't speak on music, as it's my area of least expertise. I'd assume that a general-purpose composition program would be best, though.
> 3 votes

# Answer
If your goal is getting into the game industry as an artist, your portfolio is what is going to sell you, rather than your degree. I went to a university and then switched to a technical institute, but I would never have gotten a job based solely on the skills I learned there. The trick is to constantly supplement your education by educating yourself. If you have a degree in Game Art and Design but your portfolio is a mess, no one is going to hire you. If your portfolio is amazing but the school you went to isn't as well known, it's not going to be a big deal. They will hire you for your work.

As for supplementing your education, there are a lot of good ways to do this.

I'm a 2d artist, but there are similar methods for 3d art too. A good place to start focusing on specifics would be sites like gnomon, where you can get videos specified for very specific aspects in art, and ones that are more general. (Designing a weapon, or Animal Anatomy, for example.) They also have program-specific tutorials, like using Z-brush. (Since I just started here, I can't post hyperlinks more than once, so you will have to google these places to find them.)

Conceptart.org also has tutorial videos, and classes, and they also have an online school. It's pretty new though, so I can't guarantee quality, but the forums have been around forever and always have inspiration kicking around. I got my first game job by doing a contest on that site and having my entry seen by the Art Director, so doing contests I recommend for sure! (The one I did was the Character of the Week).

Art forums in general are a good way to guage how ready you are, get feedback, and learn new things. Other than CA, I also recommend CGHub, CGSociety, and Apedogs (smaller but awesome.) CG society also has some workshops.

Practice Practice Practice constantly. Work at your craft. Get feedback, get your work out there, get noticed.

Hope this helps. :\]
> 2 votes

# Answer
I've spoken with a couple of artists in the industry on this very topic, and the general consensus has been that some of the best game artists are those that have a very deep traditional art education that they either learned through school or on their own. For example, a strong traditional art background can have a very significant impact an artist's textures.

Unfortunately, there is no easy answer to your question, as there are great traditional and trade institutions you can learn from. What I would recommend is looking into the schools individually and deciding whether or not they are a good match for you. Below are a couple of things you should look for in the school you plan on attending:

* Mixture of traditional 2d & 3d art courses, in addition to game art specific curriculum
* Exposure to different aspects of game art (prop modeling vs character modeling, organic modeling, texturing, rigging, special effects, animation, etc.)
* Exposure to different tools
* Exposure to different engines (Unreal/UDK, Source, Crytek, etc.)

Like many others, I would highly recommend supplementing your education by spending time on popular game art websites. I would even recommend asking your question to people there, to get their input. Lots of industry professionals hang out on those sites and offer free critiques and advice. It'd be a waste not to use such a valuable resource!
> 2 votes

# Answer
You can kill two birds in one stone.

USC Interactive Media Division or USC Game Development

The Princeton Review rated USC as the number 1 Game Design school, Digipen rated 2nd.

http://www.princetonreview.com/top-eight-game-design-programs.aspx
> 1 votes

---
Tags: art, education
---


# Question
Title: Mixing sprite drawing with 3D primitive drawing in XNA?
In my game, I have a base Note class, and various subclasses of Note. In addition, I have a NoteCollection class which contains a collection of these Note objects and draws them to the screen. Normally, I'd just do something like this in NoteCollection:

```
public override Draw(GameTime gametime) {
    ...
    spriteBatch.Begin(...);
    foreach(Note n in notes)
        n.Draw(gameTime);
    spriteBatch.End();
    ...
}

```

However, some of these Note subclasses also need to draw 3D primitives in their Draw() methods. I imagine setting vertex buffers in the middle of a SpriteBatch Begin()/End() block isn't a good idea (I've tried it, anyways). What would be nice would be a SpriteBatch.Pause() method that would save the state of the SpriteBatch, and then you could resume drawing your sprites with, say, a SpriteBatch.Resume(). But alas, there's no much methods.

In short, is there any way to go about this? I'd rather not call SpriteBatch.End()/Begin() from each Note.Draw(), as it'd be really slow and I wouldn't necessarily know what parameters the original outside Begin() was called with.

**EDIT**: Even though I'm using 3D primitives, my game is still in 2D. All of the Z-coordinates of my vertices are 0.

# Answer
What I would do is create 2 draw lists (`List<IDrawable>` or better yet, create your own `IDraw` interface which includes a `CullTest(Camera camera)` method and a `BoundingBox` parameter). Then add all the drawprimitives notes into one drawlist and the spritebatch calls in the other list. If you are mixing drawprimitives and spritebatch draw calls inside the note.Draw() methods you should break it up into 2 calls (note.DrawSpriteBatch() and note.DrawPrimitives()). Then I would depth sort the drawprimitives list from closest to furthest away from the camera. After that you can draw both lists. This way you are using only one spritebatch. This is much cheaper than creating a new spritebatch for every node since each spritebatch.Start() sets a whole slew of renderstates. Also, you are reducing the drawprimitives overdraw from drawing distant occluded objects before the objects in front of them (why make the pixel shader shade pixels which are not visible?).

If you do roll your own `IDraw` interface you can do something like this:

```
public interface IDraw : ICullable, IEntity
{
    void DrawPrimitives(DrawState state);
    void DrawSpriteBatch(DrawState state);
}

public interface IEntity:
{
    BoundingBox AABB { get; }
    Vector3 position { get; set; }
    ...
}

public interface ICullable
{
    bool CullTest(ICamera camera);
}

//this is useful for being able to switch camera types without
//changing any code which relies on the camera class
public interface ICamera
{
    BoundingFrustum boundingfrustum { get; }
    //and anything else common between your camera classes:
    //fov, aspect, far, near, position, target...
}

public class DrawState
{
    //Elapsed time, Current camera, Current shader
    //anything else that you are sharing between draw calls
}

```
> 2 votes

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


# Question
Title: Do online colleges give you the same experience needed for programming or is it better to go on campus?
I don't know whether I should go online for my game programming degree or to be on campus. The closest college that offers game programming degree is in a different state 6 hours away. Any advice?

# Answer
> 9 votes
Attending college not only builds your skills as a programmer, it gives you an opportunity to build your social, communication and teamwork skills. Just the social aspect of being with other people is a necessary experience for working in teams inside a company.

Beware of online school scams, however (same goes for some colleges, but there are alot of online ones which are just scams). They'll take your money, give you a pass and hand you a diploma, but that diploma won't be recognized by any company once you graduate. Be careful!

# Answer
> 11 votes
The online college will deprive you of the opportunity to build relationships with professors and industry professionals. While they try to mimic the classroom experience through webcams and chat rooms, those will only take you so far. You will likely not get to know your peers as well as you would if you had to endure painful all nighters in a lab with them. These relationships may lead to job opportunities in the future as well as potential partnerships.

# Answer
> 3 votes
In my experience, college classes are nowhere near as helpful as actually meeting other students. In most of the classes I've taken, the teachers teach everything extremely slowly. While your teachers are busy telling you how multi-threading is "too hard", you can make friends with other students and learn from them. Most of what I've learned in my classes is a result of me and friends doing homework in strange ways to entertain ourselves. I see that as a huge advantage over online classes.

I would say it would be better to just make friends with a couple programmers and skip college entirely, but what you really want are other people at a similar level as you, and an environment that will get you in the mood to do programming.

# Answer
> 1 votes
As with any college or university program (online or otherwise), you're going to be spending a shockingly large amount of money -- probably more than your first car, and at least with the car you probably took a test drive and kicked the tires. So be sure of what you're getting!

Unfortunately there is no single concept of "online class," it varies by school. Some schools consider "online" to equal "self-taught": as in, you get the textbook, teach yourself, hand in the exercises, and some remote instructor who is just a glorified grader gives you a score. Some schools include more content, everything from text to podcasts to video lectures, possibly even "live" remote lectures with courseware that simulates you being in a physical classroom. Some schools expect you to do most of the work on your own, but the instructor is expected to be there as a resource for you if you need help or get stuck.

If there is a specific school you're considering, find out more about their program. Find out exactly what is involved, what a typical class looks like, what kind of level of support you can expect, what your rights and responsibilities as a student are. If they can't tell you or they refuse to show you... run away!

Caveat emptor.

# Answer
> 0 votes
Do online colleges offer a similar curriculum as traditional colleges? Probably

Do online colleges offer a similar experience as traditional colleges? Probably not.

In my experience, a lot of online courses will try to mimic the classroom experience through software like digital whiteboards, video conferencing, etc., but it's never quite the same as being in a classroom. To me, online courses fell more rigid, professors fell more distant, and classmates seem less like classmates and more like passers-by. Not to mention the countless social opportunities and interactions you'll miss out on.

Given the choice, I would definitely choose to pursue a degree on campus, unless there is some particular reason you need/want to stay in your area.

---
Tags: education
---


# Question
Title: How can Apple know how an iOS game is made?
As you all know, Apple recently change the terms for app developers using 3rd dev tools.

I'm wondering how could Apple know whether an app is made with a specific technology like Flash or Unity or GameSalad or any other engines out there?

# Answer
A simple (but not foolproof) way might be to use the `strings` utility to examine the binary for known strings: version stamps, error messages, etc.

If symbols aren't entirely stripped (not likely in a submitted build) you can use something like `nm` or `objdump` or the like to see the names of symbols. Some symbol names may be a good indication that a particular tool, compiler, library, or framework was used.

You could look for machine code or data headers that are known to correspond to a specific version of a compiler, library, or tool.

You could suspend the app and scan its memory region, potentially, to do similar checks, looking for known patterns (akin to the way a virus scanner might work).

Of course there are a number of ways to attempt to guard an app against such checks. For example, you could compress and/or encrypt the majority of the executable and/or data. But if your app can decrypt it, likely so can an investigator...

I'd imagine they don't bother investigating unless they have reason to. They might potentially automate some of these checks if they really cared, but these checks might only flag the obvious uses of the tech...
> 7 votes

---
Tags: flash, iphone, unity
---


# Question
Title: How to simply print (write) text on a Surface in SDL.NET?
as i told in previous question, i'm using SDL.NET (wrapper in C# of SDL). Unfortunately the API website is down so i'm trying to learn it by myself. I would like simply to print text on my screen / surface ... i don't know how to do!

My goal is to print variable status/values, to "debug" directly on the run and on the screen (in the lower corner for example). Can somebody help me ?

Thank you

# Answer
> 1 votes
Ok, i found the solution on an example project:

```
SdlDotNet.Graphics.Font myfont = new SdlDotNet.Graphics.Font("arial.ttf",12);
Point dest = new Point(600,400);
surfVar = myfont.Render("Values: ",Color.White);
Video.Screen.Blit(surfVar,dest);

```

# Answer
> 0 votes
http://forums.tigsource.com/index.php?topic=8531.0 has an example of using Graphics.Font to render text to a surface (which is a wrapper for SDL\_ttf I think). Basically you load a TTF font into a Font object and then use .Render on that to make a surface from a given string.

---
Tags: sdl
---


# Question
Title: Register Game Object Components in Game Subsystems? (Component-based Game Object design)
I'm creating a component-based game object system. Some tips:

1. `GameObject` is simply a list of `Components`.
2. There are `GameSubsystems`. For example, rendering, physics etc. Each `GameSubsystem` contains pointers to some of `Components`. `GameSubsystem` is a very powerful and flexible abstraction: it represents any slice (or aspect) of the game world.

There is a need in a mechanism of registering `Components` in `GameSubsystems` (when `GameObject` is created and composed). There are **4 approaches**:

---

* 1: Chain of responsibility pattern. Every `Component` is offered to every `GameSubsystem`. `GameSubsystem` makes a decision which `Components` to register (and how to organize them). For example, GameSubsystemRender can register Renderable Components.

pro. `Components` know nothing about how they are used. Low coupling. **A.** We can add new `GameSubsystem`. For example, let's add GameSubsystemTitles that registers all ComponentTitle and guarantees that every title is unique and provides interface to quering objects by title. Of course, ComponentTitle should not be rewrited or inherited in this case. **B.** We can reorganize existing `GameSubsystems`. For example, GameSubsystemAudio, GameSubsystemRender, GameSubsystemParticleEmmiter can be merged into GameSubsystemSpatial (to place all audio, emmiter, render `Components` in the same hierarchy and use parent-relative transforms).

con. Every-to-every check. Very innefficient.

con. `Subsystems` know about `Components`.

---

* 2: Each `Subsystem` searches for `Components` of specific types.

pro. Better performance than in `Approach 1`.

con. `Subsystems` still know about `Components`.

---

* 3: `Component` registers itself in `GameSubsystem(s)`. We know at compile-time that there is a GameSubsystemRenderer, so let's ComponentImageRender will call something like GameSubsystemRenderer::register(ComponentRenderBase\*).

pro. Performance. No unnecessary checks as in `Approach 1`.

con. `Components` are badly coupled with `GameSubsystems`.

---

* 4: Mediator pattern. `GameState` (that contains `GameSubsystems`) can implement registerComponent(Component\*).

pro. `Components` and `GameSubystems` know nothing about each other.

con. In C++ it would look like ugly and slow typeid-switch.

---

**Questions:** Which approach is better and mostly used in component-based design? What Practice says? Any suggestions about implementation of `Approach 4`?

Thank you.

# Answer
> 3 votes
Door number 3... Component registers itself in GameSubsystem(s)

The component is in place to keep the coupling abstracted from the GameObject itself. Somehow, somewhere something does in fact need to interact with the subsystems and this is the component and its purpose.

The coupling isn't actually a bad thing in this case.

The performance is essentially *required* in this case if you expect to have any complexity in your system, you just can't afford the search style approaches of the other options.

Finally if one subsystem needs to be reactive to another (renderer, physics, audio all need to do stuff when something happens) the components can facilitate this with each other through the game object and keep this particular type of cross system-coupling managable through the components.

---
Tags: c++, architecture, component-based
---


# Question
Title: Local to World coordinates in 2D and back
I'm getting back into hobby game programming after a long 4-year hiatus from college and I find that my understanding of coordinate systems is somewhat lacking.

I'm trying my skills at creating a simple skeletal animation system but I'm having a hard time wrapping my head around converting local coordinates (of say, a joint) to world coordinates, particularly when it comes to rotated sprites.

I'm trying to create a test app in XNA and accomplish this using their built-in matrix class. Can anyone assist me in either linking a resource or helping me understand the operations I'd need to do to convert any point that is Scaled/Rotated/Translated from a local to a world coordinate and back?

# Answer
Here is a good summary of how to go back and forth between world and local coordinates:

www.enchantedage.com/xna-transforms

Here is another good discussion of transforms: How to think about 2D scaling/rotation transformations
> 3 votes

---
Tags: 2d, xna, mathematics, education
---