title: Match-three puzzle games algorithm

text:
# Question
Title: Match-three puzzle games algorithm
I am trying to write a match-three puzzle game like 'call of Atlantis' myself. The most important algorithm is to find out all possible match-three possibilities. Is there any open source projects that can be referenced? Or any keywords to the algorithm? I am trying to look for a faster algorithm to calculate all possibilities.

Rules:

* Diagonals don't count.
* The size is 8x8

Thanks.

# Answer
> 20 votes
I helped port one of these games to a handheld platform. Looking back at their AI code for finding potentials: yipe, it's complicated, brutish (quadruply nested loop, calls itself recursively occasionally, etc), and it doesn't appear at all cache-friendly at first glance.

(Some of that complexity comes from trying to evaluate the strength of the move in context: valuing longer chains higher, looking for combos, etc...)

But it doesn't really need to be "optimal"; we didn't even touch the code when we ported it. It never showed up on the profiler.

Looking at it now, even at one 32 bit word per cell (and I think they actually used a byte per cell), the entire board will fit in a minuscule L1 cache, and you can do many excess reads on stuff that's cached without impacting framerate too much. *Especially* since you only need to do this whole process once each time the board configuration changes. (A big-theta hovering around `n^2` isn't that horribly bad with a very low `n`, not to mention the small multiplier given the cached memory.)

That having been said: for amusement, let's attempt to parallelize the problem. Starting with bitwise operations.

Assume you have a bitmask representing all of the pieces (we'll call them stones) in a row that are of one particular type (we'll use colors to distinguish types). We'll start only looking at red stones, and worry about the cost of calculating the bitmask later.

```
// Let's assume top right indexing.
// (The assumption is not necessary, --
//    it just makes the left-shift and right-shift operators
//    look like they're pointing in the correct direction.)

// this is for row 2
col index  76543210
color      BRRGYRBR // blue, red, red, green, yellow, ...
"red" bits 01100101

```

We're looking for the series that need just one swap to become a series of 3. Courtesy Kaj, this is one of three combinations, basically: `XoX`, `oXX`, or `XXo` where `X` is a matching stone and `o` is something else.

