# Question
Title: Ways to manage changing designer data alongside changing player data
I have an online game where players get to shape the world in some way - eg. Ultima Online's housing, where you get to build your houses directly onto certain parts of the world map. These are changes that should persist over time as part of the persistent world.

At the same time, the design team are adding new content and amending old content to improve and extend the game for new players. They will do this on a development server first during testing and then later have to merge their work in with the players' "work" on the live server.

Assuming we fix the game design issues - eg. players can only build in designated areas, so they never clash geographically with designer edits - **what are good ways to handle the data or arrange the data structures so as to avoid conflicts when new designer data is merged in with new player data?**

Example 1: a player crafts a new type of item, and the game assigns the ID 123456 to it. Instances of that item all refer back to 123456. Now imagine the game designers have a similar system, and a designer creates a new item also numbered 123456. How can this be avoided?

Example 2: someone makes a popular mod that gives all your dragons a French accent. It includes a script with a new object called `assignFrenchAccent` which they use to assign the new voice assets to each dragon object. But you are about to deploy your "Napoleon vs Smaug" DLC which has an object of the same name - how can you do this without a lot of customer service problems?

I've thought of the following strategies:

* You can use 2 separate files/directories/databases, but then your read operations are significantly complicated. "Show All Items" has to perform one read on the designer DB and one read on the player DB (and still has to distinguish between the 2, somehow.)
* You can use 2 different namespaces within one store, eg. using strings as the primary key and prefixing them with "DESIGN:" or "PLAYER:", but creating those namespaces may be non-trivial and dependencies aren't clear. (eg. In an RDBMS you may not be able to efficiently use strings as primary keys. You could use integers and allocate all the primary keys below a certain number, eg 1 million, to be designer data, and everything above that point to be player data. But that info is invisible to the RDBMS and foreign key links will cross the 'divide', meaning all tooling and scripts need to explicitly work around it.)
* You can always work on the same shared database in real-time, but performance may be poor and the risk of damage to player data may be enhanced. It also doesn't extend to games that run on more than 1 server with different world data.
* ...any other ideas?

It occurs to me that although this is primarily an issue for online games, the concepts may apply to modding too, where the community creates mods at the same time that the developers patch their game. Are any strategies used here to reduce the chance of mod breaking when new patches come out?

I've also tagged this as "version control" because on one level that's what this is - 2 branches of data development that need merging. Perhaps some insights might come from that direction.

EDIT - some examples added above to help clarify the problem. I am starting to think the issue is really one of namespacing, which could be implemented in a store via composite keys. That simplifies the merge strategy, at least. But there may be alternatives I'm not seeing.

# Answer
> 2 votes
I think the answers proposing DB solutions are jumping to a specific implementation without understanding the problem. Databases don't make merges easy, they just give you a framework in which to store your data. A conflict is still a conflict even if it's in an DB. And checking out is a poor man's solution to the problem - it will work, but at a crippling cost to your usability.

What you are talking here falls into the distributed development model of problem. The first step I believe is not to think of players and designers as being separate types of content creators. That removes an artificial dimension to your problem that doesn't affect the solution.

Effectively you have your mainline - the canonical, developer approved version. You may (probably) also have other branches - live servers were people are actively developing and sharing mods. Content may be added on any branch. Crucially, your designers are nothing special here - they're just content creators that happen to live in-house (and you can go find them and hit them when they screw up).

Then accepting user generated content is a standard merge problem. You have to either pull their changes back onto the mainline, merge, then push out again, or pull the mainline changes onto their branch and merge (leaving the mainline 'clean' of user generated stuff). As usual, pulling to your branch and fixing there is more friendly than asking other people to pull your changes and then trying to fix it remotely on their end.

Once you're working with that sort of a model, all the normal processes about avoiding merge conflicts apply. Some of the more obvious:

* Encourage liberal use of name-spaces to ring-fence content from a particular author / mod / team.
* Where content needs to interact, establish clear calling / usage conventions, naming conventions, and other loose 'rules' that guide development so that it is easy to merge back. Provide tools that allow content creators to know if they're following those rules, ideally integrated into the content creation itself.
* Provide reporting / analysis tools to spot likely merge failures before they happen. Fixing it post merge is probably very painful. Make it so that a particular bit of content can be checked and given the all clear as merge-ready, so that the merge is painless
* Make your merging / integration robust. Allow easy rollbacks. Do rigorous testing of merged content: if it fails testing, don't merge it! Iterate either their content or yours until the merge will go ahead cleanly.
* Avoid using incremental integer IDs for anything (you don't have a reliable way of doling them out to creators). That only works in a DB because the DB itself is a canonical provider of IDs so you never get duplicates; however it also introduces a single point of failure / load in your system.
* Instead use GUIDs - they cost more to store, but are machine specific and so will not cause collisions. Alternatively use string identifiers, this is much easier to debug / resolve, but more expensive for storage and comparison.

# Answer
> 1 votes
Store everything as an attribute (or decorator) - with mount points. Let's take a house the player has designed as an example:

```
o House: { Type = 105 } // Simple square cottage.
 o Mount point: South Wall:
  o Doodad: Chair { Displacement = 10cm }
   o Mount point: Seat:
    o Doodad: Pot Plant { Displacement = 0cm, Flower = Posies } // Work with me here :)
 o Mount point: North Wall:
  o Doodad: Table { Displacement = 1m }
    o Mount point: Left Edge:
     o Doodad: Food Bowl { Displacement = 20cm, Food = Meatballs}

```

So each entity can have one or more mount points - each mount point can accept zero or more other components. This data would be stored **with the version** that it was saved at, along with the any relevant properties (such as Displacement etc. in my example) - NoSQL would likely make a really nice fit here (Key = Entity ID, Value = Serialized Binary Data).

Each component would then need to be able to 'upgrade' old data from a previous version (never remove fields from serialized data - just 'null' them) - this upgrade happens the minute it is loaded (it would then be immediately stored back in the latest version available). Let's say that our house has had it's dimensions changed. The upgrade code would relatively work out the distance between the north and south walls and proportionally alter the displacements of all the contained entities. As another example our meat bowl might have the 'Food' field removed, and instead get a 'Variety' (Meat) and 'Recipe' (Balls). The upgrade script would turn 'Meat Balls' into 'Meat', 'Balls'. Each component should also know how to deal with changes to mount points - e.g. if one is removed you will need a mechanism in place to figure out the position relative to another mount point that is still available.

This all leaves exactly one issue open: what happens if two objects clash with each-other (not their container - mount points protect you from that)? After an upgrade you should check for collisions and attempt to resolve them (by moving things apart, a bit like SAT). If you can't figure out how to resolve the collision remove one of the objects and place it in a stash - where they can buy these removed items (for free) or sell them (at full price); and obviously notify the player that the upgrade broke some of their layout - possibly with a 'zoom into' feature so that they can see the problem.

Ultimately you should leave complex changes in the players' hands (fail fast) as no algorithm can account for aesthetic - you should merely be able to give the player context as to where the item used to be (so that they can remember, not just land up with all these items in their stash and not know where they were).

# Answer
> 1 votes
I'm trying to associate this with something that I understand, so I'm thinking in terms of Minecraft right now. I'm picturing a live server with players making changes in real-time while the developers are running on a test server fixing/creating new content.

Your question almost seems like 2 unique questions:

1. How to insure that object IDs are unique
2. How to insure that script namespaces do not collide

I would try solving #1 through a temporary referencing system. For instance, when a new object is created by someone, it could be marked as volatile or temporary. I would imagine that all new content created on the test server would be marked volatile (although it may also reference non-volatile content).

When you're ready to bring new content to the live server, your import process would find the volatile objects and assign them live-server object IDs that are set in stone. This is different than a straight-up import/merge because you need to be able to reference existing non-volatile objects should you need to fix or update them.

For #2, it seems you really need to have some level of intermediate script transmutation that can hash the function name to a unique namespace. i.e.

```
assignFrenchAccent

```

Becomes

```
_Z11assignFrenchAccent

```

# Answer
> 0 votes
If the files for the data are text as opposed to binary and the designers and players are modifying different areas you could try an SVN merge.

# Answer
> 0 votes
I think a database/filesystem replicated across environments with a 'check-out' procedure would be best.

So, whenever a designer wants to make some modification to the world, he would check-out/lock all assets he wants to create/modify on all copies of the database (development and production), so no other player or designer could modify it. He would then work on the development database until the new design is finished, and at that time the changes would be merged with the production database and those assets would be checked-in/unlocked in all environments.

Player edits would work in much the same way, except the database/filesystem roles would be reversed - they work on the production database, and all updates are uploaded to dev when finished.

The asset locking can be limited to the properties where you want to guarantee no conflicts: in Example 1, you'd lock `ID 123456` as soon as the player starts crafting it, so the developers will not be assigned that ID. In Example 2 your developers would have locked the script name `assignFrenchAccent` during development, so the player would have to chose a different name when developing his modification (that small nuisance can be reduced by namespacing, but that by itself will not avoid conflicts unless you give each user/developer a specific namespace, and then you'll have the same issue with managing the namespaces). This does mean that all development would have to read from a single on-line database, but all you require from that database in these examples are the object names, so performance should not be a problem.

In terms of implementation, having a single table with all keys and asset state (available, locked from dev, locked from prod) synchronized/accessible in real-time across environments should be enough. A more complex solution would implement a complete Version Control system - you can use an existing system like CVS or SVN if your assets are all in a filesystem.

# Answer
> 0 votes
I think the point here is to cleanly accept your responsibility. 1) The server says what is currently acceptable, and the API to access with. The database is being modified, according to certain rules. 2) Creators are allowed to create content, but it must be playable after updates. This is purely your responsibility: any update must be able to parse old data structures preferably as clean and easy as possible.