(This idea is borrowed from the marvelous Hacker's Delight book; see also the fxtbook if such things delight you.)

```
// using c-style bitwise operators:
// & is "and"
// ^ is "xor"
// | is "or"
// << and >> are arithmetic (non-sign-extending) shifts

redBitsThisRow = redBitsRows[2]

// find the start of an XoX sequence
startOfXoXSequence = redBitsThisRow & (redBitsThisRow << 2);
// for our example, this will be 00000100

// find any two stones together in a row
startOfXXSequence = redBitsThisRow & (redBitsThisRow << 1);
// for our example, this will be 01000000

```

It's more useful to know the positions of the missing stones, not the start of the XX or XoX sequence:

```
// give us any sequences that might want a stone from the left
missingLeftStone = startOfXXSequence << 1;
// for our example, this will be 10000000

// give us any sequences that might want a stone from the right
missingRightStone = startOfXXSequence >> 2;
// for our example, this will be 00010000

// give us any sequences that might want a stone from the top or bottom
missingTopOrBottomStone = missingRightStone | missingLeftStone | (startOfXoXSequence >> 1)
// for our example, this will be 10010010

```

(About 1 load and 9 ALU instructions -- 5 shifts, 2 ors, 2 ands -- with a dreadful CPU that doesn't include an inline shifter. On many architectures these shifts might be free.)

Can we fill these missing places?

```
// look to the left, current row
leftMatches = redBitsThisRow & (missingLeftStone << 1)

// look to the right, current row
rightMatches = redBitsThisRow & (missingRightStone >> 1)

// look on the row above
topMatches = redBitsRow[1] & missingTopOrBottomStone

// look on the row below
bottomMatches = redBitsRow[3] & missingTopOrBottomStone

```

(Another 2 loads and 6 ALU instructions -- 4 ands, 2 shifts -- with a bad CPU. Note that row 0 and row 7 may give you trouble -- you can choose to branch around these calculations, or avoid the branch by allocating space for two extra rows, one before 0 and one after 7, and leave them zeroed out.)

Now we have several "matches" vars that indicate the position of a stone that can be swapped in to make a match.

This assumes a "count trailing zeros" intrinsic or very cheap inline method:

```
swapType = RIGHT_TO_LEFT;
matches = leftMatches;
while ( (colIdx = ctz(matches)) < WORD_BITS ) {
   // rowIdx is 2 in our examples above
   workingSwaps.insert( SwapInfo(rowIdx, colIdx, swapType) );
   // note that this SwapInfo construction could do some more advanced logic:
   //   run the swap on a temporary board and see how much score it accumulates
   //   assign some sort of value based on preferring one type of match to another, etc

   matches = matches ^ (1<<colIdx); // clear the match, so we can loop to the next
}
// repeat for LEFT_TO_RIGHT with rightMatches
// repeat for TOP_TO_BOTTOM with topMatches
// repeat for BOTTOM_TO_TOP with bottomMatches

```

Note that none of this bit logic should break down in little-endian vs big-endian environments. It gets much more tricky for boards wider than your machine word size. (You could experiment with something like `std::bitset` for this.)

What about columns? It may be easiest just to have two copies of the table, one stored in row-order and one stored in column-order. If you have getters and setters wrapping board access, this should be trivial. I don't mind keeping two arrays up to date, after all a set becomes `rowArray[y][x] = newType; colArray[x][y] = newType;` and that's simple.

...but managing `rowBits[color][row]` and `colBits[color][col]` becomes obnoxious.

However, as a quick aside, if you do have `rowBits` and `colBits`, you can run the *same code* with rowBits pointing at colBits instead. Pseudocode, assuming board width = board height = 8 in this case...

```
foreach color in colors {
    foreach bits in rowBits, colBits {
        foreach row in 0..7 { // row is actually col the second time through
            // find starts, as above but in bits[row]
            // find missings, as above
            // generate matches, as above but in bits[row-1], bits[row], and bits[row+1]
            // loop across bits in each matches var,
            //    evaluate and/or collect them, again as above
        }
    }
}

```

What if we don't want the bother with converting a nice 2D array into bits? With an 8x8 board, 8 bits per cell, and a 64-bit-capable processor, we might be able to get away with it: 8 cells = 8 bytes = 64 bits. We're locked to our board width, now, but this seems promising.

Assume "0" is reserved, stones begin at 1 and go to NUM\_STONE\_TYPES inclusive.

```
startOfXXSequence = rowBytes ^ (rowBytes << (8*1))
// now all bytes that are 0x00 are the start of a XX sequence

startOfXoXSequence = rowBytes ^ (rowBytes << (8*2))
// all bytes that are 0x00 are the start of a XoX sequence

```

Note this doesn't need one pass per color. In `BRBRBRGY` we'll get a `startOfXoXSequence` that might be something like `0x00 00 00 00 aa bb cc dd` -- the top four bytes will be zero, indicating a possible sequence starts there.

It's getting late, so I'll leave off here and possibly come back later -- you can continue along this vein with xors and "detect first zero byte" tricks, or you could look into some integer SIMD extensions.

# Answer
> 9 votes
You're overthinking the problem. In a single line of 8, there are 6 possible positions for a match-3, so for the whole 8x8 board there are only 96 possible match-3s. Checking 96 possibilities uses an insignificant amount of CPU time. You're probably using thousands times more clock cycles just drawing one frame.

If you're looking for swap-two-adjacent moves that can make match 3s... For each possible position, if there are already 2 pieces that match, there are at most 3 possible swaps that can make a match 3. For one line, there are at most 23 moves to consider, and for the whole board there are 112 moves to consider. Checking 112 moves is also an insignificant amount of CPU time.

# Answer
> 7 votes
There's only a few combinations that can make a match. X.X with one below or above the center (and rotated 90 degrees), and xx. with one to the right or top of the '.' (and the rotated and mirrored on both axes variants. So that makes for 14 different search patterns that need to match a (max 4x3) grid against the 8x8 grid. I'd just brute force and slide the pattern along the 8x8 grid and check if the places where there's an x are the same. If so it's a set that can create a triple.
So basically (for example) slide
. . . .
xx.x
. . . .
or (anotheher example)
. x .
x . .
. x .
across the board - if all three x positions have the same icon it's a possible move.
And that times 14 for all possible moves.

# Answer
> 2 votes
If speed is really an issue, I would say to try something like:

* Iterate the whole grid, starting from top left.
* At every point on the grid until and including the 6th column, check one tile right, and down (you do not need to check left and up because you've done this)
* As you hit the 7th column, only check down. (There is no room for 3 along when there's only 2 columns)
* If they match, then try checking one more tile along/down. If they don't, move to the next tile along.
* When you finish the 8th column, move down a row.

But for an 8x8 grid, there isn't much optimization needed. An easier form would be (similar):

* Iterate the whole grid, starting from top left.

+ At every point on the grid until and including the 6th column, check one tile right, and down (you do not need to check left and up because you've done this)
    + If they match, then try checking one more tile along/down. If they don't, move to the next tile along. Handle out-of-board errors as 'not the same'.
    + When you finish the 8th column, move down a row.

This would allow much simpler code in the for loop, since you do not have an if structure with some code on one side, and slightly tweaked code below it.

# Answer
> 2 votes
It's not very pretty or elegant, but I wrote a match-3 game in JavaScript. Source code on GitHub, you view the match-3 logic right in your web browser: https://github.com/richtaur/bombada/blob/master/htdocs/js/match3.js#L184

---
Tags: algorithm
---


# Question
Title: What is the name of the AI/algorithm used by most MMOs for monsters or mobs?
Is there a standard name for the (fairly dumb) AI that most MMOs use where you 'aggro' a monster/mob when you are within a certain radius of it, and the monster chases your character for a set amount of time or distance when you attempt to run away?

# Answer
I think everyone is on the ball with the name "aggro," however it's probably emergent behavior (side-effects from simple rule systems, e.g. Boids). I would think it would most probably be achieved using a weighted decision tree. To give you an example of why this system would have interesting results consider this:

```
    Start
      |
Player threat (based on player level, distance, DPS, etc.)
Very High  High   Low
|          |      |
Flee       Fight  Pass

```

This decision would then be executed for each player and mob sub-group (Cartesian product) in the vicinity. The entire mob would then follow a decision tree like:

```
    Start
      |
Combined results
More flee  More fight                    All pass
|          |                             |
Flee       Attack own fight result;      Attack individuals
           otherwise, attack the player
           with most fight results.

```
* The mob sees an approaching group of players; and starts moving toward them to attack (threat is low because distance is high). When they get closer the threat becomes too much and they run (i.e. they realize they have bitten off more than they can chew).
* If the players level are low, say one player was given a very high level item and the mob proceeds to attack them. Suddenly one player outputs crazy DPS and the mob flees.
* If one player is more threatening *most* of the mob will focus on him (thus your classical aggro mechanics).
* A team of players takes on a group that they shouldn't be. The mob focuses on individual players to give them a fighting chance; and if they can't defeat the mob a few might be able to run themselves.

The point here is that a very elegant, but predictable, system was built up using two very simple decision trees.

**side note**: Some of the results required mean that re-evaluation should not occur for a specific time limit (e.g. Flee should be applied as a 20s 'Scared' debuff); otherwise you would get *very* strange outcomes (e.g. infinite flee-attack feedback).
> 11 votes

# Answer
Guild Wars just calls it "Aggro", or at least that's what the algorithm's main variable is called, I suppose.

I also found a neat take on it, in the form of a blog post: "Coma AI". I like how the author relates AI complexity to coma levels. So by this definition, it could be called "Coma level 4":

> Level 4 (Confused and agitated) is the standard AGGRO AI. You encounter any creature in Final Fantasy? It will attack you no matter who you are. Even games with advanced AI like Fallout 3 have them. Wandering through the Wastelands, People and Animals will attack me for no apparent reason. There is no way you can talk them out of it. I’m reminded of the epic “I want to heal the wolves” Escapist Article.

But that's obviously not quite what you're looking for.

Unfortunately I've never heard of any official name for it, but I'm not an AI expert by any means. All I know is that I most commonly see it spelled "aggro", which is of course short for "aggressive", which has two g's, not one like you spelled it.
> 4 votes

# Answer
In addition to "aggro" modeling mentioned by Ricket, another common AI state is "leashing". If an NPC gets too far from its spawn point it moves back there and rapidly heals to full. This is to prevent excessive kiting.
> 2 votes

# Answer
It has no real name. It's not any sort of 'accepted' algorithm. It's just cheap and easy to implement as a trivial state machine. If enemy is idle and player is close enough then switch enemy to aggressive. MMOs just continue to use it because it's easy to work with.
> 1 votes

# Answer
AI in MMOs are pretty ignorant. You're dealing with a world where you have the potential to reach millions of players all of varying skill. If AI in MMOs were really present you would see creatures constantly rush attack your healers, then go after the cloth wearers, etc. But we don't see that. We see a system that gives a mob x health and an attack rating depending on it's level, and a faction that it falls under (which makes it attack people whose faction differs). They run (sometimes) when health \< y, and might trigger more mobs to help if condition x is met. The system might do a DX roll to see if the attack/spell hits or not, and goes from there. If one player is attacking a lot (raising threat), creatures turn to that player. So this system is very, very basic. There's not a way for a casual player to flip a 'casual' switch.

From there we do get into some 'advanced' encounters that appeal to the hard-core crowd. But even these are not fully automated by AI -- they're scripted events. Once a high level guild takes a week and figures out how to kill the King of Dreams, then they can pass the encounter details to casual players.

I remember back in EverQuest that you could start a conversation with NPCs and you could trigger different actions by saying certain things! Some linguistic AI.
> 0 votes

# Answer
The first version of this I ever saw was in the ancient roguelike game Moria. Each monster species has a parameter aaf, meaning area-of-affect. If you're outside the monster's aaf, it doesn't move at all.
> 0 votes

---
Tags: ai, mmo
---


# Question
Title: How to create very simple doom like corridors in XNA?
So I have seen many 3D tutorials creating heightmaps and big landscapes but I am hoping there is something simple that i can throw together. If I was to do something doom/wolfenstien-like, do i just draw a cube and texture it? I guess my question is, How should i go about creating a very simple box-like room?

# Answer
> 3 votes
The topic you're asking about is more involved and broad than you might think. Drawing is only half of the problem at that point; chances are, if drawing a room is a challenge, then 3D collision detection is going to be a pretty big task.

I'd highly recommend taking a look at the XNA starter kits and seeing what you can learn from there.

The XNA Starter Kits are available at: http://creators.xna.com/en-US/education/starterkits/

To answer your original question, the XNA Creator's Club website has a code sample for drawing 3D primitives at: http://creators.xna.com/en-US/sample/primitives3D

And this howto (for XNA 1.0, but with the right concepts) is fundamental to moving forward: http://msdn.microsoft.com/en-us/library/bb464051(XNAGameStudio.10).aspx

# Answer
> 1 votes
In theory you can build the entire level in some 3D editor (MAX, Blender etc), export it as a single model and draw it using the methods explained in XNA's 3D game tutorial.

This is not what you want, unless we are dealing with very small spaces.

Usually the world geometry is partitioned for (mainly) the following reasons:

1. Ensure you do not have to push more geometry than necessary to the hardware. There is no poing drawing the entire level if you are inside a room with all the doors closed.
2. Limit the number of polygons you need to test for collision detection etc.

The two main techniques used for this purpose in indoor scenes are binary space partitioning (BSP), used by doom/quake and friends, and portal/cell (of Unreal fame). There are advantages and disadvantages to both techniques. Both are a substantial amount of work to implement from first principles.

I recommend you base your work on an existing engine that does this for you.

# Answer
> 0 votes
If you drew a cube and textured it you would have a cube, not a room. I don't know how XNA define "primitive", but what you should be doing is drawing polygons to form a square or a rectangle for a single wall of your corridor.

---
Tags: xna
---


# Question
Title: How to create an endless scrolling background?
I need to add a scrolling background to a my game, the image is 512x512px. It's for a car game with two way traffic and I want to be able to cross over to the opposite side and drive against the traffic too. The game is in portrait mode and I use cocos2d.

How can I make this in the best possible way?

# Answer
> 7 votes
I'd basically create a 2x2 tilemap where the tiles happen to be 512x512 and all the same. Scroll through it as you would normally but as soon as X gets over 512 subtract 512 (or do a modulo 512 - but beware of negative numbers), same for Y. So instead of one poly you draw 4, although only 1 will be visible most of the time, but on border cases all 4 are visible (when you go 400 down and 400 to the right for example). This way it should scroll on forever.
Of course you can also use 4 sprites instead of a tilemap. One at worldPos, one at worldPos+(512,0), one at worldPos + (0,512) and one at worldPos + (512,512).
Make sure worldPos is always modulo 512 and again it should scroll forever.
Edited to add some code:
Untested, not syntax checked.
Very hardcoded to solve this problem. It would be better with an actual array for a map, but for this specific problem this should work.
Assumes 0,0 to be the top left of the screen.

```
void DrawBG( int worldX, int worldY)
{
   const int tileW = 512;
   const int tileH = 320;

   int worldXMod = worldX % tileW;
   if (worldXMod < 0) worldXMod += tileW;   // handle negative numbers

   int worldYMod = worldY % tileH;
   if (worldYMod < 0) worldYMod += tileH;   // handle negative numbers

   int tileLeft = -worldXMod;
   int tileTop  = -worldYMod;

   int spriteTopLeftY = tileLeft;
   int spriteTopLeftY = tileTop;

   int spriteTopRightX = spriteTopLeftX + tileW;
   int spriteTopRightY = spriteTopLeftY;

   int spriteBottomLeftX = spriteTopLeftX;
   int spriteBottomLeftY = spriteTopLeftY + TileH;

   int spriteBottomRightX = spriteTopRightX;
   int spriteBottomRightY = spriteBottomLeftY;

   // whatever the syntax of sprite drawing or setting its position is...
   DrawSprite(spriteTopLeftX, spriteTopLeftY);
   DrawSprite(spriteTopRightX, spriteTopRightY);
   DrawSprite(spriteBottomLeftX, spriteBottonLeftY);
   DrawSprite(spriteBottomRightX, spriteBottomRightY);
}

```

# Answer
> 2 votes
If I understand you correctly, you can create a set of images. Each image has an entry point and an exit point. To make things easy, you can make all the entry points and exits the same location. Then, you can randomly go between different images so that the player won't encounter a completely redundant level. If you want to mix things up a bit, you could create images that have different entrance and exits. You'll just have to do a little more work to make sure the exit of one image matches the entrance of the next image.

---
Tags: assets, art, cocos2d-iphone, level-design
---


title: Good example of a multi-pass effect?

text:
# Question
Title: Good example of a multi-pass effect?
In XNA (and Direct3D in general AFAIK), rather than creating individual vertex and fragment shaders, you bundle potentially many related shaders into 'Effects'. When you come to use an effect you select a 'technique' (or iterate through all of them) and then each 'technique' has a number of 'passes'. You loop through the each pass it selects the relevant vertex and fragment shader and you draw the geometry.

What I'm curious about though is what you would need multiple passes for? I understand in the early days of 3d you only had one texture unit and then you had 2 and that often still wasn't enough if you also wanted to do environment mapping. But on modern devices, even in the mobile class, you can sample 8 or more textures and do as many lighting calculations as you'd want to in a single shader.

Can the more experienced here offer practical examples of where multi-pass rendering is still needed, or is this just over-engineering on the part of XNA/Direct3d?

# Answer
Any time you're doing post-process effects on a set of captured buffers would be a reasonable time to use a multi-pass effect, i.e. toon outlining, motion blur, SSAO, bloom. The idea being that the first pass would be where you'd render everything out to the appropriate buffers, and each subsequent pass would handle each post-process effect.

Like Ranieri mentioned about the XNACC example, they're using multiple passes to render a huge number of lights. Though in that example, they're executing the same pass, just once for each light.

Keep in mind that Shader Model 2 and before can't handle having anywhere near as many instructions as Shader Model 3 or 4 in each shader, yet another reason to split an effect into multiple passes -- to support older hardware.
> 5 votes

# Answer
As pointed out in the other replies, multi-pass rendering (drawing a single mesh multiple times with different shaders/parameters), as suggested in other replies, is definitely still used, primarily for lighting and special effects

D3DX Effect passes could be used for this kind of thing. But it could also be implemented with more than one shader/effect.

The original intention of passes was to help with implementing complex shaders on lower-end (pre-shader-2.0) hardware, where the restrictions on the number of texture stages and shader instructions per pass were quite limiting.

In the example of multi-pass lighting, are there any significant performance gains to be had by using passes instead of switching effects?
> 4 votes

# Answer
In addition to the lighting thing that everyone mentioned, another major use of this is **blur**. Horizontal and vertical are done in separate passes (so to get a 9x9 blur, only 18 pixels need to be sampled for each output pixel instead of 81). This is used for bloom/HDR, depth of field, glow, etc
> 3 votes

# Answer
The example on the XNA creators' website uses multiple passes to compute lighting from many (hundreds) of light sources.
> 1 votes

# Answer
As Ranieri said, you can use multiple passes for multiple lights, for instance with a single material you may have an 'ambient' pass, an additive pass per point light, another additive pass per spotlight and then a decal pass to multiply in the diffuse texture (I've used a setup like this in the past and it's about the most flexible way of handling a lighting shader I've seen without getting into deferred shading).

Also, I believe most fur shaders use multiple passes.
> 1 votes

# Answer
Shadow maps for creating shadows can be done using multi-pass. Just a note, some multi-pass effects can be done in one pass if the video card supports the same number of texture units as the number of passes. So, if you don't have enough texture units, then you will have to use multiple passes. One fixed hardware platforms (like game consoles), you can probably code just using multi-texturing because you know the number of texture units. But for PCs, there are infinite number of hardware configurations. If you want to have the broadest reach to consumers, you'll probably want to break up some of your more complex effects into multiple passes so that users with lower grade hardware (i.e. don't have as many texture units on GPU) can still see the effect. Briefly, shadow maps are created by first creating a shadow map of the scene from the perspective of the light in one pass. Then the shadow map texture is blended into the scene with the other textures of the scene.
> 0 votes

---
Tags: xna, directx, shaders
---


# Question
Title: How to tell if a glut window has focus from c#
How can I tell if a glut window has focus? Im using c#/tao, Ill use p/invokes if necessary.

Basically I want to ignore input if it doesn't have focus.

# Answer
> 1 votes
Here's the solution I've got so far

```
[DllImport("User32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll")]
static extern IntPtr GetFocus();

public bool HasFocus(string windowName)
{
    IntPtr windowHwnd = FindWindow(null, windowName);
    if (windowHwnd == IntPtr.Zero)
        return false;
    return windowHwnd.ToInt32() == GetFocus().ToInt32()
}

```

# Answer
> 0 votes
I'd guess you have to use the regular win32 func to get the active window handle and compare it to your own. GLUT's focus functions don't behave as expected in Windows as they're based on move over to focus.
https://stackoverflow.com/questions/466354/how-can-i-tell-if-a-window-has-focus-win32-api
Edit: Wait...I assumed Windows. Not sure that's a correct assumption.

---
Tags: opengl, c#, windows
---


# Question
Title: Do Octrees, Kd-Trees, BSP only make sense for static geometry?
I'm still implementing my scene graph (see this question). Now, I wonder if a spatial representation such as a Kd-Tree or Octree to do View Frustum Culling (VFC) only makes sense with static geometry. The reason for my doubt is that usually dynamic geometry is a small part of the scene, while static geometry can be very large, and dynamic geometry forces to handle updates in the spatial representation at each frame.

Your opinions?

Tunnuz

# Answer
Generally I've used a separate partition tree for static and dynamic objects, or just disregarded it altogether for dynamic objects. This provides the benefits of both worlds:

* Static objects require no recalculation of the tree each frame
* Dynamic objects only require the recalculation of a minimal tree

If drawing your dynamic objects all the time doesn't provide too much of a performance hit, it can sometimes be better to just dispense with recalculating a tree for them every frame.

Another optimization is to only recalculate the tree when objects have moved a certain distance or are traveling at sufficiently high speeds, otherwise you'll probably end up with the same tree every frame anyway.
> 9 votes

---
Tags: performance, scene-graph
---


title: Sprite Animation Best Practices

text:
# Question
Title: Sprite Animation Best Practices
I'd like to get a better handle on how people in the real world are handling their animation.

Do you load 1 large image and then draw different rectangles based on the animation frame?

Do you load X image files into an array and draw the item in the array based on the animation frame?

How do you handle having different lengths of animations for various sprites.

Say a character walking takes 4 - 8 frames, and the waves on the beach only take 2 - 3 frames. How would you handle that situation? See Below

```
Dim Waves(1) as Sprite
Dim Char(5) as Sprite

Sub Animate()
     Frame += 1
     Draw Char(Frame)
     Draw Waves(Frame)
     If Frame = 5 Then Frame = 0
End Sub

```

Obviously Waves would end up with an out of bounds error.

Or do you have your sprite worry about it's own animation, and not care about the frame at all. Having each sprite know its own animation loop?

# Answer
> 24 votes
The way I've done it in the past is by separating the **animation data** from **animation playback**. An `Animation` can then become basically an array of `Frames` and a few properties that describe how the animation should behave (if it loops, etc).

I typically load one image and draw pieces of it.

Each `Frame` of the animation is essentially a rectangle and a length of time. This allows for some frames to display longer than others, which may or may not be something you want. If you want all of the frames in your animation to display for the same length of time, store that in your `Animation` object.

Anything that needs to play an animation has its own `AnimationPlayer` which can be pointed to an `Animation`. The player object takes care of playing the animation and makes the "current frame" available.

The advantage to this for me was that I could have a single instance of an `Animation` that many objects could point to and be playing different parts at the same time. It was also easy to change animations by simply pointing the `AnimationPlayer` to a different `Animation` object and resetting the playback.

**Edit**: Here's a fairly basic JavaScript implementation of the system described above. I threw it together in a few minutes as a demonstration. "Real" code would have more features. You'll need a modern browser that supports both Canvas and Data URI for it to work, though.

# Answer
> 1 votes
I would have an animation know how many frames it has. Where and how these are stored is relatively irrelevant except for performance issues (like you might want them in the same texture). I would not add 1 to the framecount ever, I would add deltaTime * animSpeed and convert that value to an integer when displaying. This way you can slow down or speed up the animations and are framerate independent.

So a sprite would have an animation which updates itself.

# Answer
> 0 votes
Why not just have a the number of frames for each of your objects stored? Personally I pass the number of frames in the animation to my objects in their constructors, then I have a standard Animate() function which takes in the amount of frames in the animation.

# Answer
> 0 votes
It depends on the implementation. In my engine, I do animation in both Direct3D and DirectDraw.

In DirectDraw I create one big image. It all gets stored in system memory anyway, which eventually comes down to a one-dimensional block of data.

**Pros:**

* Easy to move between frames. Change the start pointer, add the pitch (the total image width) every y and you're golden.

**Cons:**

* Can't just copy one frame to the screen, you have to do it manually.
* Giant block of memory. Hustling frames around comes at a penalty.

In Direct3D I use separate textures. This is because I have no idea of the texture limitations of a device so I don't know whether it even supports textures that are the size of the entire image.

**Pros:**

* You can copy a frame straight to the screen, because they're all separate entities.

**Cons:**

* Lack of memory alignment.

# Answer
> 0 votes
In my games, I've given my Sprite base class the knowledge about how to draw itself, and all animated elements inherit that knowledge: number and duration of animation frames, position on the screen, etc. The main game loop just iterates through all of the sprites, asking each to draw itself as it sees fit. Seems to work fairly well, and is a little more modular to boot: if you add a new sprite that has a different animation loop (or even more complex: multiple animation states), you don't have to go back and rewrite your Animate() routine to accommodate the additional complexity:

```
Dim Waves as Sprite
Dim Char as Sprite

Sub Animate()
     Char.update()
     Waves.update()
End Sub

```

Each time a sprite's update() method gets called, it knows if it should redraw the same frame as last time, move to the next frame in its current animation, change to a new animation, etc.

This has the added benefit of making it a lot easier to adjust the framerate to accommodate differing clock/platform rendering speeds, because the only change is how often you call Animate().

---
Tags: animation, sprites
---


# Question
Title: What are the challenges and benefits of writing games with a functional language?
While I know that functional languages aren't the most commonly used for game writing, there are a lot of benefits associate with them that seem like they would be interesting in any programming context. Especially the ease of parallelization I would think could be very useful as focus is moving toward more and more processors.

Also, with F# as a new member of the .NET family, it can be used directly with XNA, for example, which lowers the threshold quite a bit, as opposed to going with LISP, Haskell, Erlang, etc.

If anyone has experience writing games with functional code, what has turned out to be the positives and negatives? What was it suited for, what not?

Edit: Finding it hard to decide that there's a single good answer for this, so it's probably better suited as a community wiki post.

# Answer
> 58 votes
I'm currently working on a game in Haskell. I can't speak for functional programming in general, but for Haskell specifically:

# The Good

These are the awesome things that make Haskell really stand out.

* Purity means that reasoning about your code is a lot easier. You don't have to worry about the "current" value of a variable or whether using a given function will conflict with your global state in some way. It also means that parallelism and concurrency are far easier to work with (and in many cases, trivial). These things can be a godsend to game developers.
* Haskell makes it very easy to write at a very high level using abstractions of your own creation. It's often easier to write very generic code than specialized code in Haskell, and the benefits of this manifest themselves in less development time and easier code comprehension. It's more true in Haskell than in any other language I know of that using an interface is like using an entirely new language (while still keeping the benefits of the rest of the Haskell ecosystem). What most languages call language features, Haskell calls a library, and it doesn't feel forced. If you ever find yourself reasoning about your game in psuedocode, you could probably just write a simple interface and make it real code, and it's usually worth it to do so.
* This might conflict with other answers, but Haskell is better at handling imperative code than any other language I know of. The constraints of purity mean that Haskell has a separation between the concepts of "evaluation" (reducing expressions) and "execution" (performing side effects). You can control when and how side effects are performed with an ease unparalleled by the so-called "imperative" languages. Despite what I said about purity earlier, some C bindings are still very imperative (OpenGL, I'm looking at you), so this fine-grained control over imperative code is very welcome. Even the most seasoned of C programmers are likely to appreciate it once they get used to it.
* GHC generates pretty fast binaries. They are not as fast as binaries generated from common C compilers, but are within an order of magnitude, and are *far* faster than what you would achieve with an interpreted language. Even if you can't write your game in other high level languages like Python because it would be too slow, there's a good chance you can do it in Haskell.
* Despite there not being many game-related libraries in Haskell, as noted under "The Bad" below, the Haskell foreign function interface is the easiest I have ever used. You can bind to C by writing almost exclusively in Haskell.

# The Bad

These are things that are not good but can be worked around without *too* much effort.

* The time and effort needed to learn Haskell can be fairly high if you are very used to working with non-functional languages. The language itself isn't very difficult, but when you factor in common language extensions and the huge amount of libraries (remember, many things you might consider language features in other languages are libraries in Haskell), it looks much more ominous. In my opinion, it's worth it, but others may disagree.
* Some people complain about laziness a lot. If you know what you're doing, you will not cause space leaks that are difficult to track down (I have not created a space leak in a couple years now), but beginners have a lot more trouble with this. It would be foolish of me to shoot these people down and claim that this is not a problem, but I will assert that it's a problem that is easily solved with experience.
* There are not many great libraries for making games in Haskell, and not many Haskellers write games in it, so it's difficult to find resources and help on this matter.

# The Ugly

These are things that would take considerable effort to overcome.

* If you are writing a resource intensive game, GHC's garbage collector might bite you pretty hard. It's a generational, stop-the-world GC, so every once in a while you might drop a few frames. For some games this is okay, but for others it's a major problem. I and some other game developers using Haskell would like to see a soft-real-time GC implemented for GHC, but no effort is being spent on that yet, to my knowledge. Currently, I'm not worrying about working around this (and haven't seen any dropped frames from it yet), but at least one other team has resorted to putting their main rendering loop into C.

# Answer
> 19 votes
I've spent the last year developing a commercial game engine in Haskell, and for us, the experience has been overwhelmingly positive. Our game world is complex, and Haskell has made it easy to model the process of conversion from an editor format to a game engine format. I would hate to think what that code would look like in an imperative language.

Space leaks have come up on occasions, and while they've caused a bit of trouble, in the general scheme it has been a small amount (for example as compared with finding deadlocks in a similarly sized Java projects), and once they were fixed, they stayed fixed.

We are using FRP similar to Yampa, and there's certainly a learning curve associated with it, but once that's over with, the experience is very positive. Libraries have not been a problem for us - everything we've needed has been available. Garbage collection delays were a particular issue since it's for an embedded platform. We've used some C++ to manage the animation. Performance has also been an issue with this being an embedded platform (= slow processor). We've done some C and we're also looking at emerging Haskell technologies like accelerate. The C++ animator was a design decision early on and the places where the code is too slow are only very small areas. In the long run, we want to translate all our C to Haskell.

Haskell has made a difficult job easy, and all the difficulties I've just mentioned have been tiny in comparison to the large amount of complex code we've produced that is clean, maintainable and pretty much unbreakable. Parallelism will be an issue in game development very soon, and we are extremely well placed to deal with it. Some of what I've said may not apply to small projects, because we are in this for the long haul, so start-up costs like learning curves, library support, etc, are much less of an issue.

# Answer
> 17 votes
Dave mentions some excellent points, although I have to point out that Haskell has solved both of his issues. Statelessness can be bypassed using the State monad *(EDIT: not really -- see below for details)*, and sequencing can be handled using the IO monad *(EDIT: or any other monad, for that matter...)*.

The challenges you'll have (and that I've had trying to learn both games programming and Haskell), are more along these lines. (These are all Haskell-specific, since I really haven't gone deep with any other FP languages yet.)

* **FP Learning curve:** FP requires a complete shift of mindset from iterative programming. Learning to think in terms of maps and folds rather than loops requires a mental workout if you're not used to it.
* **Mathy learning curve:** Haskell is both blessed and cursed by the mathematical sophistication of its designers, because after you learn the basics of FP, you're stuck with monads, morphisms, arrows, and a whole host of other considerations which, while not tough in and of themselves, are very abstract.
* **Monads:** these puppies are not particularly hard to wrap your mind around, especially if you accept Eric Raymond's statement that they are a "a hack to turn function composition into a way of forcing the sequencing of function calls." Unfortunately (though this is getting better as Haskell gains in popularity), many explanations of monads either aim way over the head of most programmers ("they're monoids in the category of endofunctors!"), or at a completely unhelpful analogy (e.g., Brent Yorgey's distressingly accurate example, "monads are like burritos!" You think he's kidding? That nobody could ever come up with such a goofy analogy in a tutorial? Think again.)
* **Ecosystem:** If you've managed to get beyond all the other bumps in the road, you will be cheek-and-jowl up against the practical day-to-day reality of working with a still largely experimental language. God help you when you get here. Here's where I started seriously jonesing for Scala, or F#, or some other language where there is at least *some* guarantee of interoperability with other libraries. Once upon a time, I got Haskell to link and load the OpenGL libraries in Windows. That made me feel pretty good. Then the OpenGL bindings were re-released, and broke everything I had done. That's life in Haskell-land. Honestly, it can be a pain. You want a wrapper for the Bullet engine? It's in Hackage -- as abandonware from November of last year. You like Ogre3d? Hackage has bindings to only a subset of the library. Bottom line is that if you stick to a language off the beaten path for game development, you will spend a lot more time working on basic plumbing than you would if you just followed the herd and stuck with C++.

The flip side of this is that things are rapidly improving. And it really all depends on what you want out of the experience. You want to build a game and put it on your website to seek fame and fortune? Stick with C++ or Python. But if you want to learn something new that will require you to innovate your processes, try a functional language. Just have a lot of patience with yourself while you're learning.

Antti Salonen has an interesting blog detailing his on-again-off-again affair with Haskell games programming. It's worth reading.

**Edit (one year later):** Now that I've studied the State monad more, I realize it's not a particularly good solution for state that is intended to persist outside a particular function. The real solutions to statelessness are found in Haskell in IOVar, ST, MVar (for thread safety), or through something like Yampa, which uses Arrows and FRP to manage internal state that is nonetheless hidden from the developer. (This list is in order of difficulty, though the first three are not particularly difficult once you understand monads.)

# Answer
> 5 votes
**Objective Caml!**

Using functional languages can be a huge advantage in most types of software development, mostly because they cut development time considerably. I can see a big potential for writing a server backend to a game, or the AI and logic layers on the client, in a functional language. And as everyone knows, LISP has been used for NPC scripting.

If I were to try to write the frontend of a game in a functional language, I would definitely go for Objective Caml, which is a hybrid language. It's an ML descendant, and allows to mix iterative and functional styles, has an objective system with stateful objects. (Caml is the language that F# is modeled on.)

OpenGL bindings seem to work flawlessly and people have been making games in OCaml for a long time. The language can be compiled and is potentially very fast (it famously won over C in some benchmarks a long time ago, don't how things stand now).

There are also tons of libraries. Everything from computer science stuff to bindings to all kinds of libraries.

# Answer
> 4 votes
Not really an answer to anything, but I feel like a discussion of game programming in functional languages is incomplete without mention of Functional Reactive Programming (FRP) - http://www.haskell.org/frp/ \- and its most common implementation (I think?), YAMPA - http://www.haskell.org/yampa/.

# Answer
> 3 votes
As for benefits, check out Clean Game Library (http://cleangl.sourceforge.net/) and check the platformer game. Once you get your head around the syntax (I encourage you to try) you'll see the sheer elegance of the constructs and how closely the source maps to the concepts they're expressing. As an added bonus, the abstraction of state, and the necessity to explicitly pass state around, makes your code much more multicore friendly.

On the other hand, it requires a major paradigm shift. A lot of what you're used to do without thinking about it suddenly doesn't exist anymore and you'll be puzzling how to solve it, simply because you're thinking in the wrong patterns.

# Answer
> 2 votes
From my point of view the biggest challenges will be:

* **Statelessness** of functional languages: The idea in games is that each entity has a state and this state is being modified from frame to frame. There are mechanics to mimic that behavior in some languages (for example functions with a "!" in plt scheme) but it feels kind of unnaturally.
* **Order of execution**: In games some code parts depend on other code parts to be finished before executing. Functional languages generally don't make any guarantees about the order of execution of the arguments of a function. There are ways to mimic this behavior (for example "`(begin...`" in plt scheme).

Feel free to extend this list (and maybe to add some positive points^^).

# Answer
> 1 votes
You can write your code in C/C++ and use an embedded language such as Embedded Common Lisp for your scripting. Although getting these to compile on a different platform might be difficult. You might look at Lisp In Small Pieces in order to learn how to write your own scripting language. It's really not that hard, if you have the time.

# Answer
> 0 votes
I have written simple games in LISP and it was fun but not something I would recommend. Functional programming is all about the end result. So it's very handy for processing data and making decisions but I found it made it hard to do simple clean code like a basic control loop.

I have not learned F# though so it may be a lot easier to work with.

# Answer
> -1 votes
the positive would be **performance** and **portability** and the negative would be **managing complexity**, game today are seriously complex and need tools or programming language that can manage the complexity better, such as object-oriented methodology or generic programming which is hard to implement in functional programming language.

---
Tags: functional
---


title: Creating a working game with Unity3D?

text:
# Question
Title: Creating a working game with Unity3D?
I recently start learning Unity3D and following VTC's video tutorials and others tutorial, so far i've found it very easy to work it and to create stuff, i havent got to the part where i need to script anything YET.

While i still havent hit the scripting part yet i did like to ask:

* Do i really need to script anything to make a simple game with it ? (why am i asking this ? until now from the tutorials i've been watching it seems that unity3d has most of the physics and codes needs to create a working version of a simple game, for example making falling crates, the rigidbody functions, it taking into account flags and grass being touched by the wind and moving)
* What are some simple examples of where will i be scripting for ? (just wondering if there will be something to script for even for a simple game and what would that be)
* When i build the finish project will it compile everything as if it was a VS project and make a working version without the need of any other wrappers for it is data, etc ? (this is sort of self replied by their webpage but i just wanted to confirm if i got this right)

*I am aware those might be subjective questions but while i am unexperienced with it and havent found anything related to those questions yet or havent meet the end of a project to be able to confirm for myself i would like to receive some advices and information in regards this.*

**PS: i did a search but i was not sure of what should i look for to find answer for this kinda of questions so if this is a duplicate of any sort let me know and i will delete it once i am pointed out for the duplicate.**

Best regards.

# Answer
* Yes you will need to script things. Everything is done through scripting. They do have really basic scripts you can use instead of writing your own for some common things like a first person controller, but they don't have any kind of graphical logic editor or anything like that.
* You'll need to script any game logic, enemy behavior, probably player input, menus, which animations to play, when to spawn entities... really anything other than the core foundational stuff they provide like physics and importing assets and such.
* Building a unity app is done entirely through their interface (other than for the iPhone and consoles). So you go to the build settings window, say "I want to make a web version", hit build, and it spits out a preliminary HTML file and a .unity3d file. For the mac builds it spits out a .app, and for windows it spits out a .exe and a folder with all the compiled data in it.

Really the best thing to do is download the free/indie version and play around with it.
> 8 votes

---
Tags: unity
---


# Question
Title: Have any video game designs used non-uniform random numbers in interesting ways?
A variety of video games use uniformly distributed numbers to decide the outcome of an event, such as a "50% chance to hit" almost always means to check if a random floating point number from 0-1 is greater than 0.5. Many games will layer a few of these uniform percentages on top of each other, for instance a D&D hit roll is a uniformly distributed number from 1-20, except that 1 and 20 have special outcomes. To my mind it seems like things like critical hits are added by designers to try and emulate the fact that in reality hitting/missing or winning/losing is not actually a binary outcome.

In many cases the real life amount of "damage" done by an attack would likely be closer to a gaussian/bell curve distribution, which many results in the middle but the occasional very exciting outlier and smooth curve connecting them. Dice games like Settlers of Catan emulate gaussian distributions by adding together multiple independent rolls, but I feel like I've almost never seen this mechanic in video games.

It seems like games like Civilization (Sid Meier talked extensively at GDC about player perception not matching the actual math used in the game) would benefit from results that matched how things work in the real world. Have any video games used a gaussian or otherwise non-uniform distribution of random numbers in interesting ways?

# Answer
> 22 votes
Shooters often use Gaussian random distribution for weapon accuracy. (If you use linear random numbers and you have bullet decals, it's very easy for a player to see that the accuracy distribution is square, which "feels wrong.")

One interesting random selection method that you don't mention, but which shows up fairly often in games, is "random without replacement." This is analogous to drawing cards from a deck; the game runs in random order through a set of possible outcomes (put together with the desired distribution) and then "reshuffles." This is done to reduce the chance of lucky or unlucky streaks.

# Answer
> 9 votes
I use Poisson distributions quite a bit - mainly when trying to work out the number of times that a random event should occur within a period of time.

This has the nice property that the distribution of events if you have two 1 second timesteps is the same as one 2 second timestep, so great for simulations with variable-length time steps.

# Answer
> 8 votes
Something that I have done in the past and that World of Warcraft currently does is to increase the chance of a random event based upon the number of tries since the last successful event. That is for instance, a quest item may have a 20% drop rate on the first NPC kill, a 22% on the 2nd, a 25% on the 3rd, resetting back to 20% when it does drop. I implemented a tech tree where the chance to discover a tech increased each turn until it was on the order of a 99.9% chance of occurring.

# Answer
> 7 votes
Random encounters in RPG-s are often non-uniform.

```
Set X to a random integer between 64 and 255.
For each step in plains, decrement X by 4.
For each step in forest, swamp, or desert, decrement X by 8.
When X < 0, a fight ensues. Go to step 1.

```

This makes encounters more realistic because animals/trees etc. like to have some space between them.

# Answer
> 2 votes
I've seen critical hits in some action-RPGs before, but usually for action-based games the numbers are kept intentionally simple for a reason: the player is busy running and jumping and dodging and shooting, and they really don't have time to do probability calculations in their head.

So, you're more likely to see non-uniform numbers in things like turn-based strategy games. A typical example are "rogue-like" games (Nethack, Angband) which have non-uniform weapon damage -- one weapon might do 3d5 damage for example, and another does 4d4, and the game will tell you these numbers and it's up to you to decide which one is better (factoring in other variables like weapon weight, character proficiency, etc.)

# Answer
> 2 votes
League of Legends has a hero named Gangplank with an attack that used to have pretty much uniform distribution which they changed to a gaussian. There is a circle area of effect where multiple hits may occur and they decided to make it cluster towards the center.

---
Tags: game-design, random
---


title: How is game difficulty tested/balanced?

text:
# Question
Title: How is game difficulty tested/balanced?
How is game difficulty typically tested or balanced so that there's a steady progression of difficulty; how do I ensure that no level is too difficult or too easy for its point in the game?

Are play testers of various skills brought in, or a random sampling of people? What considerations are/should be taken into account during the actual level design process?

# Answer
> 16 votes
Two big helps in difficulty tuning.

**Metrics**

Tracking player data can go a long way to making difficult tuning as objective a process as possible. How long are people staying alive, where are the taking damage or getting killed, how many tries does a section of the level take. Getting good metric data can really help your team see where people are having issues in your game.

**Kleenex Testers**

The longer your QA staff plays the game the better they get at it, so it's good to have sessions where you grab new people who have never sat down with the game and have them go through it.

# Answer
> 9 votes
Watch someone play but don't talk to them. By not talking to them, you can see things them do things that will make you pull you hair (You: *the solution is obvious. What's wrong with you? #$@!*).

Instead of saying your thoughts aloud, write down what you want to say. Use this as your basis to guide your game difficulty.

# Answer
> 4 votes
Ensure that you change the people playtesting your game. We shipped a title for the original PSX that was far too difficult (far too tight time limits) as we'd had all the same playtesters testing the game over the development period so they knew the levels backwards.

# Answer
> 3 votes
Some games adjust the difficulty based on the skill of player during the game.

For example every time a player dies at a level - difficulty decreases. Every time he finishes - difficulty increases.

Still this needs some testing to get the decreasing and increasing right.

This method makes the scoring a little less accurate and harder to compare with others but the game more enjoyable as you won't get totally stuck.

# Answer
> 3 votes
an idea I've seen mentioned elsewhere is to sit pairs of people in front of the application\[game in this case\]. They're more likely to reveal their thought processes to someone else watching and the 2nd person may ask questions without leading them like you or another team member might.

# Answer
> 2 votes
First a quality assurance pass is needed to make sure the tasks are reasonable and completable by your internal QA.

Now do a sweep on initial difficulty and/or level times, rinse and repeat until diminishing returns mean you need to move on.

The next step is to use all the other internal staff you can grab for a few play-thoughs. Be sure to record as much as possible for later analysis. Sweep, iterate, repeat.

Families are a good next line if your on a budget, after that you need to bring in focus groups or outsource testing.

Remember do small chunks, iterate and repeat.

---
Tags: game-design, testing, balance, difficulty
---


# Question
Title: Profiling code with threads and script interpreter
Basically, how I profile a game that have multithreading and script interpreter? (Lua in my case)

I have no idea of where to look for that.

Also it would be nice to be able to profile code that resemble somehow the release code, my "debug" binary is about 12 times bigger...

EDIT: My game was made with C++, compiled with GCC, runs on Windows and GNU/Linux for now, compiled natively (ie: MingW on Windows, regular GCC on GNU).

# Answer
> 1 votes
Until we have a few more specifics on your platform/OS/compiler, it's going to be hard to answer, but in the mean time, look at this answer to "In general how often and when should I optimize my code?" for some generic suggestions.

Most of these suggestions will work equally well in optimized (release) or non-optimized (debug) builds.

(I'll return and update this answer with more specific tools and ideas if you update the question with more details.)

---

Edit: okay, more specific suggestions.

Take a two-pronged approach. One, do exactly what Simon is suggesting -- build a lightweight "stopwatch" timer into your code. It doesn't have to be pretty to start with -- as my link above suggests, you can always "drill down" from coarse info to finer-grained info.

Second, take advantage of the free (gratis) tools. Even if you don't get exactly the info you want, scope out a sampling profiler such as AMD CodeAnalyst. This shouldn't have problems with threads, and should be capable of giving you a "code was often in this place" readouts, or even full stack traces. While it may be a little harder to reason about the masses of data you'll get here, chances are you'll see something, and it has the advantage of being non-intrusive. If you have an AMD processor CodeAnalyst will even do the performance counter stuff for you, giving you access to e.g. cache miss and branch prediction info.

It might be fun to take valgrind's cachegrind, callgrind, or massif across the project. This is definitely going to slow things down but you may learn a lot. The valgrind memcheck module is worth knowing about too.

You may also want to investigate the GCC's intrusive gprof. Sampling profilers are generally observed to be a better idea (they don't alter what they're looking at quite as much), but you may also learn something from gprof's complete instrumentation that you couldn't see using sampling.

None of this gives you great visibility into the lua parts. You'll get stack samples or call info from within lua, and you might be able to infer what it's doing with per-line or per-instruction samples. But it may not be easily decomposable into "which scripts took the most time" or "which line of this script is giving us the most trouble". For that you'll need to either look into a commercial lua engine, or just extend your stopwatch tool a bit...

(There was a game middleware company offering a fully custom lua engine with profiling and debugging tools, can't find them now... There's also lua profiler, googling around a bit. Not sure if it would fit the bill, but it seems like there are others too.)

If you're willing to take the time to play with CodeAnalyst, valgrind, or gprof, chances are you'll learn something -- if not about your code, then about profiling in general, which you might use to enhance your own custom solution. =)

# Answer
> 1 votes
I have a home-made profiling system that consists of profile-probes that I've injected on a lot of none-inner-loop places in my code. The probes are initially disabled and I just enable the ones that I want to check up on. The system simply throws out the information to a .txt file (or a network stream) that I then use another language to parse the output from and present the data in a more user-friendly way. The probes are globally initialized upon creation and only when recording them creates any data.

The benefits of this is:
* While enabled (even in release builds), the system is light on cpu cycles and you'll most likely not notice any performance hit while all probes are disabled.
* While disabled (final build), the system is reduced to 0 cost (like most home-brewn profile-systems).
* It can measure time, hits, record callstacks, print variables, so it's flexible and can be used for most debugging that you'll need.
* It's dynamic, you can get exactly the information that you want from it.

On the negative side: It took nearly 2 days to implement so it's fairly complex. It'll likely make up for that time though.

Examples for usage:
* Timescoping
* Memory allocations (sizes, names, etc).
* Resource tracking
* Debugging (conditional prints).

---
Tags: optimization, scripting, multithreading, profiling, profiler
---


# Question
Title: How can I record my vector graphics game without  blurring the graphics?
A lot of people asked for a trailer for my game, because screenshots do not do it justice. I have tested PlayClaw, Fraps, CamStudio, VirtualDub, and some other minor tools; none have produced a viable result. My game uses vector graphics and is designed to run at 60fps, so lossy compression of a regular screen capture video destroys the graphical appeal.

How can I record gameplay without blurring my graphics and slowing down the framerate?

# Answer
Basically, the issues were:

Quality on a vector-based game. CPU amount taken. I/O bottleneck.

What software to use for editing.

To solve quality, I needed a lossless codec, or no compression. The lesser the compression, the more I would have I/O problems, but the more CPU I took, the more I would have CPU problems (doh).

The solution, was use a RamDrive to solve the I/O bottleneck, thus now I was left mostly with how much CPU I wanted to take (ie: the smallest as possible). Thus theoretically the best would be no compression at all, but no compression at all on a ramdrive hit space available problems...

So I researched, and found that the fastest lossless codec (don't matter how much it actually compress), and it was CamStudio Lossless

The software I used, was VirtualDub (CamStudio itself cannot capture the window contents, it capture the entire window, thus wasting space).

Now editing software: Well, noone here gave a good awnser, and neither I will do, but other lists can be found in other places.
> 1 votes

# Answer
Make your game framerate independent, so you can set it to play with a fixed timestep. Play your game, record the input. Replay with fixed timestep, recorded input and write every frame to a file - since you replay with fixed timestep it doesn't matter how long writing out a frame takes. That way your source footage is uncompressed and you can decide on quality later without having to sacrifice speed, or having glitches because of a capture program. After that things like After Effects come in - at least you'll have crisp source material.

Edited to add: yeah, I know, making it framerate independent to play back at a fixed timestep is silly. Duh. Well, if it's framerate independent fraps might be less of a problem as well ;o) Games should be framerate independent anyhow!
> 22 votes

# Answer
This article on Pixel Prospector may be what you need:

How To Record And Edit Gameplay Videos

The game used in the video is NeonPlat 2, which also uses vector graphics.

The article covers everything, from capturing to editing.
> 8 votes

# Answer
For recording your game footage, you could try CamStudio, which is free. I find that it doesn't work with games in full screen mode though, so you'll want to run your game in a window.

As for making the actual trailer, you'll want some video editing software. There are several expensive commercial options, but if you're looking for something free, your choice is more limited. You could try Windows Movie Maker, or iMovie if you have a Mac, but the best free video editor I've found is Blender, more widely known as a 3D modeling and animation tool. The UI isn't intuitive, but if you spend some time to learn it, you'll also get your hands on a pretty good video editing tool.
> 4 votes

# Answer
My best experience is with Fraps but I used the full version (it seemed like a small one-time prize to pay for a great utility) which has no limits or logo. You can set the framerate beforehand, as David Young suggested in his comment. Like many video capturing tools, Fraps uses a low-cost compression during while it's recording which then can be converted to a higher compression format of your choice. For this i usually use VirtualDub.

I had no problem running Fraps behind my game at full speed (50fps in my case) getting high quality captures.

The key issue here is that capturing requires some performance, and you should always try to to it on the best computer available. More specifically, the capturing tool makes substantial and continual disk writes so choosing to store the file on a fast hard drive is key. Laptops often come with slower-access hard drives so this may affect performance a lot. Using a smaller frame size during the capture gives the hard drive an easier time and could keep your framerate up. Fraps allows you to set half-size frames.

In the case of Fraps, the quality of the final movie is greatly affected by what compression you use when converting the FPS1-encoded capture AVI to a distributable format. If you don't consider lossiness here it will of course not matter how well the capture tool performed.

I seriously don't think that the programs you mention are generally that bad, but need some configuring before they perform optimally together with you specific game.

---

Saving every individual frame in PNG is probably not a good idea if you already have problems with speed. It would likely eat more CPU and disk time because it would need every frame to be stored with all its information. When encoding and storing a movie many encoders use a number of key-frames which are complete and let successive frames after them be defined as the difference between one frame an the next. This can be a huge reduction in size but it does not let you take out one frame and read it without the key-frame.

Not only will the size of each frame be larger if you try to dump them to separate files, but you will also get an overhead from the file access itself. This is because you must open a new file handle for every frame instead of holding on to and streaming to one file like in the movie case.

Your best bet is still with recording a lossless movie and extracting the frames from it, OR to capture a finite number of frames like screen-shots during play.
> 3 votes

# Answer
Devices like these are super cheap, and I bet you can get a hold of a second computer to run it on (it doesn't need anything special) so you can capture your game from your game running machine (be sure to have a computer with S-Video out for this cheap version). There is also something like this for higher quality capture - http://www.blackmagic-design.com/products/intensity/ but requires USB 3 and is more expensive, but you can capture HDMI and higher resolution. I really see no better option than either of these two.
> 2 votes

# Answer
If on Windows, record using PlayClaw if you want a game video without barely slowing down your computer. On Linux you have glc.
> 1 votes

# Answer
I've used Windows Media Encoder a couple of times to record videos of my games and tools - it's free and produdes good quality videos.

Although, I've wondered the same question too, because recording a video is only half the process (if that). The other half is editing it, adding effects, etc. Windows Movie Maker kinda works but it's fairly simplistic... and crashy.
> 1 votes

# Answer
I haven't used it, but you might want to try Taksi.
> 1 votes

# Answer
You might want to try vnc2flv, but it won't do audio itself (you can add in an audio track later though). Not sure if your CPU will hate you trying to do realtime FLV encoding alongside a running game though.
> 0 votes

# Answer
It probably sounds obvious, but... Don't full-screen your game while you're recording the video otherwise it will 'obviously' be incredibly slow because it captures your screen resolution. I'm guessing this is what you're being bit by.

FRAPS will take care of this just fine. So will many others but I found FRAPS the most convenient and easiest to use.

I used FRAPS to record and Windows Movie Maker to put together some maps I made in Starcraft II -- example.
> 0 votes

# Answer
Here's what I've done in the past to make video-only trailers:

1. Make your game runnable with a fixed time step. That means passing in the time between now and the last frame explicitly rather than calculating it internally to your game loop.
2. After rendering a frame, dump it out to a lossless picture format such as .tiff with the frame number as its name. This makes it easy for another app to encode a series of pictures into a movie.
3. Dump into the appropriate video encoder (I wrote a simple one using DirectShow) to convert to .avi or whatever video format you want.
> 0 votes

# Answer
the best way is make your game self recordable. Easy way is just save every frame with fixed framerate. With SSD it takes "no" time. Harder way is to make your own "fraps". If You do it. You can directly communicate with your game.
> 0 votes

# Answer
I've made a trailer recently for my game. I was somewhat helped by the engine, that allows for screenshots fast enough to actually animate. What I did:

* Although I did not fixed the framerate, the captures were made at fixed intervals, 25 per second. I recorded my game session, which generated thousands of images on the drive.
* I then imported these images into a clip in kdenlive
* Added some titles, music, logos, fades in and fades out to give it a more pleasant look

Actually capturing the images directly meant that I could not get the sounds from the game, but got a much better quality of images. Adding some music more than made up for it.
> 0 votes

# Answer
If you have two PCs use skype's screen sharing feature. Play the game in one PC then use the other to capture the video. This way you won't affect your game and resources won't be scarce for the video capture program.

Conversely you can buy a video capture card for your PC.
> -6 votes

---
Tags: marketing, trailer, video, screen-recording
---


title: Authoring Hitboxes

text:
# Question
Title: Authoring Hitboxes
What sort of tools/processes are used for setting up hitboxes and make them move/resize/appear/disappear to match the character animations? I'm working in 2d, so attaching collision volumes to the character in a modeling program are no good for this case :).

# Answer
This may be much heavier than you need, but here's how we do it. We stick to AABBs for simplicity... (The terrain is more arbitrary than AABBs, but almost all objects stick to AABBs. They might be bigger or smaller than the sprite, but it works quite well with some tuning!)

The pipeline supports several types of box:

* **collision**, a single 2D AABB for interacting with terrain features (a relatively simple SAT engine)
* **attack**, zero or more numbered 2D AABBs for determining where damage will occur
* **vulnerability**, an optional 2D AABB for overlap testing with attack boxes (if A's attack box connects with B's vuln box, it's a hit!)
* **attack select**, zero or more numbered boxes tested against either collision or vulnerability boxes to determine if AI should trigger a specific attack type
* (you can also add additional named box params if this doesn't suit your needs)

Each of these boxes is per-frame, per-animation. If they don't change across an entire anim we only store them once with the first frame and a note that they repeat.

The artist/designer-facing tool, which aggregates all the sprites and a bunch of metadata, will help you with the collision box. In *automatic* mode it will simply snap the collision box to the "outermost non-transparent pixels" in a given sprite frame. In manual mode you can tweak the box however you like. There's a "magic wand" button for snapping it back to the outermost non-transparent pixels again.

You don't have to have any given box for any given frame if you don't want it.

(Note: it's also useful to track a "reference point" for sprite placement -- you can treat your character coordinates as bottom-center, or maybe you're dealing with a button and you want to place based on the center of the sprite, etc... Helps with setting up UIs and uniformity in moving characters around -- characters are usually hauled around by bottom-center.)

This info is exported into an intermediate xml-based format, and then baked by a subsequent tool into a binary format appropriate for the target platform.

All of these reach the game and then use a simple quadtree-like space partition system to do their testing vs. one another.

It's definitely possible to add a deeper pass to do pixel vs. pixel tests after the AABB pass if you need it.
> 3 votes

# Answer
What tool are you using for authoring your sprites? If you're using GIMP or Photoshop, you can easily have the artists paint hit areas as a separate named layer. You would then write a tool as part of your content pipeline to:

* extract the layer in question from each sprite sheet directly from the PSD/XCF file.
* for each sprite area in the sprite sheet, search for the non-zero pixels in that sprite area and generate a bounding box
* associate the bounding box with the sprite descriptor.

The PSD format can be found here: http://www.wotsit.org/list.asp?search=PSD&button=GO!

Of course, you could always have the artists export the layer manually to a standard file format that's easier for your tool to read, but we all know how artists love having manual processes forced down their throats :)
> 4 votes

# Answer
One easy/semi-hacky solution is to not use hitboxes but instead do a pixel test for you given sprite. Basically you set up some alpha threshold and if the alpha value of a given pixel closest to the area you need to test against is greater than that, you've collided with it.

A better approach I've used in the past is to just set up an array of points per tile (in your case, per frame) that signifies where the edges are. You generate line segments out of that and do arbitrary n-gon testing for your collision.

Barring that, you'll probably have to write your own solution to save out exactly what you're suggesting, i.e. bounding volume type x with properties y at location z for sprite w. It heavily depends on what your specific needs are.
> 1 votes

# Answer
I would use an aabb-point test to single out which model(s) that I'm potentially hitting, and then do a pixel-test on those models.
> 0 votes

---
Tags: collision-detection, animation
---


title: How to handle font loading?

text:
# Question
Title: How to handle font loading?
I need to display text in my game, who doesn't.

I had originally thought that I could just statically render all the text I would need to images and use those. I'm starting to think that is a bad idea. I figure I'll have to internationalize it in the future, and the game has score counters and such which cannot be statically rendered. It looks like I'll need to use a more dynamic approach.

So my question.

How do games usually handle font loading?

* Load the TTF directly and render it to a texture atlas.
* Pre-bake the TTF into an image with a configuration file storing locations and kerning.

# Answer
This is what you're looking for:

http://www.angelcode.com/products/bmfont/

Used by numerous games, from indies to AAA titles, to create bitmap fonts from TTFs

Using this tool or something similar is probably the most common way to implement font rendering in a game. Other options do exist (e.g. rendering vector fonts directly with something like FreeType), but the simplicity and performance of bitmap fonts usually makes them the obvious choice

(Note that Valve's distance-field stuff is super-sweet for extreme magnification of text, such as the examples of decals in an FPS, but of little or no benefit for UI text, which is often being scaled down from the source texture, or maybe scaled up just a little)
> 6 votes

# Answer
If you are working with something that supports shaders and reasonably large textures, Valve has a technique for font rendering that scales very nicely and has minimal memory cost compared to other methods.

http://www.valvesoftware.com/publications/2007/SIGGRAPH2007\_AlphaTestedMagnification.pdf

If you need Unicode support, you can split the font textures up by codepage block or whatever. I believe we found that even fairly complicated kanji were readable at small-ish prerendered sizes (128x128 and 64x64).

If you are trying something more complicated, like Arabic, or Devanagari, you are pretty much screwed, no matter the method you choose. There's no way to render arbitrary text in some languages efficiently in real-time, and you'll end up needing to render character digraphs/trigraphs/whole words at once.
> 8 votes

# Answer
One important question is how many languages you plan to support. If you are going to need to support things like Arabic, you are pretty much stuck with freetype (which speaks TTF) since rewriting Arabic kerning rules is probably up there with writing your own GPU driver in terms of pain.
> 4 votes

# Answer
Distributing the TTF is usually significantly more expensive (money wise) than other licensing schemes, so the games that do that are pretty rare. See also this thread. You don't want to make a Unicode font yourself.

Most implementations I've seen follow something like what you suggested in your second bullet point. A lot of modern AAA games, though, are starting to use Flash to render all their UI elements and I'm not entirely sure how that handles its fonts.
> 2 votes

---
Tags: textures, fonts
---


# Question
Title: Fastest way to create a simple particle effect
I am looking to the fastest way to create really simple particle effect that will be spammed like hell on the game...

Basically, my game looks like a vectrex game, made mostly of lines... I want to make some small explosions that will be really common.

There are something faster than just moving around some points and rendering with GL\_Point?

# Answer
> 7 votes
I made several tests, and the FASTEST way (not the fastest to code) was particles made of GL\_LINEs that knew their position and speed, and used that as the points when rendering (so, the faster the particle go, the most "line" it becomes, the slower, it becomes a point).

The effect is REALLY cool (look at any geometry wars video to see it), and REALLY fast too. Kick the crap out of quads (specially because quads would make me need to calculate the double amount of vertexes)

Also, it is better than using a already done particle system, because I wanted a specific and FAST effect, particle systems usually support lots of features, with proportional amount of overhead.

# Answer
> 13 votes
There's really no need to store memory for every particle and animate each particle separately. You can do it procedurally by reconstructing the particle position during drawing by using the classic physics equation. s = ut + 1/2.a.t^2

A simple example (without constant acceleration of particles):

```

void drawExplosion(ExplosionParameters& s)
{
  Random rng;
  rng.seed(s.startSeed);
  glBegin(GL_POINTS);
  for (int i = 0; i < s.numParticles; i++)
  {
    vec3 vel = rng.getRandomVector(-1.0f, 1.0f) * s.explosionSpeed;
    float timeBias = rng.getRandom(0, s.particleTimeBias);
    vec3 pos = s.explosionCentre + (vel * (s.timeElapsed + timeBias));
    glPoint3fv(&pos);
  }
  glEnd();
}

```

Then you simply increase s.timeElapsed on every iteration of your update loop.

It is also completely amenable to being implemented on the GPU thus freeing up your CPU from having to do any work. A gpu implementation might look like this:

```
void drawExplosion(ExplosionParameters& s)
{
    //bind Vertex Shader If Not Already Bound();
    ...
    // bindVertexBuffer of Zeroes If Not AlreadyBound();
    glVertexPointer(...)
    //uploadShaderUniformsForExplosion(s);
    glUniform3f(...)
    ...
    glDrawArrays(GL_POINTS, 0, s.numParticles);
}

```

The GPU vertex shader would then reconstruct the particle position via the physics equation and the uniforms/constants passed to it - just as the CPU version did.

To add some variance, you can use more simultaneous explosions with slightly differing parameters, animating colors/alpha, choosing differing starting positions. etc.

# Answer
> 6 votes
Normally I think you would do particles as texture-mapped quads. Treat them as 2D sprites basically, and fade them out over time, destroying them when invisible. Better still, reuse the old ones when you make new ones so you're not thrashing memory for these things.

If you use premultiplied alpha on the art then you can easily support lights, fire, smoke, and more besides all with one type of blending operation.

# Answer
> 4 votes
With OpenGL ES 2.0, ES 1.X with an extension and OpenGL =\> 2.1, you can use GL\_POINT\_SPRITES. GL\_POINT\_SPRITES are like a quad always in front of camera.

In fragment shaders, you can:

* define sizes of sprite with gl\_PointSize in vertex shader
* use gl\_PointCoord (uv coordinates) in fragment shader

You can use texture with alpha to draw ball sprites...

A tutorial for Point Sprites

# Answer
> 1 votes
Most particle effect systems I've seen, instead of drawing a *huge* number of points, draw a relatively smaller number of billboard textures where each textures looks a bit like an explosion. Unless your art style really prevents, you'll likely be happier going down that route. It will minimize the amount of particles you need to individually animate and render while still give a big visual effect.

# Answer
> 1 votes
For a neat little way to handle the spawning/deletion/update of particles, assuming you have a simple array of particles - Particles\[MAX\_PARTICLES\]:

Keep track of the active particles (starting with NumActiveParticles = 0)

New particles are always added at the end of the array:

```
pNewParticle = &Particles[NumActiveParticles++];

```

The clever bit - When removing a 'dead' particle - swap it with the last active particle, and decrement NumActiveParticles:

```
if ( DeadParticle < NumActiveParticles-1 )
{
  Particles[ DeadParticle ] = Particles[ NumActiveParticles-1 ];
}
NumActiveParticles--;

```

This avoids any searching for 'unused particles' when spawning, and avoids any scanning through an array of MAX\_PARTICLES if none are in use.

Note that this only works if the update/render order is unimportant (as is the case for many particle effects, which use additive blending) - as this method of deleting a particle re-orders the array

# Answer
> -1 votes
The fastest way i would assume is to find a particle engine and use that for your effects. Here are a few:

---
Tags: graphics, opengl, graphics-programming
---


title: Web site for XAML snippet sharing?

text:
# Question
Title: Web site for XAML snippet sharing?
I am making a game with WPF and C#, and I frequently am in need of artwork for it. Some things could be easily shared, such as explosion animations, exhaust plumes, etc. I was wondering if there are any good web sites for this? All I can find are tutorials and the infrequent sample, but I imagine there is a site out there that I am missing. I would also like to clarify that I am looking for pure vector based XAML snippets. I know there are a lot of sites out there for sprites and textures, but I am looking for XAML components that I can tweak.

# Answer
I don't know of any sites specifically for this, but the XAML icon pack that comes with VS2010 is a good starting point. See also: https://stackoverflow.com/questions/315819/source-for-xaml-toolbar-icons . These are not game related -- but considering how few WPF games there are out there, you gotta take what you can find.

Illustrator makes it very easy to export XAML (Inskscape also has a XAML export feature, but in my experience it's very buggy, borderline useless). There's also tools to convert Flash to XAML, if you have Flash and prefer that workflow. If you want to go 3D, there's a XAML exporter for Blender (probably other 3D packages have them too). And don't forget Blend (the trial lasts for a long time!).

Finally, there are also a lot of open-source WPF apps to check out. I'd guess 95% use bitmap rather than vector graphics (mainly because vector rendering *will* slow things down), but some might have XAML graphics. Also, the legality of this is questionable, but if you find a really cool effect in a closed-source app, you can use .NET reflector + BAML Viewer to check it out -- don't copy/paste it, but it can't hurt to look for a little inspiration.
> 1 votes

---
Tags: graphics, animation, wpf
---


# Question
Title: How do i create bounding boxes with XNA 4.0?
I am having some trouble making bounding boxes for my models I am using within XNA 4.0. The way it was done in XNA 3.1 seems to be obsolete as you can no longer access parameters that were used before in XNA 3.1. Has anyone got any decent links I have been looking around the net for a while now and all I am finding is things for XNA 3.1 or below.

Help much apprechiated. Regards Mark

**EDIT:**

Hey, the problem i am having is getting the min and max points for my model i load through the content pipeline. as articles i have seen on how to do it tell you to do such things as `VertexPositionNormalTexture[] vertices= new VertexPositionNormalTexture[mesh.VertexBuffer.SizeInBytes / mesh.MeshParts[0].VertexStride;` but i can no longer call size in bytes and vertex strides within XNA 4.0

# Answer
> 13 votes
I have encountered the same problem yesterday. My solution is this one, it is vertex type independent and works quite good.

```
protected BoundingBox UpdateBoundingBox(Model model, Matrix worldTransform)
{
    // Initialize minimum and maximum corners of the bounding box to max and min values
    Vector3 min = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
    Vector3 max = new Vector3(float.MinValue, float.MinValue, float.MinValue);

    // For each mesh of the model
    foreach (ModelMesh mesh in model.Meshes)
    {
        foreach (ModelMeshPart meshPart in mesh.MeshParts)
        {
            // Vertex buffer parameters
            int vertexStride = meshPart.VertexBuffer.VertexDeclaration.VertexStride;
            int vertexBufferSize = meshPart.NumVertices * vertexStride;

            // Get vertex data as float
            float[] vertexData = new float[vertexBufferSize / sizeof(float)];
            meshPart.VertexBuffer.GetData<float>(vertexData);

            // Iterate through vertices (possibly) growing bounding box, all calculations are done in world space
            for (int i = 0; i < vertexBufferSize / sizeof(float); i += vertexStride / sizeof(float))
            {
                Vector3 transformedPosition = Vector3.Transform(new Vector3(vertexData[i], vertexData[i + 1], vertexData[i + 2]), worldTransform);

                min = Vector3.Min(min, transformedPosition);
                max = Vector3.Max(max, transformedPosition);
            }
        }
    }

    // Create and return bounding box
    return new BoundingBox(min, max);
}

```

All calculations are done in world space, this gives you world space bounding boxes (which is quite common for AABBs). Since it is quite expensive (but still performs good in real-time) just update it on dynamic objects and only when a rotation is performed (you can just translate AABBs with objects if that is the only transform).

---
Tags: xna, c#, bounding-boxes
---


# Question
Title: What are the hot dev positions in game industry?
What are the hot postions which are hard to get in game industry? Client/Server/Game Engine/Networking and database or else?

# Answer
> 10 votes
Technical artists are rare as hens teeth. That is, someone who is primarily an artist, but who can also script/code and understands the shader tech underpinning the art stuff.

Also, good shader graphics programmers are still pretty rare, i.e. someone who can create some of the more impressive visual effects, and optimise the rendering performance.

# Answer
> 5 votes
Good audio programmers seem quite rare. However this may not be a hard job to get because most game studios undervalue audio.

# Answer
> 3 votes
Any programmer who knows that this is not a const pointer:

```
const MyClass* myObject = getObject();

```

Is a hot property.

Seriously: good programmers are hard to come by and there's a lot of inexperienced guys in the videogames industry.

# Answer
> 1 votes
I say the hottest and hardest is to be a Studio founder, and to be a successful one at that.

# Answer
> 1 votes
Coding positions seem to be becoming less exciting/creative and less respected with each passing year and increase in team size :(

For each 'exciting' dev position (e.g cutting-edge graphics, or gameplay coding on a big title), there's about 10 coders needed to to fairly dull work (front end, TRC/TCR compliance, tools, porting to the lesser platforms)

You won't make big money coding games unless you really get lucky (right place at the right time). The only real money is in founding a studio and selling up to a megapublisher. Or creating an unexpected big hit with a very small team.

As a career, games programming seems somewhat dead-end unless you have what it takes to start a studio of your own, or are willing to give up coding and aim for a management role...

# Answer
> 0 votes
I would say that that the "Hot position" when it comes to programmers is probably Lead Architect, Lead Engine, or any other name to the same job. Essentially the guy who gets to decide what to implement and how. It's often a person with very good knowledge regarding programming, someone who probably has one of the best overviews of the code in the company. I don't think that it's something that you often get recruited to externally, but instead most likely internally. It requires a lot of experience and often have a tendency to be the best "general" programmers that make it there.

# Answer
> 0 votes
I think, that it is any dev position with good project profit share :)...

# Answer
> 0 votes
a person who's got patience and the quest to learn when new technologies arrive.. he'd get the job he always wanted..be it a game graphics programmer or game programmer lead. i believe u can build a house only after u've bought the first brick :)

going up is a slow and very much desired process.

---
Tags: jobs
---


# Question
Title: What are standard methods for organizing game code? Grouping by standard "kinds" of methods?
I've made a few games, and am getting faster and better organized each time. I'm well out of the "just make it work" phase and working on methodology and readability. I need some tips on code organization though.

I don't mean patterns - I'm having great success with MVC - but the organization of methods inside the classes themselves. I've noticed that methods in my state models can usually be grouped into four categories: (1)constructor/destructor, (2)data access (3)actions (4)events.

My controllers usually have c/d and input methods. My views usually have c/d, view updaters, and event listeners.

I feel like I'm reinventing the wheel though; someone must have spelled out "these are the common types of methods" somewhere before, right? Storage has Create, Read, Update and Delete (CRUD), so what are the equivalents for objects?

EDIT: Found some cocoa-specific advice here: http://www.mactech.com/articles/mactech/Vol.21/21.07/StyleForCocoa/

and some generic advice here: https://stackoverflow.com/questions/73045/whats-the-best-way-to-organize-code/73081#73081

I'm going to use that as a foundation, modified for game-specific stuff. More info still appreciated if you have any.

# Answer
This varies widely between projects from my experience. My biggest rule is to keep your code consistent. If you choose a particular style, make sure all the code follows that style.

As for a "CRUD" equivalent, I haven't seen one, although I like the idea of trying to come up with a unified model for this.
> 3 votes

# Answer
This isn't language agnostic but things like stylecop help a bit here. It's not very helpful contextually, but at least everything is in a known place (Things like Public Properties after constructors, protected methods after public ones, etc.).
> 2 votes

# Answer
I stick to: Private (implicit), then public.

* Creators (constructors and static named constructors)
* Destructor
* Blank line
* Non-const methods
* Blank line
* Const methods

I'm a minimalist when it comes to formatting. I also don't mess with vertical alignment or whatever. If I need more than one public or private block, I refactor. If my methods are too long (names or parameters), I refactor. Etc. Everything must be as small and easy to read as is practical, but no more. :)

If there are enough methods on the class that I have to group them by functionality, as in:

```
...
public:
    // Here are the XXX methods.
    ...
    // Here are the YYY methods.

```

then my class is probably doing too much. I recommend reading the book Clean Code by Robert Martin.

EDIT: Accidental tab-space submit \>:(
> 1 votes

# Answer
If the class is longer than roughly one page of your editor, refactor it. I don't think the order of methods or members matter much, as long as they're grouped somewhat logical together.
> 0 votes

---
Tags: software-engineering, methodology
---


title: OpenGL FBO Rendering

text:
# Question
Title: OpenGL FBO Rendering
I'm getting some artifacts when I try to use a colour attachment on an FBO. I'm saving my first pass as a texture, then passing it as an input to an anti-aliasing shader. The result is, as below, some weird noise and an enforced black background. The AA is applied fine.

```
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, _hndFBO);
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.DrawBuffer((DrawBufferMode) FramebufferAttachment.ColorAttachment0Ext);
GL.PushAttrib(AttribMask.ViewportBit);
GL.Viewport(0, 0, _intWidth, _intHeight);
//Do rendering here
GL.PopAttrib();
GL.BindFramebuffer(FramebufferTarget.FramebufferExt, 0);
GL.DrawBuffer(DrawBufferMode.Back);

```

Any ideas? Need more code?

# Answer
Are you clearing the back buffer before you render to it each frame?

I'm assuming magenta is "transparent" in the first picture. If so, the parts of the back-buffer where there is no terrain are not affected. Residual data could very well account for what you are seeing.
> 3 votes

---
Tags: opengl
---