Mount point idea has merits if you are interested in keeping track of unique items and positions inside a malleable structure, especially if we accept that the whole 'home' structure of a player is going to undergo a dramatic change, and you want to keep that little deco stuff in their respective lockers.

It's a massively complicated issue, good luck! There probably does not exist any one answer.

# Answer
> 0 votes
I don't think this has big of a problem as you are making it.

I would just overwrite user created mods, with a warning noting that "Mod X may not work correctly with this version", leave it to the mod creators to change their work. I don't think this is an unrealistic expectation that updates might disable certain mods.

Same for user created content, just make a backup, and overwrite.

I have no actual experience in this, just making suggestions.

---
Tags: modding, online, version-control, patching
---


title: How to create wrap-around pathfinding?

text:
# Question
Title: How to create wrap-around pathfinding?
I've created a planet and obstacle grid and want to move units through this grid using A\* or any other algorithm. The only problem is wrapping. I need a simple example of how to handle this unusual pathfinding requirement. I prefer C#/XNA rather than C++.

# Answer
NOTE: The source code referenced in this answer is located in Engine Nine. However, CodePlex will be going offline soon & that project may no longer be avaiable; the source code *may* also be available in the follow up project Nine.Graphics

Here is a version of `GetEdges` that manages wrapping. The important part is the computation of `x2` and `y2` which are wrapped around the torus. I also removed the incredible level of code duplication that was in that method:

```
/// <summary>
/// Gets all the adjacent edges of the specified node.
/// </summary>
public int GetEdges(int node, GraphEdge[] edges, int startIndex)
{
    int count = 0;
    int x = node % SegmentCountX;
    int y = node / SegmentCountX;

    GraphEdge edge;
    edge.From = node;

    for (int dy = -1; dy <= 1; dy++)
    {
        for (int dx = -1; dx <= 1; dx++)
        {
            if (dx == 0 && dy == 0)
                continue;

            int x2 = (x + dx + SegmentCountX) % SegmentCountX;
            int y2 = (y + dy + SegmentCountY) % SegmentCountY;

            if (data[x2 + y2 * SegmentCountX] == 0)
            {
                edge.To = x2 + y2 * SegmentCountX;
                edge.Cost = (dx * dy == 0) ? 1.0f : 1.4142135f;
                edges[startIndex++] = edge;
                count++;
            }
        }
    }
    return count;
}

```

And here is the new `GetHeuristicValue`:

```
/// <summary>
/// Gets the heuristic value used by A star search.
/// </summary>
public float GetHeuristicValue(int current, int end)
{
    int dx = Abs(current % SegmentCountX - end % SegmentCountX);
    int dy = Abs(current / SegmentCountX - end / SegmentCountX);

    int xx = Min(dx, SegmentCountX - dx);
    int yy = Min(dy, SegmentCountY - dy);

    return (float)Math.Sqrt(xx * xx + yy * yy);
}

```
> 2 votes

# Answer
Assuming you already have a way to move objects in a looping world, you just need to implement a wrapping heuristic function for A\*. Normally in a tile-based world the heuristic function is something like `H = sqrt(dx*dx + dy*dy)` or `H = abs(dx) + abs(dy)`, where dx and dy is the difference between the current tile and the goal tile: `dx = targetX - currentX`. Replace that with something that takes the wrapping into account such as `dx = min(abs(dx), abs(width + dx), abs(width - dx))` and same for dy. Also make sure your A\* implementation gets the neighbours from the other side of the world on the edges.

**Edit:** When using the source code given in the comments, modify the following parts:

**Function GetEdges:** Remove all if-statements, but keep their content. Change all usages of `(x +- var)` to `(x +- var) % SegmentCountX` and same for y. Below are the required changes in the code:

```
edge.To = y * SegmentCountX + x - 1; // Change this line to ...
edge.To = y * SegmentCountX + (x + SegmentCountX - 1) % SegmentCountX;

```

and

```
edge.To = y * SegmentCountX + x + 1; // Change this line to ...
edge.To = y * SegmentCountX + (x + 1) % SegmentCountX;

```

And similar change for y direction and diagonals.

**Function GetHeuristicValue:** Before the return statement add lines:

```
xx = Min(Abs(xx), Min(Abs(SegmentCountX + xx), Abs(SegmentCountX - xx)));
yy = Min(Abs(yy), Min(Abs(SegmentCountX + yy), Abs(SegmentCountX - yy)));

```

You need to replace Min and Abs functions with the ones provided by your framework.

I'm not sure what SegmentCountX and bounds are in this code, but you might need to replace SegmentCountX or SegmentCountY with something from the bounds.
> 8 votes

---
Tags: xna, path-finding
---


title: Decompile an FX shader

text:
# Question
Title: Decompile an FX shader
Is it possible to decompile a `.xnb` file? I've lost my shader code, but only have my `.xnb` file left.

# Answer
> 0 votes
It's unlikely you'll be able to retrieve the source from the xnb file as it has undergone compilation into a binary format during the XNA pipeline stages. While it's theoretically not impossible, in my opinion you'd probably be much better off rewriting the shader..

# Answer
> 5 votes
The best you can get is a disassembly, which may help you recreate the source code. (Unless someone can point you to an actual HLSL decompiler. I've never seen one.)

If you happen to be using XNA 3.1 you could simply load it into an `Effect` object via the content system and then call `Effect.Disassemble` on it.

XNA 4.0 removes this - so it will be much harder:

First of all you need the actual effect data. Probably the easiest way to get it would be to use reflection to get access to the private `Effect.pCachedEffectData` member which (I think) contains it.

Once you have the binary data, you'll want to disassemble it. I can't figure out a way to use `fxc.exe` to disassemble the data directly. But perhaps you can install XNA 3.1 and use that. Or use Direct3D and `D3DDisassemble` \- which is, I suspect, what XNA 3.1 uses internally.

# Answer
> -1 votes
http://mirror.dataorb.net/XNB\_Exporter.zip \- Maybe this can help you.

---
Tags: xna, shaders
---


# Question
Title: Why does my 2d collision and movement not work properly?
I'm trying to write(in c++ using sdl) a mario like game as in a tile based world with by pixel movement for the character and I've run into some problems I cannot seem to find the source of:

1.The player won't collide with the walls.

2.when moving through open space the player sometimes stops moving and then becomes unmovable in either direction.

I'm not sure where the problem is and I would love your help finding these issues and any advice in general is appreciated. thanks!

Here is all the code:

http://pastebin.com/FGxW2x3T //sorry I can only post two links cause I don't have 10 rep.

Here is the collision detection function and player input/movement functions. http://pastebin.com/jWaZPDBm

# Answer
I was using SDL\_Rect for my collision box. The x and y variables for an SDL\_Rect are of type short and I was using a double for my velocity so my player.xPos and player.yPos(which are doubles) were not equal to the collision box's position because of lost decimal points when converting my double xVel to the int of collisionBox.x I assume.

Thank you Samaursa for the link to the guide on debugging this is how I found my issue!
> 0 votes

---
Tags: c++, collision-detection, movement, sdl, collision-resolution
---


# Question
Title: Pong - Changing the Ball's Y location depending on where it hits the paddle
I'm making my first game in, Pong, and I'm trying to make the ball's Y increase or decrease, depending on where it impacts the paddle. After implementing the code below, the ball only goes down, but not up. What could the problem be?

```
if(paddle.detectCollison(ball)){
    //30px on either side of the actual center of the paddle is considered the center
    if((ball.getY() > ((paddle.getH() / 2) + 30)))
        ball.setY(ball.getY() + 10);
    else if ((ball.getY() < ((paddle.getH() /2) - 30)))
        ball.setY(ball.getY() - 10);
    ball.setDX(-(ball.getDX()));
}

```

# Answer
I think the center calculation is off as its not taking into account the position of the paddle at all.

Shouldn't it be something like (posY + (height / 2) +/- fudgeFactor) or the like?

Depending on where 0,0 is on the y axis this could cause one of the if's to always return true as it is comparing against a location based off of the paddle always being at the 0 y location.
> 3 votes

# Answer
Your ball should have direction vector (i,j). Your pad can have vector field. Let's say your pads are vertical (since you haven't mentioned are they vert or horiz).

Vector field for a pad should be something like:
for the upper corner: (0, 1) 1 is y-up
for middle of pad: (1, 0)
for bottom corner: (0, -1)

everything in between are interpolated values. (these values can be easily calculated when needed using with/height etc).

Next thing you do, is do addition of vector from vector field and ball direction field (but you need to * -1 *i* value of dir vector because ball changes X direction).

So if input (ball direction) vector is (-1, -1) that is 225 degrees, and ball hits almost to bottom corner on left pad vector from vector field would be (0.1, -0.9). Invert ball dir vect *i* value and perform addition; that is (1, -1) + (0.1, -0.9) and resulting vector is (1.1, -1.9), and you can convert this to angles and work your way from there. Also good thing would be to normalize this vector before giving it to ball.
> 0 votes

---
Tags: java, collision-detection, lwjgl
---


# Question
Title: How to quickly calculate the sight area in a 2D tiled game?
I have a matrix of tiles, on some of that tiles there are objects. I want to calculate which tiles are visible to player, and which are not, and I need to do it quite efficiently (so it would compute fast enough even when I have a big matrices (100x100) and lots of objects).

I tried to do it with Bresenham's line algorithm, but it was slow. Also, it gave me some errors:

```
----XXX-        ----X**-     ----XXX-
-@------        -@------     -@------
----XXX-        ----X**-     ----XXX-
(raw version)   (Besenham)   (correct, since tunnel walls are
                              still visible at distance)

(@ is the player, X is obstacle, * is invisible, - is visible)

```

I'm sure this can be done - after all, we have NetHack, Zangband, and they all dealt with this problem somehow :)

What algorithm can you recommend for this?

---

For my needs, I'll define *visible* like this: tile is visible when at least a part (e.g. corner) of the tile can be connected to center of player tile with a straight line which does not intersect any of obstacles.

# Answer
> 10 votes
Your definition of visible is the following:

> tile is visible when at least a part (e.g. corner) of the tile can be connected to center of player tile with a straight line which does not intersect any of obstacles

You can implement this concept quite literally by tracing rays from your player tile and intersecting them with your scene. You break from each iteration once the ray hits an obstacle (or exceeds a certain distance threshold) since you're only interested on the tiles the player can see directly. I'll break up the process for you:

1. Specify the level of precision you'd like to give the algorithm. This will be the number of rays you will be tracing.
2. Divide the full 360 degrees circle by the chosen precision to know how many degrees to rotate between each ray.
3. Starting at 0 degrees and incrementing by the amount determined in step 2, create a ray with the origin at the center of the player tile, and the direction determined by the current angle.
4. For each ray, starting from the player tile, *walk* along the direction of the ray until you hit an obstacle tile. Add that tile to the visible tile list and proceed to the next ray. You might also want to add a maximum distance to "give up" in case no collision is found.

Here's a picture showing 3 example rays. The darker colored tiles are the "result" of each ray, i.e where the collision happened. You'd need to repeat this all around the circle though:

Tweak the maximum distance and number of rays for performance. Too little and you'll miss tiles, too much and your performance will suffer. Also, the furthest the rays have to travel, the larger the "error" will get, and the more precision you'll need.

**Edit**

Check the following tutorial on raycasting, in particular Step 3 and Step 4, to help you implement the intersection bit of the algorithm:

http://www.permadi.com/tutorial/raycast/rayc7.html

# Answer
> 8 votes
I'd rather cast shadow rays instead of line of sight rays.

Let's say this is your view area (the potentially visible area)

```
######################
#####.............####
###................###
##..................##
#....................#
#....................#
#..........@.........#
#....................#
#....................#
##..................##
###................###
#####.............####
######################

```

The # blocks are not visible while the . are visible

Let's put some obstacle X:

```
######################
#####.............####
###................###
##.....X.....XXX....##
#......X.......X.....#
#...X.XX.............#
#...X......@.........#
#...X..........X.....#
#...XXXXXX...........#
##..................##
###....X...........###
#####.............####
######################

```

You have a list of the X that are within the view area then you mark as hidden every tile that is behind each of this obstacle: when an obstacle is marked as hidden, you remove it from the list.

```
######################
#####.............####
###................###
##.....X.....XXX....##
#......X.......X.....#
#...X.XX.............#
#...X......@.........#
#...X..........X.....#
#...XXXXX*...........#
##......##..........##
###....*#..........###
#####.###.........####
######################

```

In the example above you can see the shadow casted by the rightmost of the bottom wall and how this shadow delete the hidden obstacle from the list of the obstacle you have to check (X have to check;\*checked).

If you get sort the list using some binary partiton so the cosest X are checked first you may slightly speed up your check.

You may use a sort of "Naval Battles" algorithm to check block of Xs at once (basically looking for an adiacent X that is in a direction that can make the shadow cone wider)

**\[EDIT\]**

Two rays are needed to cast correctly a shadow and, since a tile is rectangular, a lot of assumptions can be done using the available symmetries.

The ray coordinates can be computed using a simple space partitioning around the obstacle tile:

Each rectangular area constitutes a choice about what of the tile's corner should be taken as shadow cone edge.

This reasoning can be pushed further to connect multiple adjacent tiles and let them cast a single wider cone as follow.

The first step is to ensure that no obstacles are toward the observer direction, in that case the nearest obstacle is considered instead:

If the yellow tile is an obstacle that tile becomes the new red tile.

Now lets consider the upper cone edge:

The blue tiles are all possible candidate to let the shadow cone wider: if at least one of them is an obstacle the ray can be moved using the space partioning around that tile as seen before.

The green tile is a candidate only if the observer is above the orange line that follows:

The same stands for the other ray and for the other positions of the observer about the red obstacle.

The underlying idea is to cover as much area as possible for each cone casting and to shorten as fast as possible the list of obstacles to check.

# Answer
> 8 votes
The problem you are trying to solve is sometimes called Field of View, FOV for short. As you mentioned roguelikes as examples, you should take a look at what the RogueBasin wiki has to say about the subject (there's even links to implementations): http://www.roguebasin.com/index.php?title=Field\_of\_Vision

There are quite a few different algorithms with different pros and cons - a very handy comparison is available also at RogueBasin: http://www.roguebasin.com/index.php?title=Comparative\_study\_of\_field\_of\_view\_algorithms\_for\_2D\_grid\_based\_worlds

---
Tags: 2d, mathematics, algorithm
---


# Question
Title: Importing World of Warcraft models into Unity
I'm following some tutorials to create a simple game with Unity in order to learn, and I would like to enhance my learning experience by adding World of Warcraft models. Don't worry, this is all just for learning and won't see public eyes in any way. I downloaded a model viewer and I can export textures and animation from WoW with it, but when importing into Unity I'm having some problems.

Which extension should I export the model to, and what is the process I should follow in order to have an object with a model I just exported?

I'm really new to Unity, so any help would be great!

# Answer
> 4 votes
I would say you should export to FBX. That format includes animations and various other info. You could probably export to other types but Im pretty sure most use FBX. Once you import it, you will have to specify the texture for it so you will have to take the texture your exporter gives you and feed that into unity.

Also, you said you are just learning but I would say to be careful about using those models. I don't know for sure, but I would think blizzard might not like it. There are tons of free models you could use online that work with unity. Their asset store has a lot of free stuff that works just fine and imports ready to go.

---
Tags: unity, models, importing
---


# Question
Title: Slick2D Tile Based 'Fog of War' Blurring Problem
I'm working on my first Java Game and I have run into a little problem I'm hoping to get some help with. I'm using Slick2D displaying a tile based map, and I'd like to know how I can created a "blurred" fog of war.

Here you can see the fog of war covering most of the map, I am rendering the fog by filling a rectangle over each tile who has the property isFog = true.

When the climber goes to a tile isFog sets false, and the map is re-rendered.

I'm looking for a way to create a smoother fog like in this poor paint.net image. Please let me know what ideas you might have. Thanks!

Apparently I can not post images yet... I will update when I've earned enough reputation.

# Answer
> 1 votes
A couple of things you can do that come immediately to mind.

1 - Completely Tile Based

One of the layers of your map can be the "fog" layer, and have values that render images based on how close you have gotten to the tile(basically 64 different states, based on which directions the player has been adjacent to the tile). This will make your fog kind of blocky, but it might be okay for your needs, and it doesn't require all that much storage to update.... just another layer of tiles.

2 - Using Overlay Images

Ideally, you'd have a black images the size of the entire world, and update it as the player moves around by rendering the fog onto it wherever the player has gone.

In real life, you'd want to split it into screen-sized images so that at any give time, you never need to render more than a portion of four.

Of course, the downside of this is that you have to keep a bunch of screen-sized images somewhere, and that will get expensive if your world is big.

---
Tags: java, tiles, tilemap, slick
---


# Question
Title: Learning to code first game, few questions on basic game development and 3D
I've been programming for a while, and I'm concurrently learning how to make a basic game and slimdx, and wanted to talk to someone to hopefully get a few pointers. I've read that Tetris is the "Hello, world" of game programming, which made sense to me, so I decided to give it a shot.

I've been able to code up a basic version in a few hours, which I'm quite happy with, but I had a few questions about 3D programming. Right now I'm using Direct3D to do display the blocks without any textures (just colored squares). I have a data structure (2d array of bytes, where each byte denotes the presence of a block and its color) which is the "game board," and on every render() call I create a new vertex buffer of the existing squares in the game board, and draw those primitives.

This feels very inefficient, and I wondering what would be the idiomatic way of doing this in a 3D world, with matrix/rotations/translation operations. I know 3D is overkill for such a project, but I want to learn any 3d concepts that I can while I'm doing it. I understand that what you'd usually want to do is keep the same vertices/vertex buffers but manipulate them with matrices to achieve rotations/translations, etc. To do so, I assume what would happen is I'd have one vertex buffer for the "active" piece, since that'll be constantly rotated and moved, and have one vertex buffer for the frozen pieces on the bottom of the board, which is pretty much stationary, but will need to be changed/recreated when the active piece becomes frozen.

Right now I'm just clearing and redrawing on every render call, which seems like the easiest way to do things, although I wonder if there's a more efficient way to deal with changes.

Obviously there are a lot of questions I'm asking here, but if you can even just point me a step or two ahead in terms of how I should be thinking, it'd be great. Thanks

# Answer
> 2 votes
There are two approaches you can do to improve performance in this case:

The first one is a very simple fix to what you are doing right now. Do NOT recreate the vertex buffer of the existing pieces/cubes because there is not reason to do this.

Assuming all the pieces have the same geometry what you want is to have only one vertex buffer that describes the geometry of a given piece. Then in your Render loop you would "place" this in the world by changing the world transform. Something like this:

```
for (int piece = 0; i< numPieces;++i)
{
    // Setup the world, view, and projection matrices
    SetupMatrices(piece);

    // Render the vertex buffer contents
    g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof( CUSTOMVERTEX ) );
    g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
    g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2 * 50 - 2 );

    // End the scene
    g_pd3dDevice->EndScene();
}

```

That will perform better than what you are doing and is probably good enough. The only problem is that you will be sending the same geometry (the vertices) to the GPU many times (Every time you do a DrawPrimite). This is wasteful as well so you can actually do something called "hardware instancing" where you send the list of vertices once and a list of all the transforms you want the GPU to do. Here is a nice article explaining how to do it: http://http.developer.nvidia.com/GPUGems2/gpugems2\_chapter03.html

---
Tags: 3d, directx, slimdx
---


# Question
Title: Why doesn't this ContentLoader project (VS2010 e) recognize Microsoft.Build.dll?
I am working with an XNA content loader sample. In the references for the project (VS 2010 Express) there are:

* Microsoft.Build
* Microsoft.Build.Framework

//as well as the standard XNA framework and graphics references

To emulate this project, I am trying to first add a reference to Microsoft.Build.dll. But Visual Studio warns me that it cannot load the .dll. I looked at MSDN and the document referenced Microsoft.Build.Evaluation. This is suppose to be available in the Microsoft.Build.dll and then I'll have access to the Project class.

Has anyone had any experience with this?

# Answer
> 3 votes
Make sure to change the project's target .Net Framework from .Net 4 Client Profile to .Net 4. The client framework does not include MSBuild.

To do this open the project properties, select the Application tab, and change the Target Framework dropdown to ".Net Framework 4".

# Answer
> 1 votes
If for some reason you have the infamous .NET bug where the Target Framework box is greyed out and you are stuck in Client mode, you can force VS2010 to use the full framework by opening the .csproj file in a texteditor and then make sure that this line:

```
<TargetFrameworkProfile></TargetFrameworkProfile>

```

is empty.

Worked for me, now Microsoft.Build is available to reference in the project.

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


title: A* Pathfinding Problems

text:
# Question
Title: A* Pathfinding Problems
I'm trying to implement the a\* pathfinding algorithm in my game. I've looked at dozens of tutorials but I can't seem to get it right. My code is below, and It's not working... does anybody see something I'm doing wrong? Mainly, I followed these tutorials: Tutorial 1 Tutorial 2

I'm sure you will be able to understand all of the classes/methods I've created. If you can look over this code and just tell me if it looks remotely correct that would be great.

```
public void highlightPath(Tile start, Tile end)
    {

        AStar astar = new AStar();

        Tile currentTile = start;
        Tile endTile = end;

        start.node.g = 0;
        start.node.h = astar.getHeuristic(start.getCoordinates(), endTile.getCoordinates());

        start.node.parent = null;//for the loop

        astar.openList.add(start);

        while(!astar.openList.isEmpty())
        {
            currentTile = astar.getTileWithLowestF();

            if(currentTile==endTile)
                break;

            astar.openList.remove(currentTile);
            astar.closedList.add(currentTile);

            AdjacentTiles adjacentTiles = getAdjacentTiles2(currentTile);

            //Assign G and H costs:
            adjacentTiles.aboveRight.node.g = 10 + currentTile.node.g;
            adjacentTiles.right.node.g = 14 + currentTile.node.g;
            adjacentTiles.belowRight.node.g = 10 + currentTile.node.g;
            adjacentTiles.below.node.g = 14 + currentTile.node.g;
            adjacentTiles.belowLeft.node.g = 10 + currentTile.node.g;
            adjacentTiles.left.node.g = 14 + currentTile.node.g;
            adjacentTiles.aboveLeft.node.g = 10 + currentTile.node.g;

            ArrayList<Tile> adjacentTilesList = new ArrayList<>();

            adjacentTilesList.add(adjacentTiles.aboveRight);
            adjacentTilesList.add(adjacentTiles.right);
            adjacentTilesList.add(adjacentTiles.aboveRight);
            adjacentTilesList.add(adjacentTiles.belowRight);
            adjacentTilesList.add(adjacentTiles.below);
            adjacentTilesList.add(adjacentTiles.belowLeft);
            adjacentTilesList.add(adjacentTiles.left);
            adjacentTilesList.add(adjacentTiles.aboveLeft);

            for(Tile t:adjacentTilesList)
            {
                t.node.h = astar.getHeuristic(t.getCoordinates(), endTile.getCoordinates());
            }

            for(Tile t:adjacentTilesList)
            {
               //Check traversability:
               if(t.exists == false)//Change this to test segments/elevation
                   continue;//skips everything below...

               if(astar.closedList.contains(t) && currentTile.node.g < t.node.g)
               {
                   t.node.g = currentTile.node.g;
                   t.node.parent = currentTile;
               }
               else if(astar.openList.contains(t) && currentTile.node.g < t.node.g)
               {
                   t.node.g = currentTile.node.g;
                   t.node.parent = currentTile;
               }
               else
               {
                   astar.openList.add(t);
               }

            }

        }

        Tile startingTile = start;
        Tile currentTile2 = endTile;
        ArrayList<Tile> path = new ArrayList<>();
        path.add(currentTile2);

        while(currentTile2 != start)
        {
            path.add(currentTile2.node.parent);
            currentTile2 = currentTile2.node.parent;
        }

        for(Tile t:path)
        {
            t.highlight();
        }

    }

```

# Answer
I think you messed up your if-statement. It should be something like this:

```
for(Tile t:adjacentTilesList)
{
     // if the node doesn't exist, or is not walkable, or we have already traversed it ignore it
     if(!IsWalkable(t) || astar.closedList.contains(t))
         continue;

    // If we don't have this node as a candidate node then add it. Make sure you signal where we are coming from
    if(!astar.openList.contains(t))
    {
        t.node.parent = currentTile;
        astar.openList.add(t);
        continue;
    }
    else
    {
        //We already identified this node before so compare it to the previous cost and switch if it can be reached cheaper/faster
        var existingNode = astar.openList.Find(t);

        if (t.g < existingNode.g)
        {
          existingNode.g = t.node.g;
          existingNode.g = t.node.parent;
        }
     }
}

```

Note that you'll need to define the **IsWalkable** function.
> 2 votes

---
Tags: java, path-finding
---


# Question
Title: C#/XNA multiplayer TCG game inside a browser possibe?
I wish to try and create a TCG using C#/XNA that would run inside a web browser. Some of the main game's features would be:

* At least 2.5D to imitate the card flipping/shuffling and etc. effects
* Simple particle effects (maybe even none at all)
* Use of scripting since each card would have its own abilities/type/effects
* Utilization of relational databases(cards themselves, users, profiles, decks, etc.)
* Lobby
* Chat rooms
* Buddy list
* Free

Is such thing possible? You might want interject and point me towards Flash/AS3 as a better alternative, but the thing is I'm much more versed in C# than AS3 and never worked with Flash.

Also, I believe Unity has a WebPlayer and uses C# as one of its scripting(?) languages. Thing is, I want to make sure that the game can run on pretty old PC/Laptop/maybe Tablet and or smartphone hardware.

Suggestions? Warnings? I'm just brainstorming about this at the moment to select the right technologies(aka C#/XNA/? if possible or Unity/C#/Unity WebPlayer) to start researching further on my own. Not a single line of code has been written.

# Answer
Silverlight 5 has an graphics API that basically a subset of the full XNA library. Its pretty capable, can handle 3d, and most basic XNA could be dropped in minimal changes.

Also there is an active community and libraries dedicated to improving its capabilities.
> 4 votes

# Answer
Technically it is possible by making an OCX browser control (I am not sure if this will work in browsers other than Internet Explorer) and host XNA inside of it, finally you will likely need to write your own `ContentManager` and override `OpenStream` so that it grabs resources from your web server. Keep in mind that this doesn't 'save' your clients from needing to download the .Net runtime or the XNA runtime - furthermore your runtime will still need to be installed manually *and GACed* (because otherwise you would be running in partial trust and I doubt the .Net runtime will allow XNA to boot up).

However, I really recommend Unity because they have already tackled all of these issues (so you don't have to waste your time tacking them): and C# is a supported language in Unity.
> 2 votes

# Answer
Consider Mono and Native Client. Mono is programmed in C# (It runs on Linux, Mac and Windows without .NET) and Native Client allows applications written in C/C++, C#, Java and other languages to run within Chrome Browser. The gonacl site has details about Native Client and you can watch recent video of a Native Client event that took place in December.

Note. Currently NaCl as it's called works mainly with C/C++ but the Mono C# compiler generates compatible code. There's not a lot of documentation out about it yet with Mono but Mono is being pushed as a major dev platform for NaCl.
> 1 votes

# Answer
http://jsil.org/ will provide you the ability to convert an XNA spritebatch based game to Javascript so that it's playable in a browser.

That being said, I'd suggest it's probably easier in the long run to learn Javascript directly and write something for the Canvas element (e.g. a nonsense example I wrote very quickly at http://lzcd.com/mat ) or via one of the Javascript gaming libraries such as Easel ( http://easeljs.com/ ).

That way you don't have to worry quite so much about supported browsers or operating systems.
> 0 votes

# Answer
There's always PlayN. I tried it, but didn't like the lack of documentation and long compile times required by the Google Web Toolkit (it's known to be slow). Still, it may fit your needs well.
> 0 votes

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


# Question
Title: Top-Down mapping with GLEED2D: Collision and Faux 3D
This is just a theoretical question. I was thinking of using GLEED2D to map a top-down game (I haven't decided on what type, but that shouldn't matter for this question.). I chose GLEED2D because I was getting tired of tile-based maps, and wanted to try something new.

However, two questions come to mind: How would you implement collision, and how would you display faux 3d? (I can't come up with a better name. It's where in RPGs and other topdown games you can have a bottom wall that obscures your character if you walk up to it. Say there's a pillar on the map. On a tiled map, it takes up one tile of space that you can't move on to, but the sprite itself is taller than one tile, so it covers character when you are behind it.)

An idea I had was to use the primitive shapes such as the Path to define areas where the character should collide. But then there's the faux 3d issue, which I can't figure out. Maybe GLEED2D isn't meant for it?

# Answer
**Problem #1 - Collision Detection**

Under the assumption that you will use Gleed2D mostly for sprite based level editing, i.e. by placing, rotating and scaling a set of rectangular sprites in the world, I would suggest *one of the following approaches* to collision detection **depending on your needs** (read to the end even if the first suggestions don't apply to *your* case):

1. **Use a physics engine** such as Farseer or Box2D to handle both collision detection *and* collision response between physics bodies that are good representations of your sprite's bounds. These bodies could be simple oriented bounding boxes or some other shape if more appropriate. Good for when the collision geometry should be fairly similar to the sprite's look.
2. Similar to number 1 but handling collision detections yourself using an **OBB-OBB intersection test** between your sprite's bounds. See the Separating Axis Theorem for one common way to implement this sort of intersection. That's only valid if you want to use the sprite's bounds *as the collision geometry* though.
3. If you wanted you could also add an additional **pixel perfect collision test** after step 2 by checking the opacity of the pixels on the sprites against each others. For this you'd need to transform pixels into the same space first. But I wouldn't really recommend doing this, and would go with one of the other alternatives instead.
4. If on the other hand you need *different collision shapes than the sprite's bounds* then I think your idea was right on track. So what I'd suggest in that case is to **add a new layer on Gleed2D just for collision geometry**, and draw it using the `Path` tool. I actually do something similar to this on my graphic adventure game engine, although I use my own editor for creating the geometry. Here's a video of how it behaves. You could always add this functionality outside of Gleed2D if needed, and it's pretty easy to do using the Clipper library as I did on the video above.

*Example:*

---

**Problem #2 - "Faux 3D"**

I'm not sure I really understood your problem, but from my interpretation, I think it's just a matter of choosing the correct drawing order for your sprites. The approach I would take would be:

1. **Assign an origin to each sprite** that would act as the sprite's "feet", i.e. a point in the sprite that is touching the ground. In its simplest form, you could simply pick the middle-bottom point of your sprites.
2. **Sort your sprites so that they're drawn starting from the ones with lower origin Y** values and moving towards higher origin Y values. This way, objects further down the screen will automatically occlude objects that are supposed to be behind them.

*Example:*

Note: I marked the origins on the sprites using a blue dot, and drew them top to bottom. I assume this is the effect you were talking about.
> 0 votes

---
Tags: sprites, gleed2d
---


# Question
Title: Import a 3D animation into an android game
I want to import a skinned and animated character model built with bender into an android game. The animations can be: idle, walk, run ...etc

I've seen a related question but it's only about importing a static model: https://stackoverflow.com/questions/204363/is-there-a-way-to-import-a-3d-model-into-android

But I don't see how to import a set of animation with tweened frames.

Any ideas, resources or tutorials about how this can be achieved ?

---

Edit: After some further searching I've found this library that claim to provide model loaders for md5 files. http://code.google.com/p/libgdx/

Edit2 (2011 12 16): I tested libgdx mentionned above And it actually works well for now, I can render a walking animation from md5 models with a good framerate, but the model loading time is quite long. For a large amount of models and frames, I think switching to binary formats will become necessary.

# Answer
You need to look up the file format for your animated mesh and decipher it. So, you'll need a framework capable of rendering a skinned mesh; you may have to do weighted mesh transformations in software, yourself, unless you're able to use vertex shaders in your version of OpenGL ES.

Next, you'll need to be able to load the mesh, the skeleton and the animation. This is probably a binary file format so you'll need:

1. The file format(s) in question, showing you the byte offsets of all data members and other relevant information.
2. You'll need to load your files, possibly using 'DataInputStream' if they're binary. Make sure the 'endianness' of the data matches your system, you may have to swap bytes around if the data has a different order to the platform you're working on.
3. Skin your weighted mesh - i.e. either in a vertex shader or on the CPU, go through each vertex and blend the position according to the vertex weights and the matrices that they refer to.
4. Profit!

I'm not sure how much of that made sense because I don't know what you don't know. You could try giving a bit more information such as the file formats for your data and if you're using a 3rd party 3D engine or writing your own.

HTH.
> 4 votes

# Answer
For converting animated models from Blender to M3G you can use Liquidiser (http://code.google.com/p/liquidiser/). As for reading -- I'm not aware of any publicly available library that would allow you to import .m3g files but I do have a library which can do that.

I wouldn't mind making it public as it does what it's supposed to do (read, process and render models, including tweened animations) but at the moment it's not optimised as I'm still developing the game that uses it and performance hasn't been a priority yet. If you're interested in cooperation please get in touch at max.\<my-stackexchange-nick\>@gmail.com
> 3 votes

# Answer
Just for the record, in case someone else wants to import/play skeletal animation with skinning using Blender:

There is the open source AnimKit that can play skeletal animation straight from a .blend file. It includes some basic samples using OpenGL/glut. THe code is portable, works under Windows, Linux, OSX, and a sample using Android is planned.

http://code.google.com/p/gamekit/downloads/detail?name=animkit\_src\_r1020.zip And also some info related to this here http://opengles20study.blogspot.com/
> 1 votes

---
Tags: 3d, android, animation
---


# Question
Title: Looking at the mouse position in a top down Unity game?
I'm trying to make a simple top down game where the player looks at wherever the mouse is pointed. The player is only going to rotate on the Y axis.

Here's what I have so far but I can't seem to get it working.

```
private void RotateToMouse()
{
    //Veriables
    Vector3 ScreenMouse;
    Vector3 ShipPos;

    //Get Mouse Point ON screen
    ScreenMouse.x  = Input.mousePosition.x;
    ScreenMouse.y  = Input.mousePosition.y;
    ScreenMouse.z  = 1;

    //Get Mouse Point In World
    WorldMouse = Camera.main.ScreenToWorldPoint(ScreenMouse);
    //Get Ship Position
    ShipPos = transform.position;

    //Get Angle Of Mouse From Ship Position
    Angle = Mathf.Atan2(ShipPos.z - WorldMouse.z,ShipPos.x - WorldMouse.x) * 180 / Mathf.PI;

    transform.localEulerAngles = new Vector3(0,Angle,0);
}

```

# Answer
Instead of using Atan2, I would suggest using the built in function `Transform.LookAt`

So, after you get `WorldMouse`, just do `transform.LookAt( WorldMouse );`.

You *might* have to set `WorldMouse.y` equal to `transform.position.y`, but it shouldn't matter.
> 2 votes

---
Tags: c#, unity, mouse
---


title: Rotation of images in Slick2D

text:
# Question
Title: Rotation of images in Slick2D
I have have a rotation problem in the Slick2d library, the image is just not rotating (ie I set a rotation but no result is shown). Here is the rotation code:

```
if (input.IsKeyDown(Input.KEY_LEFT))  {
    velocity.x = -1;

    rotation = (float)Math.toRadians(180);
}

```

That is meant to set the rotation of image to 180 degress.

Then I render the image with an origin of the center of the image:

```
image.setCenterOfRotation(image.getWidth() * scale / 2, image.getHeight() * scale * / 2);
image.setRotation(rotation);

image.draw(position.x, position.y, scale);

```

Any ideas? Thanks.

# Answer
> As far as I know, Image.setRotation(float) accepts degrees, not radians. Bobby.

Thanks Bobby!
> 0 votes

---
Tags: 2d, java, rotation, lwjgl, slick
---


# Question
Title: Interesting/Innovative Open Source tools for indie games
Just out of curiosity, I want to know opensource tools or projects that can add some interesting features to indie games, preferably those that could only be found on big-budget games.

**EDIT:** As suggested by The Communist Duck and Joe Wreschnig, I'm putting the examples as answers.

**EDIT 2:** Please do not post tools like PyGame, Inkscape, Gimp, Audacity, Slick2D, Phys2D, Blender (except for interesting plugins) and the like. I know they are great tools/libraries and some would argue *essential* to develop good games, but I'm looking for more rare projects. Could be something really specific or niche, like generating realistic trees and plants, or realistic AI for animals.

# Answer
I think OpenGL and OpenAL are extremely obvious, but beyond that...

API

* Bullet 3D Physics engine, used in AAA titles
* Chipmunk Flexible and Powerful 2D Physics engine in straight C
* Box2D Another robust and popular 2D physics engine
* FPMath C++ template based math library, specifically for dealing with Fixed Point arithmetic (requires Boost)
* OpenSteer Steering Behaviors for Autonomous Characters
* Xiph home of lots of open source audio and video alternatives like Vorbis and Theora

Tools

* Blender 3D Modeling Tool with a great deal of functionality and support for many different file formats
* Gimp 2D Raster image manipulation, very robust feature set
* Inkscape 2D Vector image manipulation, based on SVG
* sfxr Sound effect generator, great if you're in a hurry or don't have an audio specialist
* FFMpeg record, convert and stream audio and video

Engines

* RakNet cross platform, open source, networking engine for game programmers (RakNet 4 is free for independent Developers that gross $50K or less)
* Irrlicht open source high performance realtime 3D engine written and usable in C++ and also available for .NET languages.
* Ogre3D One of the most popular open source game engines, and for good reason

Mobile Specific (since that's what I'm into at the moment)

* Oolong game engine that includes much of the above mentioned, optimized for PowerVR on the iphone, maintained by Wolfgang Engel and Erwin Coumans of Grand Theft Auto fame
* Cocos2D free Objective-C based iPhone specific port of the Python original, very easy to use and lots of community support
* VFPMath Crazy fast math library written mostly with inline assembly to take advantage of the ARM processor
* AndEngine 2D OpenGL Game Engine for Android

More Exotic:

* Canonical Multitouch Gesturing system for all multitouch input devices and more
* 1 dollar and N dollar stroke recognition systems. Links are for javascript implementations, but they have been ported to many other languages
* OpenFoam Computational Fluid Dynamics (CFD) library in C++, see also FireFOAM an extension for modeling fire
* Moody an n-Model body development framework I found interesting, primary usage would be Celestial Mechanics and Astrodynamics. Includes a viewer tool for files.
* ofxMSAFluid Fluid dynamics simulation framework
* Gromacs \- "versatile package to perform molecular dynamics, i.e. simulate the Newtonian equations of motion for systems with hundreds to millions of particles"
> 26 votes

# Answer
Recast & Detour is an awesome open source navigation mesh / path finding library. It's potentially got more appeal to larger titles than indie games, but I could definitely see it being useful to anyone wanting decent multi-agent movement in any 3D game.

The developer's (Mikko Mononen) blog also has several interesting entries around steering, path finding and navigation in general.

And it's actively maintained / developed.
> 16 votes

# Answer
I pulled some audio gems from my memory with help from Wikipedia.
> 6 votes

# Answer
Examples of tools/projects I found interesting are:
> 5 votes

# Answer
The following are blender tools:

ANT landscape generator: http://wiki.blender.org/index.php/Extensions:2.5/Py/Scripts/Add\_Mesh/ANT\_Landscape

Procedural generation of landscapes which simplifies the generation of complex terrain.

Blended Cities: http://jerome.le.chat.free.fr/index.php/en/city-engine/news/

Procedural city generation for the artist to quickly generate large cities. For my undergraduate dissertation I added city zoning to this: http://www.blendernation.com/2010/04/26/city-zoning-modification-for-blended-cities-script/

L-system tree generator: http://lsystem.liquidweb.co.nz/Examples/tabid/122/Default.aspx

Standalone vegetation generator: http://arbaro.sourceforge.net/
> 5 votes

# Answer
* Ivy Complex vegetation generator
> 5 votes

# Answer
It's a bit of an old topic but has some other recent posts, so I'm going to throw in my own voxel library. It's great for creating environment with smooth voxel terrain or 'cubic' environments like Minecraft. Environments can then be modified in real time and it should be easy to integrate with most 3D engines. It's under the zlib license for free for commercial use.

Have a look at http://www.thermite3d.org for more information.
> 5 votes

# Answer
The Verse Protocol and reference Engine is astonishingly awesome; check out some discussion of a game made with the engine, and then ... the tools demos! The tools demos will blow you away....
> 5 votes

# Answer

> 5 votes

# Answer
Here is a list of tools I found just today:
> 4 votes

# Answer
These two probably go without saying, but:

* OpenGL (rendering)
* OpenAL (audio)

are both high-quality industry staples that are open source and cross-platform. Always worth considering.
> 2 votes

# Answer
If you are interested in an innovative 3D framework, checkout Google's O3D that allows development of 3D games for WebGL compatible browsers, such as Chrome 9 (beta), Firefox's nighly build; Minefield & Safari WebKit (iPhone)

Checkout this video of the body browser made with this new technology if you don't yet have one of these browsers :)
> 2 votes

# Answer
I came across some tools for 2D game development recently that I find quite exciting:

* SWFSheet converts a SWF created in Flash (including animations created using Actionscript) into a spritesheet or series of sprites
* Zwoptex packs a series of sprites into a spritesheet and emits metadata about their position
* Texture Packer is an alternative program which does the same

Personally, I think the Flash authoring tools are amazing and dearly miss them when I work in XNA or Java. Which is why I'm excited about giving the above a spin.
> 2 votes

# Answer
AnimKit is a small basic open source skeletal animation system with skinning, that loads the data straight from a Blender .blend file. It uses the liberal ZLib license, like Bullet.

The code is portable, it works under Windows, Linux, OSX and some iOS and Android samples are planned.

See http://code.google.com/p/gamekit/downloads/detail?name=animkit\_src\_r1020.zip and http://gamekit.org/forum/viewtopic.php?f=9&t=144
> 0 votes

# Answer
### Wiki: PxTone, Orig: PxTone \- \[Tutorial\] - \[Download\]

A japanese music/beat/tone maker!
> 0 votes

---
Tags: tools, open-source
---


# Question
Title: How to reduce the CPU usage during the state preservation phase in my MMO?
I'm writing small MMO using Boost library. I want to make it non-target game, but I'm having trouble saving the previous game state. I don't know how to implement the game world, NPCs', and players' states. Currently, I'm copying all my NPCs, players and map in main game cycle, but it consumes too much CPU usage, about 60-80%. Obviously it too much.

Example of code in my save game method:

```
void GameHistory::saveGame(game* g)
{
    if (player_history.size() == 64) {
        player_history.erase(player_history.begin());
    }
    if (map_history.size() == 64) {
        map_history.erase(map_history.begin());
    }
    if (npc_history.size() == 64) {
        npc_history.erase(npc_history.begin());
    }
    long long t = lib::GET_SERVER_TIME();
    players_obj_hash players;
    game::players_hash::iterator itp = g->__players_by_id__.begin();
    game::players_hash::iterator endp = g->__players_by_id__.end();
    for (; itp != endp; itp++) {
        players[itp->second->getId()] = (*itp->second);
    }
    player_history[t] = players;
    map_history[t] = g->map;

    npcs_obj_hash npcs;
    game::npc_hash::iterator it = g->npcs_by_id.begin();
    game::npc_hash::iterator end = g->npcs_by_id.end();
    for (; it != end; it++) {
        npcs[it->second->getId()] = (*it->second);
    }
    npc_history[t] = npcs;
}

```

I'm using map as grid, where every NPC or player "register" on which cell it's on for fast lookup of nearest entities.

Maybe there is another more light approach to save the game state?

# Answer
> 4 votes
Instead of making full copies of every entity in the world, just save the entities and attributes that are relevant to what you want to lag compensate.

For example, in a first person shooter, often the only thing to lag compensate are the bullet shots. To calculate whether a bullet hit, you only need to know, (a) the positions of other players and, (b) their hit boxes. That's all you should store in the history buffer. When you need to lag compensate, update the positions and hit boxes of the players, without touching anything else.

Additionally, you can be intelligent about which entities you choose to lag compensate. If you know your skill has a maximum range of `x` and players can move at a maximum speed of `y` then don't bother lag compensating any entities farther than `x+y*dt` distance away, since you know that they won't be hit by the skill.

P.S. I'm also working on an MMO that uses lag compensation. Just because it's not expected by MMO players doesn't mean we should deny them a good experience! WoW is over 7 years old now.

---
Tags: c++, mmo
---


# Question
Title: In the GJK algorithm, when is a point ever closer to the origin than a line?
The GJK algorithm depends upon a function in its loop that updates the simplex and search direction for the next iteration (which is often called something like `DoSimplex()` or `ProcessSimplex()`). In order to find the next simplex, the algorithm divides the current simplex into regions, and determines which region contains the origin.

Here is an example of the regions for a 1-simplex (i.e. a line). In this example, the simplex previously only contained point B, and then point A was added in the direction of the origin.

(http://entropyinteractive.com/2011/04/gjk-algorithm/)

Now it makes sense to me why the origin can't be in region 4, since we just came from there. However, I can't think of any case where the origin would be in region 1 either. We just traveled from B to the origin, and if we didn't reach the origin, then we know there was no collision. So won't the origin always be in 2 or 3? Why does every algorithm always check whether the origin is in region 1?

# Answer
I discovered my answer. If the origin is in region 1, then it is a termination condition. It means that the origin isn't inside the Minkowski Difference, and therefore the shapes are not colliding. We just return the single point so that the next loop will terminate, and we can keep our support code general, without any special casing for exiting early.
> 3 votes

---
Tags: collision-detection, algorithm
---


title: Xna rotate around world axis?

text:
# Question
Title: Xna rotate around world axis?
I want to make it so that either the pitch yaw or roll rotates around the world axis and not the local axis, but I'm not sure how, I've got.

```
Vector2 mouse_change = new Vector2(mouse_previous.X - mouse_new.X, mouse_previous.Y - mouse_new.Y);
camera_angles *= Quaternion.CreateFromAxisAngle(new Vector3(0, 1, 0), mouse_change.X / 800f);
camera_angles *= Quaternion.CreateFromAxisAngle(new Vector3(1, 0, 0), mouse_change.Y / 800f);

```

Updating every frame, then I've got.

```
view_matrix = Matrix.Invert(Matrix.CreateFromQuaternion(camera_angles) * Matrix.CreateTranslation(camera_position));
projection_matrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, device.Viewport.AspectRatio, 0.2f, 500f);

```

The problem is that if I e.g. change the pitch then change the yaw then the yaw changes through the local axis, I need it to turn around the world axis so that it doesn't matter what the yaw is :/.

# Answer
You should try function Quaterion.CreateFromYawPitchRoll. It should create the correct quaterion.

Or if you are using this only for view matrix, you may want also try Matrix.CreateFromYawPitchRoll.
> 2 votes

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


# Question
Title: As an aspiring game developer, which game engine should I learn?
I am currently a full-time student and part-time game developer. I have released six 2D games into Android and WP7 markets. I have also dabbled in 3d development with C++ and DirectX. I am decent at 2D, but have a lot to learn in 3D. I want to be a professional 3D game developer for PCs and/or consoles.

As I understand, most game developers use off-the-shelf engines in AAA games.

My situation is as follows:

* I will learn alone. No team involved.
* I am interested in graphics programming (writing shader code) as well as gameplay programming.
* I am not (currently) interested in learning core game engine architecture in depth.
* I have no plans on releasing any commercial 3d game any time soon. Learning purposes only.
* I want to code in C++ and for Windows platform only.

Which 3D game engine should I invest my time learning? Which one is industry standard? Will it help my resume?

# Answer
> 21 votes
**If you want to be an engine developer / graphics programmer**:

* OpenGL. DirectX. (pick your order)
* GLSL. HLSL. (pick your order)
* GCC + its tools. Visual Studio + its tools. (pick your order)
* Understand first the fixed function pipeline (if you intend to start simple) and then the programmable pipeline from end to end, thoroughly.
* Spend time improving your maths: trig, matrices(!), quaternions, general calculus.
* Spend time learning about the most common 3D computational geometry problems including e.g. fast intersection tests, mesh construction, tessellation (creating triangles), mesh optimisation.
* Spend time learning about / understanding the various lighting models out there, this stuff is gold for an engine programmer. This will take you into new worlds of mathematics as compared with what is mentioned above.
* Spend time studying research papers (particularly stuff released by NVidia and in the Graphics Gems books) and demoscene code to improve your knowledge of optimisations used in graphics programming.
* Learn parallelisation / vectorisation *well*.

**If you want to be a dedicated gameplay programmer / C++ generalist**, any C++ engine will do, but I would suggest that you may not want to use a fully fledged engine, since you will still want to show that you are able to set up the application architecture on your own, and write the various subsystems involved (loaders, parsers, basic physics, entity systems etc. etc.). Something that wraps the 2D or 3D graphics and sound interfaces lightly is better from this viewpoint.

**If you want to be a designer/developer hybrid**, Unity, UDK, Flash, Java, XNA, JS/HTML5 Canvas are all good options, because they allow you to focus on the logic that gets the job done fast. Otherwise any high-level C++ engine that simplifies development as much as possible. Faster coding = more designs pumped out per year.

I would suggest sticking to *a* path. Know what skills you bring to the table.

# Answer
> 11 votes
> Which 3D game engine should I invest my time learning?

Whichever one interests you most.

> Which one is industry standard?

There isn't one.

> Will it help my resume?

Maybe.

Fundamentally I think you're asking the wrong question and possibly for the wrong reasons. The skill you want here is not the skill of understanding a particular engine, but the skill *to be able to* understand any particular API -- in other words, the ability to take a look at code or technology that isn't your own and start developing familiarity with it. Especially when you start as an entry-level developer in the industry, you'll be doing that more often than not.

I would generally say not to bother trying to learn an "engine" and just keep doing what you've been doing -- working on projects and releasing them on your own time. In my opinion as an engineering lead in the industry that's far more valuable than somebody who can tell me all the API calls you need to make to get an Unreal game working (I can read documentation and I expect you to be able to as well).

It is still useful to work those parts of your brain that are used to understand other people's code though, so along those lines pick an engine you are interested in (perhaps you like the games built with it) and start learning that, or find an interesting open-source project and think about contributing to it.

---
Tags: education
---


title: Blender or 3Ds Max

text:
# Question
Title: Blender or 3Ds Max
I am starting a 3D video game project and I do not know whether I should use Blender or 3Ds max. Other sites say to use Blender because it has similar functionality and it is free, but I need to know which one I should use completely disregarding the cost. I have some experience with 3D modeling and I have used both programs before. For the game I will be making landscapes, buildings and small models (ex. weapons).

I would like to hear your opinions on which program would be better for me to use disregarding the price.

# Answer
In your case, it all depends on what you feel comfortable with. Blender can be pretty confusing for some and it takes a while to learn as it is a bit different from standard modelling programs. If you plan to have others help, determine what they prefer and base your decision with that.

The main selling point to blender is that most indie developers don't want to spend a lot of money for Max and usually go with Blender. On the other side, Max is more industry standard and some like to know that they use what the Pros use.
> 1 votes

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


# Question
Title: Performance/architectural implications of calling SpriteBatch.Begin/End in many different places?
I notice some code samples only call `SpriteBatch.Begin` and `SpriteBatch.End` in the game's main draw method and then draw everything within that method through direct `SpriteBatch.Draw` calls or indirect calls through method calls from other classes that store a reference to the SpriteBatch object and then use its `Draw` method.

Another approach I see is that in these separate classes they call `SpriteBatch.Begin` and `SpriteBatch.End` before their drawing code in each of these classes and don't rely on already being contained within a drawing session (between a begin and end call).

My question is two-fold. Firstly, as the title suggests, what are the performance implications of calling `SpriteBatch.Begin/End` in all these separate classes so often (once per class per drawing update) versus just calling it the one time each update. Secondly, and this question is a a bit more subjective but, which design is generally preferable?

Thanks.

# Answer
**Short Answer**

Try to use the *same* `Begin/End` block as much *as possible* in order to maximize the amount of sprites that are batched and reduce the *actual* number of Draw calls made to the graphics device. In general, you only really need to use a different `Begin/End` block when you want to change some of the parameters to `SpriteBatch.Begin`.

---

**Long Answer**

I'll start with the second question:

> Secondly, and this question is a a bit more subjective but, which design is generally preferable?

Take a look at the longest version of `SpriteBatch.Begin`:

```
public void Begin (
         SpriteSortMode sortMode,
         BlendState blendState,
         SamplerState samplerState,
         DepthStencilState depthStencilState,
         RasterizerState rasterizerState,
         Effect effect,
         Matrix transformMatrix
)

```

In general, *as long as I don't need to change any of these parameters* I try to use the *same* `Begin/End` block for all of my `Draw` operations. The reason should become evident when I address your other question later, but to sum it up, it's to reduce the amount of calls (render stage changes and draw operations) made to the graphics device.

Conversely, whenever I start a new `Begin/End` block it's usually for *a very specific reason*. For instance, I might use separate blocks when:

* I need a group of sprites to be drawn with additive blending instead of alpha blending.
* I have a group of sprites that use a view matrix for camera movement, but there's another group of sprites that should always be drawn on top as an overlay, so the view matrix shouldn't affect them.
* I have different layers of sprites with parallax and implement parallax by passing a different view matrix to each layer.
* I need to use different shaders for different groups of sprites.

All of these cases fall under the general case above - one of the parameters to `SpriteBach.Begin` needs to be changed.

---

As for the first question:

> What are the performance implications of calling SpriteBatch.Begin/End in all these separate classes so often (once per class per drawing update) versus just calling it the one time each update.

The *main* implication is that you won't be taking advantage of the `SpriteBatch` class that way - in particular you might end up with *many* more render stage changes and draw operations happening on the graphics device than what is really needed.

The reason for this is that the `SpriteBatch` is not just a class for rendering sprites; it also tries to group as many sprites as it can into a single graphics device operation. For instance, if you draw ten sprites in a row using the same texture with the default `SpriteBatch` parameters, the class will actually store the vertices for all of those sprites in the same vertex buffer, and submit it to the graphics device *only once*.

If you `Begin/End` for each `Draw` call then you'd get ten individual draw calls instead of just one. The performance implications should be clear from that.

Also the bit about *using the same texture* is important - as soon as you change to another texture it needs to stop batching, submit all previous vertices that have been batched so far, and start with an empty vertex buffer for the next sprites. This is why to get the best performance when using `SpriteBatch`you should use spritesheets and group as many sprites as you can in the same texture (since changing source rectangle does not count as a change of texture).
> 7 votes

# Answer
I would imagine that creating a new batch for every drawable element of your game would cause a hit on performance because each call to Spritebatch.End() :

> "Flushes the sprite batch and restores the device state to how it was before Begin was called." - MSDN.

But I have no proof to back up the performance claim.

As for which is preferable from a design standpoint, I'd say passing a SpriteBatch around from call to call. What is being drawn should have no idea how or where it's being drawn. What I mean by that is that when you create a SpriteBatch, you can apply effects to the SpriteBatch or redirect the SpriteBatch to write to a different render target for example. If you wanted to blur the whole screen, take a screenshot, or draw a split-screen, it would be way easier if you pass the appropriate SpriteBatch in.
> 0 votes

---
Tags: xna, c#, game-design, architecture, spritebatch
---


# Question
Title: Is there a way to increase the collision check efficiency of a system of n objects?
I'm making a game that consists of many onscreen objects, one of which is the player. I need to know which objects are colliding every iteration.

I made something like this:

```
for (o in objects)
{
   o.stuff();
   for (other in objects)
      if (collision(o, other))
          doStuff();

   bla.draw();
}

```

This has O(n^2), which I'm told is bad. How do I do this more efficiently, is it even possible? I'm doing this in Javascript, and n will usually be lower than 30, will it be a problem if this stays the same?

# Answer
With only 30 objects max, you shouldn't need much optimization at all other than to not check the same two pairs against each other more than once per frame. Which the code sample below will cover. But if you're interesting in different optimizations that a physics engine would use then continue reading through the rest of this post.

What you will need is a spatial partitioning implementation, such as an Octree (for 3D games) or Quadtree (for 2D games). These partition the world into sub-sections, and then each sub-section is partitioned further in the same manor, until they have subdivided to a minimum size. This allows you to very quickly check which other objects are in the same region of the world as another, which limits the amount of collisions you must check against.

In addition to spatial partitioning I would recommend creating an AABB (Axis-aligned bounding box) for each of your physics objects. This allows you to check the AABB of one object against another, which is much faster than a detailed per-poly check between objects.

This can be taken another step further for complicated or large physics objects, where you can sub-divide the physics mesh itself, giving each sub-shape its own AABB that you can check against only if two object's AABBs are overlapping.

Most physics engines will deactivate active physics simulation on physics bodies once they come to a rest. When a physics body is deactivated, it need only check for collision against its AABB each frame, and if anything collides with the AABB then it then it will reactivate and do a more granular collision check. This keeps simulation times down.

Also, many physics engines use 'simulation islands', which is where a group of physics bodies that are close together are grouped together. If everything in the simulation island is at rest then the simulation island itself deactives. The benefit of the simulation island is that all of the bodies inside of it can stop checking for collisions once the island is inactive, and the only check each frame is to see if something entered the AABB of the island. Only once something enters the AABB of the island will each of the bodies within the island need to check for collisions. The simulation island also reactivates if any body inside of it starts to move again on its own. If a body moves far enough from the center of the group, it is removed from the island.

In the end you're left with something like this (in pseudo-code):

```
// Go through each leaf node in the octree. This could be more efficient
// by keeping a list of leaf nodes with objects in it.
for ( node in octreeLeafNodes )
{
    // We only need to check for collision if more than one object
    // or island is in the bounds of this octree node.
    if ( node.numAABBsInBounds > 1)
    {
        for ( int i = 0; i < AABBNodes.size(); ++i )
        {
           // Using i+1 here allows us to skip duplicate checks between AABBS
           // e.g (If there are 5 bodies, and i = 0, we only check i against
           //      indexes 1,2,3,4. Once i = 1, we only check i against indexes
           //      2,3,4)
           for ( int j = i + 1; j < AABBNodes.size(); ++j )
           {
               if ( AABBOverlaps( AABBNodes[i], AABBNodes[j] ) )
               {
                   // If the AABB we checked against was a simulation island
                   // then we now check against the nodes in the simulation island

                   // Once you find overlaps between two actual object AABBs
                   // you can now check sub-nodes with each object, if you went
                   // that far in optimizing physics meshes.
               {
           }
        }
    }
}

```

I would also recommend not having so many loops within loops like this, the above sample was just so you got the idea, I would break it up into multiple functions that give you the same functionality as something like what is shown above.

Also, make sure not to alter the AABBNodes container while looping through it, as that could mean missed collision checks. This may sound like common sense, but you would be surprised how easy it is to have things reacting to collisions cause changes you wouldn't anticipate. For example if a collision caused one of the colliding objects to change position enough to remove them from the AABB of the Octree node you were checking then it could alter that container. To solve this I recommend keeping a list of all collision events that occur during the checks, and then after all checks are complete run through the list and send out any collision events.
> 16 votes

# Answer
Your example test each pair of objects multiple times.

Let's take a very simple example with an array containing 0,1,2,3

With your code you get this:

* At loop 0 you test against 1, 2 and 3
* At loop 1 you test against 0, 2 and 3 ===\> (0-1 already tested)
* At loop 2 you test against 0, 1 and 3 ===\> (0-2 / 1-2 already tested)
* At loop 3 you test against 0, 1 and 2 ===\> (0-3 / 1-3 / 2-3 already tested)

---

Now lets see the following code:

```
for(i=0;i<=objects.length;i++)
{
    objects[i].stuff();

    for(j=i+1;j<=objects.length;j++)
    {
        if (collision(objects[i], objects[j]))
        doStuff();
    }

    bla.draw();
}

```

If we use the array containing 0,1,2,3 once again, we have the following behaviour:

* At loop 0 you test against 1, 2, 3
* At loop 1 you test against 2, 3
* At loop 2 you test against 3
* At loop 3 you test against nothing

---

With the second algorithm we have got 6 collision tests while the previous one asked for 12 collisions tests.
> 4 votes

# Answer
**Design your algorithm around your needs, but keep the implemetation detail encapsulated. Even in Javascript, basic OOP concepts apply.**

For `N =~ 30, O(N*N)` is not a concern, and your linear search is likely to be just as fast as any alternative out there. But you don't want to hard-code assumptions into your code. In pseudocode, you'd have an interface

```
interface itemContainer {
    add(BoundingBox);
    remove(BoundingBox);
    BoundingBox[] getIntersections();
}

```

That describes what your list-of-items can do. Then you can write a ArrayContainer class that implements this interface. In Javascript, the code would look like this:

```
function ArrayContainer() { ... } // this uses an array to store my objects
ArrayContainer.prototype.add = function(box) { ... };
ArrayContainer.prototype.remove = function(box) { ... };
ArrayContainer.prototype.getIntersections = function() { ... };

function QuadTreeContainer { ... } // this uses a quadtree to store my objects
... and implement in the add/remove/getIntersections for QuadTreeContainer too

```

And here is example code that creates 300 bounding boxes and gets all the intersections. If you've implemented ArrayContainer and QuadTreeContainer correctly, the only thing you would need to change in your code is change `var allMyObjects = new ArrayContainer()` to `var allMyObjects = QuadTreeContainer()`.

```
var r = Math.random;
var allMyObjects = new ArrayContainer();
for(var i=0; i<300; i++)
    allMyObjects.add(new BoundingBox(r(), r()));
var intersections = allMyObjects.getIntersections();

```

I went ahead and whipped up the implementation for the standard ArrayContainer here:

http://jsfiddle.net/SKkN5/1/
> 3 votes

# Answer
You should also consider the types of objects than can sensibly collide.

For example the player probably needs to be checked for collision with everything except his own bullets. However enemies may only need checking against the player bullets. Bullets almost certainly don't need to collide with each other.

To implement this efficiently you probably want to keep separate lists of objects, one per object type.
> 2 votes

---
Tags: collision-detection, algorithm, javascript, efficiency
---


# Question
Title: Why do computer games differ so much in size?
There are alot of PC games out there that have (seemingly) roughly the same graphics (with bump-maps, shaders, etc), sound complexity and play-through time yet one of them needs 4GB space while the other 13GB.

Why is that? Why to they differ so much in size?

# Answer
> 30 votes
Most of the size used by any game lies in its assets, most notably, audio, video and (to a slightly lesser degree) images/textures. Binaries and game data is typically much smaller than any of those.

Then, all of these assets may or may not be compressed, may use different compression schemes, may have different formats, and even have different resolution/bitrates.

One game may for instance have large resolution HDR cubemaps while the other uses normal textures. One game may store shadow maps for each environment while the other achieves the same effect by computing the shadow map at runtime. One 2D game may use skeleton animation while the other has the exact same visual output but storing each animation frame individually.

It's pretty easy for two games to appear to have the same order of complexity, when it's not necessarily the case from the asset point of view.

# Answer
> 20 votes
Just in addition to what David already said in his answer:

It is true, that up to 95-99% of almost every modern game size is constituted by its assets: video, audio, textures etc.

*If you are wondering why some games take only 4Gb whereas others much more having same level of graphics??* It can be also due to the fact that **some game store their assets on the hard drive in compressed form and just uncompress those on-the-fly during loading**. This adds some overhead during loading, but same time the total size of the loaded data remains relatively small, since the data is first read compressed and only decompressed as soon as the reading is complete.

**Other games decompress their assets on your hard drives completely and load resources already in "final" format**. This are normally games where the installer size is much lower than the size of your installation. Some resources are so densely packed using some proprietorial algorithms that decompressing results in files being 10 times larger. In this case the assets are stored in non-compressed form and loaded directly into the memory. Here the throughput of your drive can become a crucial point, but there is no additional overhead due to on-the-fly decompression.

Both approaches have their pros and contras: **the storing in compressed form is essential if you can't install the game on a re-writable medium and has to read it from ROM, like DVD- or BR-ROMs (this is often the case for game consoles)** here you must do the decompression on the fly. PCs always have a writable drive (HDD, SSD etc.) so the decompressing in advance is quite common here.

**The complete decompression of game assets can improve game performance allowing it to be started and played even on old computers having not so powerful CPU or GPU.** Game consoles usually have a standardized hardware you can easily test your game on to see if the performance of your game is fine and do some other tricks (like down-sampling your sprites etc.) to reach the necessary performance.

**\[EDIT\]**: How to recognize if the game is uncompressing its assets on loading? Here are some symptoms you might have noticed at some games:

1. The game offers you some way of interactivity while loading data.

* In Mirror Edge version for iPad, this has only 123 Mb you are presented the radio message from the resistance radio in the form of the floating text *á la* Star Wars intro. It normally takes you for 20-30 secs to read the message before a new mission starts.
    * In Anthill this is only 17.1Mb on iPad the loading screen generates funny messages, something like "We are polishing the riffles" etc.
2. The game mimics the "booting" of a normal computer system, giving you some information about the progress of booting.

* A classical example here is the World of Goo, which boots your "Corporation of Goo" computer every time you start it. Again, it is just 80 Mb large -- almost nothing :)

# Answer
> 6 votes
I think the kind of data with the most commonly underestimated size is **audio**, especially **music** and **voice** recordings. This is because audio compression is hard, audio mixing is tricky, and while the eye can tolerate pixelated or blurry textures, level of detail popping, and a few missed frames here and there, the ear is absolutely unforgiving with audio stuttering or clicks.

That said, **videos** can often make for the most storage a game will use.

# Answer
> 0 votes
this is a bit of a subjective question. but still, if you look at the install directory of these games you will straight away be able to see the differences. at a guess the 13gb one will have several gb of movies and audio files.

# Answer
> -2 votes
It's sometimes because of "piracy" reasons. They add padding-files to games so that you have less incentive to illegally download them. If you really want the game in question and pay for it, you will go through the trouble of buying it digitally even though the file is large.

It's also a way for the companie(s) to measure how much interest the IP or franchise still has;

"Do they still want to buy or pirate this game even though it's a very short game yet very cinematic but is about the size of half a bluray-disc?".

---
Tags: optimization, pc
---


# Question
Title: AndEngine Moving a Connected Texture and Physics Body
In AndEngine, many times we create a TextureRegion for our sprite. We can move this region around the scene but when I connect that region to a physics body I end up being able to use either one to move around.

My question is, which one do I move around. Should I use the physics body's position or the Texture?

# Answer
> 5 votes
1) I think this is referenced here, and if not there's a decent community over there to ask. Even a bunch of tutorials/examples documented.

2) If I'm not mistaken I think you should always use transforms/forces to move anything associated with a body to correctly step with the Box2D physics...

---
Tags: 2d, android, textures, box2d, andengine
---


# Question
Title: How can I package and read multiple asset files into/from one file?
I want to somehow "pack" (not compress) multiple game files into one bigger file. Something like Valve's .gcf, where reading from the application should be easy; like accessing an ordinary stored file.

I'm aiming for some kind of simple use, something like:

```
my_asset_file->setAssetFile(ASSET_FOLDER + '/file.ext');
Model *m = new Model();
m->loadFromTxtFile(my_asset_file->openTxtFile('models/props/lamp.obj'));

```

# Answer
PhysicsFS should be able to handle it.
> 7 votes

---
Tags: c++, asset-management
---