# Question
Title: Spatial Partitioning - How do I find the object is in the tree?
I understand the structure of Spatial Partitioning Trees - BSP, Quad and Octal. You just take a space and split it into however many parts specified by your tree - BSP:2, Quad:4, Octal:8. I've written a self managing quad-tree (in Java but this shouldn't matter) before, and I had the same question I'm having now (in XNA).

How, once an object is in the tree, do I find it specifically. ie. I put the player in the tree, he updates ever frame, but unlike the other AI driven/world objects, he needs input, and his health needs to be checked every frame to see if the game is over. How do I get him out, without knowing his exact location.

My solution last time was to just leave the player out of the tree, and when I need to do collision checking, just pass in his coordinates to get the possible collisions, but I feel like this isn't using the tree the way it's supposed to be used.

Right now I'm trying to write a tree for a 3D game this time in XNA. So my second question really is which tree is better? I've heard BSP trees are the standard, but weren't oct trees written for dividing 3D spaces (Same as quad trees are for 2D)?

# Answer
> 1 votes
Spatial partitioned data structures should only be used for finding out what is in a particular area, they do not replace plain data structures.

```
SpatialObjectGrid<Entity&> worldGrid;
List<Enemy&> enemies;
[...]
Player& player=Player(blar, blar, blar);
worldGrid.add(player);
[...]
Enemy& newEnemy=Enemy(bar, bar);
enemies.append(newEnemy);
worldGrid.add(newEnemy);

```

# Answer
> 0 votes
Well, BSPs are mainly for rendering but are typically not used today (certainly fine for something that you are making however). Octrees are for spacial partition of the world for objects in game. And yes, you want to put your player into the tree. However, keep a reference to the player specifically if you want to manage them and so that you know where they are. (You can also put the input parsing in the player's AI if you want)

Also, if you can, simplify your design. If you have a game that could be represented in 2D, then only spacially manage 2 directions. Also, using a grid over a tree is typically faster (as it is a simpler design).

---
Tags: space-partitioning
---


# Question
Title: How to do score systems, combos, multipliers, chains, etc
I am designing a game, but I am having some trouble implementing a decent score system. Basically I have nodes with two different possible characteristics: color and shape. Since the player click from node to node, I want to award more points to the players which hit the same shape, same color or both, like: (SAME SHAPE x 3! AWESOME!, SAME SHAPE AND COLOR x 5! ARE YOU A WIZARD?!).

However I am having a lot of trouble implementing this. Can someone point me in the right direction or show me algorithms that can do this?

# Answer
> 7 votes
To do this, your game has to keep track of the previous nodes clicked by the player, and check the sequence for the combos that you care about.

The usual approach is to just keep adding things to your record of what the player has done until they break the combo chain (however your game defines that), at which point you clear the record and start over again, building up a new chain of actions.

---
Tags: algorithm, scoring
---


title: Texturing an asteroid

text:
# Question
Title: Texturing an asteroid
I'm trying to texture this asteroid so it looks reasonable. I'm missing something though.

Following this tutorial, I got this so far.

Now I don't understand the next step: **how do you resolve the seam problems**? This icosahedral sphere has a seam running through it that cannot be avoided. Ok. How do I paint the texture so it **looks seamless** when applied to the object? How do I know which edge connects to what side? I guess it will just be symmetrical?

This seems awfully hard to texture a simple sphere. Am I missing some technique here?

# Answer
> 10 votes
This is where I will use a 3D painting program. I primarily use Blender for my modeling, and it has a 3D painter built in. Being able to paint directly on the model in a 3D environment, makes the strokes continue across seams.

I don't find the paint tools in Blender to be great, so I'll usually switch to something like GIMP once I've got a rough idea. Then I add details in GIMP. Though, your 3D paint program may be different.

The program you use will depend on your work flow, but here's a tutorial (and another) for using Blender's 3D painting capability.

# Answer
> 2 votes
One simple solution is to keep the background of the asteroid very flat so it wraps well, then add detail away from the edges. Don't cross the edge. Put your craters and bumps and things inside. That should minimize the seam.

# Answer
> 2 votes
I was able to get a reasonable wrap using this kind of UV layout:

It's only got 2 seams, one in the top, and one in the bottom (edges 1 and 7 from the diagram above).

The texture is tileable, so along the rest of the seam, it is seamless.

I couldn't figure out another way to do it!

# Answer
> 2 votes
I also thought just now about using a *cubemap* texture (ie 6 textures). My rationale is, if you were planning to use a 256x256=65536 texel image, you may as well use a 64x64x6=24576 texel image (cheaper!) and get less distortion and no poles.

You lay the UV mapping out like this:

Identifying what side is what and laying out the UV's this way is tedious but not very hard.

You have to create a *cubemap* texture to put on the sphere. I didn't have a rocky one, so I just used one from http://humus.name/. It's important to note tileability *isn't* enough for a cubemap: you have to have continuity across the *edges* of the cubemap (just fold a paper cube to figure these out!)

# Answer
> 1 votes
You could texture map it by pretending it's a sphere or a cube. The quality of this approximation depends on how round your asteroids are.

With sphere treat each vertex position as a normal and convert them to polar coordinates. This will create poles though, but at least it will be seamless.

With cube you can create 6 faces that are seamless. Alternatively you can just use a cube map by again treating all vertex positions as normals and sampling from a cube map with that.

---
Tags: textures, uv-mapping
---


title: Why would typeof(T) kill performance?

text:
# Question
Title: Why would typeof(T) kill performance?
**TLDR:** using `typeof(T)` twice; assigning the value to a variable and reusing that = uber fast (30FPS), actually calling `typeof(T)` twice = derped (5FPS). Why?

---

I have a simple entity/component system; my basic entity had an array of `IComponent`s, and methods like `HasComponent<T>` and `GetComponent<T>`. These just iterate over the arrays and return the first matching item (`this.components.Any(c => c is T)`).

Turns out a performance bottleneck I experience with 100k components "in memory" (albeit most off-screen) is actually these two methods. With a few components, no problem (30FPS+). With 100k components, just sprites, I get around 5FPS.

So I figured, why not use a `Dictionary<Type, IComponent>` instead? It'll be faster, right?

Right?!

Wrong. First, a complexity: I have a `SpriteComponent` class, and a `SpriteSheetComponent` component class (knows about frames, animation, etc.). To simplify everything, `SpriteSheetComponent` derives from `SpriteComponent`. This makes drawing, ordering, etc. simpler, because of the is-a relationship.

Second, querying for components became more complex; if I ask `HasComponent<SpriteComponent>`, and you have a `SpriteSheetComponent`, you should return `true`, right?

So the way I handle that is:

`return this.components.Keys.Any(t => t == typeof(T) || t.IsSubclassOf(typeof(T)));`

Ditto for fetching the element, except I use `First` instead of `Any`.

Anyway, I noticed that the performance actually **degraded**. What's even more surprising is that this fixed the performance issue:

```
var tType = typeof(T);
return this.components.Keys.Any(t => t == tType || t.IsSubclassOf(tType));

```

The only difference is that **I'm checking typeof(T) once and reusing *that*.** This fixed my FPS up to 30ish, hurrah.

But this is definitely a "lolwut" moment for me. Is `typeof(T)` really that slow? And in this case, it's shredding my performance with just *one extra call*?

# Answer
> 13 votes
Well, it's not really *one* extra call, is it? It's n * 100k extra calls per frame, if you're doing this every time you retrieve the sprite component for each entity!

Maybe your entity should just have a field for the sprite component, null if it hasn't got one, rather than indirecting through all this dictionary and typeof stuff. Ditto for other commonly used components.

I understand the impluse to generalize, but your system sounds rather overengineered for what it needs to do.

BTW, if you have 100k entities (a *huge* number by most game standards) and most of them are offscreen, you should *definitely* invest in a space-partitioning system of some sort so you can avoid updating - or even looping over - all of 'em.

---
Tags: c#, entity-system
---


# Question
Title: How do I store multiple bullets' coordinates?
My game is a 2D game(or tries to be) in pure C using SDL(no OpenGL at all). No specific goal in it, it's pretty much boilerplate code.

I decided I want to make my character/player shoot "something", whether you'd call it a bullet or not is up to you. But even before writing any code, I already saw my first hurdle. You see, in reality when you shoot a bullet it's pretty fast, you'd normally hit a target by the time you shoot again, in my game I want the bullets to be slow so that two or three or more can be displayed on the screen. This is where the problem starts. I have written some pseudo-code to illustrate my problem.

Basically, when I shoot a bullet, I increment a total bullet counter, then the sprite would appear and every few MS I would update the animation and check for collision. When I have multiple bullets which I store in a structure array, I would loop through all of them to check their collision, or if they went out of the screen's view. When one fits either condition, I will remove it from the screen and (free it) from the structure array and that index will point to invalid memory. Basically, my pseudo-code tries to illustrate the problem.

http://pastebin.com/9Y40GgT4

This is my interpretation of how it should be done. I am assuming there are other ways. Hopefully we can avoid the "Why C and not C++ discussion at this time".

# Answer
> 4 votes
There's no reason to go c++ here =)

The simplest solution in these kinds of situations that I've found is something like this:

```
#define MAX_BULLETS (something reasonable)

struct Bullet
{
int alive; // default = 0
float x, y;
...
}
bullet[MAX_BULLETS];

..

void spawn_bullet(float x, float y, ...)
{
// find first free slot
int i = 0;
while (bullet[i] == 0 && i < MAX_BULLETS) i++;
// fill in the data
bullet[i].alive = 1;
...
}

```

..and when handling physics, just loop through the whole array and handle the ones that are alive.

YES, you will be "wasting time" looping through unused array slots, but you should be able to handle the situation where all of the slots are in use, so this is not as big a problem as it seems - the simplicity is worth it.

Alternatively you could use linked lists, but then you get the overhead of traversing the linked list - the worst case performance will be much worse than looping through an empty array.

As a bonus feature, you can use the "alive" as a counter that you decrease on every physics loop to give the bullets a limited range; and the "age" of the bullets can also affect the amount of damage they cause.

If you have huge amounts of bullets, you can skip the "find first free slot" scan and just pick a random slot; if it's in use, just don't spawn a bullet. Nobody will notice.

**EDIT**

As Sam Hocevar pointed out, the search is not necessary if, when removing bullets, you move the latest bullet on top of the currently removed one, like:

```
void remove_bullet(int n)
{
    bullet[n] = bullet[--bullet_count];
}

```

In this case you won't need the alive member either.

---
Tags: c, architecture
---


# Question
Title: How to start external AS file playing on frame 2 (instead of frame 1)
I am using actionscript 3 and I have used an external actionscript file (.as) for my game.

I would like the external actionscript file to be played at frame 2 (instead of frame 1, as it is an introductory page of the game) on the timeline.

How do I do that? I have been trying and looking for answers for hours, appreciate if you can help on this. Many thanks in advance!

# Answer
> 1 votes
I'm assuming you're using the Flash IDE?

If your file isn't an Actionscript class, just use the `include` statement. Eg. on frame 2, write:

```
include "myFile.as";

```

If you're using classes, there's an option in the Actionscript-3 settings, where you can specify a frame where classes should be imported to. So if your class is `MyClass`, just call something like this on frame 2:

```
var myInstance = new MyClass();

```

Maybe you'll even want a combination of the above.. eg. export all classes to frame 2 and also `include` an initialization script on frame 2.

---
Tags: actionscript
---


# Question
Title: onSceneTouchEvent Triggering more than once on one click in Andengine
I am making a simple american football game, and I'm having an issue with the onSceneTouchEvent function, I have this code:

```
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {

    if (hiking == 0) {
        Log.v("me", "Only the player should move");
        return hike();
    } else {
        Log.v("me", "this shouldn't ever happen on first click");
        return throwBall(pSceneTouchEvent);
    }

}

```

Inside hike() I set hiking to 1, so that theoretically, the player should be able to click anywhere to hike the ball, (all the other sprites start moving and the ball is not thrown). Then on the second click the ball is thrown. But with one click on the emulator, the ball is hiked and thrown at the same time, I also see this in the log (after only one click):

> 12-21 14:34:32.113: V/me(1189): Only the player should move
>
> 12-21 14:34:32.143: V/me(1189): this shouldn't ever happen on first click
>
> 12-21 14:34:32.183: V/me(1189): this shouldn't ever happen on first click

So it appears that it's triggering three times on one click? Why is this happening? How can I make it only run the code once per click?

Update:

Perhaps I could just prevent any events by using a timer? Like disable the listener for a second after the hike? I'm hoping there is a better solution though.

# Answer
I think you didn't know the working of the onSceneTouchEvent().

The onSceneTouchEvent() method execute three times when user one time touch on the device. This happen three times because it calls three events on single touch.

1) touch down 2) touch move 3) touch up

As per your requirement you have to change your code in following manner.

```
public boolean onSceneTouchEvene(){

    if(pSceneTouchevent.isActionDown()){
         // you code goes here
    }
}

```

This way three other method exist that also you can use based on requirement.
> 2 votes

---
Tags: java, andengine
---


# Question
Title: In an asynchronous server environment where player input and timed events modify data is using an in-memory array problematic?
So let's say I have a server running on node.js, and there is an array of player objects...

At an interval, all of these player objects are looped and processed for events and changes that are based on time, such as fuel or food consumption and movement.

However players can also trigger things from the client that could modify player data as well.

Now what I'm trying to determine is if I am going to run into any problems with timing, such as if we are mid loop and somebody changes something and it throws some other calculation off balance.

Will I need to implement some kind of locking mechanism I can use as needed or is there a better way to hold this data in memory?

# Answer
First and foremost you have to understand the JavaScript event model. JavaScript has an event list, whenever an event happens, that could be an incoming HTTP request, one of your intervals triggering, or a bunch of other stuff, that is event is put on a list. Events on that list are being handled one at a time, in the order in which they occurred, but not necessarily at the time when they occurred, since other prior events may need to be handled first.

This means that when you iterate over the array using a simple for loop, no other code is running, if a user takes an action that will change the array, the corresponding request will be handled only after you have finished.

The downside to this is of course that your users will experience a delay whenever you are doing an update. But this is not a problem unless your update takes a long time.

Beware that any code you put in a callback will be executed under a different event than the current code, so arbitrary other events may be handled in-between.

On a slightly related note, beware that the `setTimeout` and `setInterval` functions are not exact in their timing. In V8 an interval will "drift", taking breaks that are slightly longer than specified, or in some cases under heavy load a lot longer. If you want your updates to stick to a schedule you will have to use `setTimeout`, and in each iteration check how much off schedule it was executed and subtract that from the time set for the next update.
> 1 votes

# Answer
If multiple, independent agents can both use/modify the same data on the server, then it requires certain design principles to prevent problems.

1. If the server environment is multi-threaded, then the access to the actual data on the server has to be protected with mutexes (or something similar like a multi-user database) so that changes to the data are atomic and no two threads or processes are ever trying to change the same piece of data at the same time and all data structures retain appropriate integrity no matter how many people are trying to change the same data at the same time.
2. The client environment has to both know that any data it holds might be getting changed by another agent at any time and it has to be designed to handle that in its normal operation. There are a number of design strategies for handling that and which makes the most sense depends entirely upon the application.
3. When the client wants to change data, it has to have a design strategy for how to handle the case where somebody else has already changed the data since you last saw it. The strategies can be as simple as "last writer wins" or much more involved requiring verification that the client knew the previous state of the data before changing it or even temporary locks while making a change.
> -2 votes

---
Tags: javascript, node.js
---


# Question
Title: Progressively loading the racing arena in a 3D driving sim
I need advice and resources on a 3D car simulator. I want to progressively load the track for the player as I'm thinking of porting the game to mobile devices. This seems too difficult to me as I'm trying to separate the racing arena model design and the code as much as possible. Is there a structured method for achieving that for any model (arena/map). I think this is something that comes up a lot in games in general not just this instance.

# Answer
In general for large maps you can separate the map into multiple chunks and load each chunk as a quad or oct tree for LOD rendering. This might be a generic answer, but you will have to specify your target platform and more details if you want a more more specific answer.

This thread might give you some ideas.
> 2 votes

---
Tags: physics, 3d-meshes, racing, car
---


# Question
Title: Why and how should I cast DirectX function parameters?
I'm learning DX11 and I found that in some D3D functions, a parameter has to be cast just like in the GetBuffer function of the swapChain: the third parameter has to be of type void\**, so when calling this function the conversion is done just writing (void*\*) before, a C conversion if I'm not wrong.

But in other functions with a pointer like type\** (where type IS NOT void) is used the reinterpret\_cast. I wanted to know if the difference is because of the void type respect to the other types and, if it's not because of the void type, when should I use (type\**) and when should I use reinterpret\_cast.

# Answer
> 3 votes
In C++, either C casts or the C++ cast operators (`static_cast`, `const_cast`, `reinterpret_cast` and `dynamic_cast`) can be used for the purposes of casting parameters to Direct3D functions (and, indeed, most anywhere). There are subtle differences between the C and C++ casts, but not all of them are applicable here. For more information you could start with this StackOverflow question.

I prefer the C++ casts when writing C++ code because I feel they clarify my intent more, and are more restrictive in terms of potentially dangerous behavior (you cannot, for example, use a `static_cast` to remove CV qualifiers but a C cast happily will do just about anything). What is more important is that you are *consistent in your own usage* throughout your own code.

Note that there *is* a big difference between casting a parameter to `void *` and casting one to `void **`. The latter type has an extra level of indirection and is thus a very different type from the former. Thus, while the style of cast you use is somewhat flexible the types you cast to aren't. Different D3D functions will expect casts to different types.

The origin of most of these castable parameters is in the fact that D3D uses COM technologies and uses output parameters to return pointers to interface objects. The specific type of interface isn't fixed at compile time, and so the API uses `void **` to represent a generic output, but you generally want to work with known interfaces in your own code, and thus the cast:

```
// We want to get the swap chain buffer and do some stuff to it;
// specifically we want to manipulate it as a texture, so we declare
// a variable of the appropriate type (pointer-to-texture)
ID3D10Texture2D * texture;

// Get the first buffer of the swap chain. This is a good example of the
// "unknown interface" issue mentioned above. Here, we tell GetBuffer that
// we'd like to get the buffer as a texture via the second parameter. This
// allows the function to fail gracefully if the buffer does not support
// the ID3D10Texture2D interface.
//
// Since GetBuffer doesn't know the result type at compile time it's output
// parameter is a void **, but we know the result type and declared it above.
// That's why we need the cast to void **, which we do using a C++ cast here:
swapChain->GetBuffer(0, __uuidof(texture), reinterpret_cast<void**>(&texture));

```

---
Tags: c++, directx
---


title: Multiplayer online game engine/pipeline

text:
# Question
Title: Multiplayer online game engine/pipeline
I am implementing online multiplayer game where client must be written in AS3 (Flash) to embed game into browser and server in C++ (abstract part of which is already written and used with other games).

Networking models may differ from each other, but currently I'm looking toward game's logic run on both client and server parts but they're written on different languages while it's not the main problem.

My previous game (pretty big one - was implemented with efforts of ~5 programmers in 1.5 years) was mainly "written" within *electronic tables* as structured objects with implemented inheritance: was written standalone tool which generated AS3 and C++ (languages of platforms to which the game was published) using specified *electronic tables* file (.xls or .ods). That file contained ~50 tables with ~50 rows and ~50 columns each and was mainly written by game designers which do not know any programming languages. But that game was single-player.

Having declared problem with my currently implementing MMO, I'm looking toward some vast pipeline, where will be resolved such problems like:

* game objects descriptions (which starships exist within game, how much HP they have, how fast move, what damage deal...)
* actions descriptions (what players or NPCs can do: attack each other, collect resources, build structures, move, teleport, cast spells) - actions are transmitted through server between clients
* influences (what happens when specified action applied on specified object, e.i "Ship A attacked Ship B: field "HP" of Ship B reduced by amount of field "damage" of Ship A"

Influences can be much more difficult, yes, e.i. "damage is twice it's size when Ship has \>=5 allies around him in a 200 units range during night" and so on. If to be able to write such logic within some "design document" it will be easily possible to:

* let designers to do their job without programmer's intervention or any bug-prone programming
* validate described logic
* transfer (transform, convert) to any programming language where it will be executed

Did somebody worked on something like that? Is there some tools/engines/pipelines which concernes with it? How to handle all of this problems simultaneously in a best way or do I properly imagine my tasks and problems to myself?

# Answer
There are no standard tools or processes here - every game is different and every team is different, so meeting their needs will vary from one to the next. All you can do is look at what options are available and pick the ones that suit you most.

If you want custom behaviour, that sounds like you'll need a scripting language. There's no magical tool (that I know of) which could translate a normal design document, even a well-written one, into usable game code that works in the language and engine of your choice. But a scripting language at least allows you to execute external files as if they were code. That allows people, maybe designers, to write behaviour in the scripting language without needing to edit the main game engine. Arguably your designers are becoming programmers at that stage, but hopefully the scripting language is easier to use than C++, and less bug-prone, but a lot of that depends on your choice of language and how you implement it.

Scripting languages can also function as data documents too, so designers can combine the behaviour and data in one file. However it is often more effective for data to be handled in a separate tool that you make yourself, or via a standard tool such as Excel. What is best for you will depend on the nature and amount of your data.
> 2 votes

# Answer
Here's some more detail on the reasoning behind Kylotan's answer.

# Problem deconstruction

The "design document" that your designers work on is effectively a high-level programming language. They have a high-level API (your XLS/ODS loader) that they're writing their "code" to.

They want to express...

* **properties** that may be *fixed* (e.g. that a certain spaceship type has `range = 200`) which may be *conditional* (e.g. `damage = 2*normalDamage` during the night)
* **behaviours** (e.g. clicking fires laser toward cursor)

...in some format.

The questions condensed: *What should that format be? How can I make it work in a pipeline?*

# Answer

This is what scripting languages are for.

**Why?** You can express *properties* in a table, but you cannot express *behaviour* without programming.
**Why not just write a more complex API?** Imagine if you did: You'd extend the API to allow designers to write conditional statements. Then maybe event callback functions. And then you'd realise you've implemented a scripting language.

Thankfully, scripting languages (Lua is pretty popular) are made to be easy to write and easy to interface with "heavy" code (such as C++).

Assuming C++ core code, you could expose an interface `game` to the scripting language and call the scripting language for values and behaviours from the core code whenever you need them.

In Lua, the above examples could be expressed like this:

```
shipTypes = {
    {
        type = "Assassin",
        range = 200,
        damageDealt = (game.isNight and 1000) or 500,
        actions = {
            leftClick = game.fireAt(pos)
        }
    }
}

```

Your game designers would, of course, have to learn Lua basics. (Or of whichever scripting language you choose.)
> 6 votes

# Answer
You can take a look at eathena project, a mmorpg server clone. I used to practice with it because it contains a simple scripting language to design the whole game and you can find tools for free for designing the scenes or just make them yourself, there is a lot of information out there about it.

When I was newbier I wrote a reader for some of those files such as .gat containing tile description and the like. You can take a look at the sources at google code and also you can see screenshots about tests of the functions at picasa

There may be other free sources of mmo servers but that's the one I know most :). I hope it helps.
> 2 votes

# Answer
I've worked professionally in several games with various teams, and I have to tell you that game designers (they like to call them "planners" in here) love using Excel to tweak all the in-game data. As programmers, we would be idiots not to let them use it.

With Excel and a good and fast ad-hoc excel-to-code converter, not only they can use a tool they are familiar with, but also they can do formulas, check averages, graphs, link to other files and so on, to make sure their data is just as they want it to be.

What I've done in the past, is, when making a new feature that has tweakable data, create a new Excel book. The first sheet contains the exportable data, which has to have a specific formatting so the converter can convert it unambiguously, so I make a skeleton with some test data, and briefly explain what can be changed and what can't be changed. The rest of the sheets are free for them to use.

The converter is a simple script, which can be made in Ruby, Python, C#, or my favorite: VBA. It takes the data from the exportable data sheet and creates one or more source files (in C, C++, Assembly, PHP, SQL, INI, or whatever it is that your game understands) which contain the necessary data as *hardcoded* data, and places them in the correct source folder.

Each time a change is made, the planner runs the converter and builds the game, or whatever she has to do (you have a one-click build process, and the possibility for each team member to have a separate game environment, right?). She can then immediately test her changes on her workstation without having to call a programmer.

Once she is satisfied with her changes, she pushes them to source control, and everybody is happy!

This is a very useful way to let game planners modify game data. Also, since the resulting data is hardcoded, it *may* run faster in the final binary.

Needless to say, this works optimally with data that is tabular in nature, such as monster attributes, spell parameters, stage configuration and the like. It is worthy to note that Excel tables are specially useful to store all the game texts, which everybody will thank you to when it's time to translate the game to spanish, french, german and 10 other languages.

However, this doesn't work with data that is scriptable in nature, such as Enemy/AI behavior and menus. For those, what we have done in the past is decide a set of basic building blocks (the AI for a coward enemy, an aggressive enemy, a healer, etc) and either let them assign them with another excel table, or give them **basic** instructions on how to tweak them to achieve their own purposes.

Finally, very complex data, such as the actual levels; or data that may be tabular but cannot be easily understood by just seeing numbers, such as enemy/agent positions, can't be done either with scripts or excel tables. You're going to have to make a small editor that shows data in an easy to understand manner, and generates data in a way the game program can understand it. I prefer C# with Windows Forms, as it is very easy to make anything in it.

Do not expect or require your game tweakers to script everything themselves. That's just you being lazy. Writing programs, even if scripts is our job, not theirs, so it's at the least lazy, and at worst dangerous.

But anyways, that's what I've experienced. In conclusion, what I think is best, is to talk with your tweakers, ask them what is the data they want to tweak, and how they imagine themselves tweaking it, and make a solution that is as close as possible to what they want. Game balance is very critical, and we want them to do their job as best as they can.

That is one of the many responsibilities of a game programmer.
> 1 votes

---
Tags: networking, multiplayer, mmo, pipeline
---


# Question
Title: Calculate bike heading from front wheel heading and velocity
I have a simple top down bike game that I'm trying to add steering to. I would like to know how I use the heading of the front wheel to determine the heading and velocity of the bike.

```
void Update ()
{
    //Get input from user Vertical: 0 to 1, Horizontal -1 to 1
    float forwardInput = Input.GetAxis("Vertical");
    float sidewaysInput = Input.GetAxis("Horizontal") * m_steeringAmount;

    // Turn front wheel
    m_frontWheelTransform.localEulerAngles = new Vector3(0, sidewaysInput, 90);

    // get speed and drag
    float   speed           = m_velocity.magnitude;
    Vector3 forwardDrag     = -m_forwardDragConstant * m_velocity * speed;

    // calculate acceleration
    float engineForce       = forwardInput * m_enginePower;
    Vector3 forwardTraction = transform.forward * engineForce;
    Vector3 forwrdForce     = forwardTraction + forwardDrag;
    Vector3 acceleration    = forwrdForce / m_mass;

    // update velocity and position
    m_velocity += acceleration * Time.deltaTime;
    transform.localPosition += m_velocity * Time.deltaTime;
}

```

I have tried to apply the bike velocity to the front and rear wheel and use the difference of there positions to determine the bike heading, but the forward drag make it confusing.

**Edit based on madshogo comment**

# Answer
Ok, I'm back with results!

I tried two approaches:

* Using solids mechanics to derive a differential equation governing the movement of the centers of the wheels: the inputs of the system "bike" are the torque at the rear wheel and the angle of the front wheel, and the outputs are the kinematics of the centers of the wheels. But I gave up, it was hard!
* Trying to guess what happens from a geometric point of view when the rear wheel "pushes" the front wheel forward with the front wheel not straight. This method directly yields an equation of infinitesimal increments (see below) from which you can get an actual differential equation. I haven't tried manipulating this first equation to get the ODE but my guess is that I would have obtained that very same ODE using solids mechanics. It just feels right.

## Notations and hypotheses:

We are in the plane with basis vectors *ex* and *ey*.

*A* is the center of the rear wheel. *B* is the center of the front wheel. The length of the bike *L* is the distance between *A* and *B*. The angle between *ey* and the vector *AB* is *φ*. The angle between *AB* and the front wheel is *θ*.

## Intuitive rationale:

We suppose that, at a certain instant *t*, *A(t)* has a velocity *V(t)* colinear with *AB*. Therefore, for an infinitesimal timestep *dt*,

*A(t+dt) = A(t) + V(t).dt*.

We also suppose that, at time *t*, the front wheel doesn't drift, i.e. the speed of *B* is colinear with the direction of the front wheel, i.e. forms an angle *θ* with *AB*. We call  the unit vector forming an angle *θ* with *AB*, i.e. the unit vector with the same direction as the front wheel.

Therefore, at *t+dt*,

*B(t+dt) = B(t) + λ.Uθ*

for a certain real, positive *λ* such that the length of the bike *L* is conserved:

*distance( A(t+dt) , B(t+dt) ) = L*

## Calculations:

This last equation translates to

*norm²( B(t) + λ.Uθ - A(t) - V(t).dt ) = L²*

but *B(t)*, by definition, is *A(t) + L.Uφ*, so that *λ* must satisfy the equation

*norm²( L.Uφ + λ.Uθ - V(t).dt ) = L²*.

The solution, of course, is independent from *φ* since the problem is the same when the bike points towards positive *y*. Therefore, if we call *R* the rotation matrix with angle , *λ* must be the positive solution of

*norm²( L.ey; + λ.Uθ - R.V(t).dt ) = L²*.

After a few calculations, if we call *v* the norm of *V*, you get

***λ = L.( sqrt( 1 - (sin(θ).(1-v.dt/L))² ) - cos(θ) ) + v.dt.cos(θ)***.

Here's the pseudocode I used to get the animation above (instead of using , I use *u = U(θ+φ)* because it was simpler):

```
// I start at i=1 because i=0 contains the initial values
for (int i=1; i<=N; i++)
{
    // the array in which I stored the successive A points
    Aarray[i] = Aarray[i-1] + dt*V;
    float lambda = L*( sqrt(1 - (sin(theta)*(1-v*dt/L))**2) - cos(theta) )
                   + cos(theta)*v*dt;
    // the array in which I stored the successive B points
    Barray[i] = Barray[i-1] + lambda*u;
    // the AB vector normalized
    AiBiUnit = (Barray[i] - Aarray[i])/L;
    // Refreshing the velocity of A
    V = v*AiBiUnit;
    // Refreshing u.
    // u is indeed a unit vector separated from AiBiUnit by an angle theta,
    // so you get it by rotating the newly computed AiBiUnit by an angle
    // of +theta:
    u = AiBiUnit.rotate(theta);
}

```

If you repeat a lot and/or increase the steering angle, the trajectory is a circle, which is coherent, I believe.
> 3 votes

---
Tags: physics, car
---


title: XNA Deferred + Forward, Depth Problem?

text:
# Question
Title: XNA Deferred + Forward, Depth Problem?
Im working with my deferred engine in XNA 4.0 and Im combining it with a forwardpipeline to support semi-transparency and other "forward only" effects.

Let me describe what I do:

1. Render GBuffer and all deferred geometry based on materials
2. A final composit where I combine the lightbuffer and the diffusebuffer from the GBuffer. I output color and depth to a rendertarget so I can use forward rendering to draw directly onto that RT.
3. Render forward geometry
4. I then take the RT from the forward pipeline and do postprocessing stuff.
5. Finally I write the RT to the backbuffer

Question:

* As you can see in the image below there's a problem with the boundingboxes. The are drawn using forward rendering and is drawn using the depthbuffer I descibed in step 2. I have tried to offset the depthbuffer in different directions with a texel or two. But nothing seems to solve the problem. Has anyone experienced this problem before?

**EDIT:** This post has been cleaned from some statements to avoid confusion.

# Answer
Turns out, I was wrong. The source of the problem was in step 5 where I used a shader to copy the rendertarget to the backbuffer.

I forgot to correct the texture coordinates by negative texel X and Y. Not doing this results in incorrect sampling and color data being lost because the sample was taken at the wrong texel.
> 2 votes

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


# Question
Title: How to raise funds for game developement
Creating a game can be a costfull process, if you are working on it full time with around 4 people for 2 years (buidling from scratch) you need about €400.000 for salaries alone. (An average medior skilled employee will easily cost €50.000 a year) (I want to work with skilled people that are available 24/7, not hobby programmers etc. that just do it on the side for fun. I need 100% dedication and motivation)

Is using crowdfunding like kickstarter usefull for small game developers? Can this really get you the required amount of money?

Most projects on (for eaxmple) kickstarter that are started by well known names in the industry collect a lot of money (sometimes over a million).

As a small team being 'unknown' anyone can start a project, but how can you get enough funding? I don't see myself collecting about €400.000 using sites like kickstarter. Not even with the best idea in the world, because people simply don't know you and will not invest in anything they don't believe can be accomplished.

I would prefer not to need investors since they will have the biggest share in your company and you need to do what your told by them, thus loosing all sorts of freedom in the development process. Also they will need a some sort of guarantee about how you are planning to earn money with the game, which of course you don't know about at the start.

In the Netherlands it is possible to get funds from the government for this sort of stuff, but that's still a really small portion of what is needed.

So my real question is: what is the best way to gather the required amount of money to start game developing full time?

# Answer
> 7 votes
Crowdfunding can be very successful, and it is designed for entrepreneurs, not well-established businesses. It not only gets you needed funding, it gives you incentive to finish, so you can deliver the promised gift. An awesome crowdfunding site that just launched is http://gamelaunched.com. It is like kickstarter, except exclusively for games. It also is set up to be a store, so you can sell your completed games, which is different from Kickstarter.

To get the needed crowdfunding, be honest and open. Post your contact information, and make it easy for people to find you. Show your face explaining it in the video. That is the biggest thing. If they know you aren't hiding anything, they can be sure you are actually trying, and aren't just a scam that'll run off with the money. Next, let them know you can complete the project. Sound confident. Link to any previous game projects you completed, and give them a deadline. Show you have actually started production. The final thing is to show the game is fun. Describe the game in detail. Demonstrate how it will work in the video.

---
Tags: game-design, game-industry, fund-raising
---


title: Could the delta frame time be negative?

text:
# Question
Title: Could the delta frame time be negative?
I'm following a tutorial about the time management and, the tutorial shows this function:

```
double GetFrameTime()
{
    LARGE_INTEGER currentTime;
    __int64 tickCount;
    QueryPerformanceCounter(&currentTime);

    tickCount = currentTime.QuadPart-frameTimeOld;
    frameTimeOld = currentTime.QuadPart;

    if(tickCount < 0.0f)
        tickCount = 0.0f;

    return float(tickCount)/countsPerSecond;
}

```

The tutorial explains that, this function basically gets the time that one frame takes, but, I don't understand how the variable tickCount can be negative, if the currentTime is increasing all the time (calling this function every frame, obviously), so, is that if really necessary?

# Answer
> 2 votes
1. Even a 64-bit integer can overflow eventually; after increasing for a certain amount of time (exactly how long will depend on `QueryPerformanceFrequency(&outvar)`), it will eventually roll over, and what used to be a very large number will become a very small number. So when you calculate `currentTime.QuadPart - frameTimeOld`, that becomes `small number - large number` == negative number. (This would only happen on one frame, since frameTimeOld then gets overwritten with the small number, and everything would be fine again on the next frame)
2. According to MSDN, bugs in a computer's BIOS or HAL on a multi-processor machine can result in different values being returned from `QueryPerformanceCounter()` based upon which processor happens to run the code. So in this sort of case, it could happen far more often.
3. Probably the real reason: `QueryPerformanceCounter()` provides its output as a signed 64-bit integer. So you might as well work with it in that form. And since when you're dealing with a signed integer variable it's possible to wind up with a negative number, and that would cause problems if it happened, it's just good practice to guard against it.

---
Tags: windows, timer
---


# Question
Title: Tweaking Heightmap Generation For Hexagon Grids
Currently I'm working on a little project just for a bit of fun. It is a C++, WinAPI application using OpenGL.

I hope it will turn into a RTS Game played on a hexagon grid and when I get the basic game engine done, I have plans to expand it further.

At the moment my application consists of a VBO that holds vertex and heightmap information. The heightmap is generated using a midpoint displacement algorithm (diamond-square).

In order to implement a hexagon grid I went with the idea explained here. It shifts down odd rows of a normal grid to allow relatively easy rendering of hexagons without too many further complications (I hope).

After a few days it is beginning to come together and I've added mouse picking, which is implemented by rendering each hex in the grid in a unique colour, and then sampling a given mouse position within this FBO to identify the ID of the selected cell (visible in the top right of the screenshot below).

In the next stage of my project I would like to look at generating more 'playable' terrains. To me this means that the shape of each hexagon should be more regular than those seen in the image above.

So finally coming to my point, is there:

1. A way of smoothing or adjusting the vertices in my current method that would bring all point of a hexagon onto one plane (coplanar).
2. A better approach to procedural terrain generation that would allow for better control of this sort of thing.
3. A way to represent my vertex information in a different way that allows for this.

To be clear, I am not trying to achieve a flat hex grid with raised edges or platforms (as seen below).

I would like all the geometry to join and lead into the next bit.

I'm hope to achieve something similar to what I have now (relatively nice undulating hills & terrain) but with more controllable plateaus. This gives me the flexibility of cording off areas (unplayable tiles) later on, where I can add higher detail meshes if needed.

Any feedback is welcome, I'm using this as a learning exercise so please - all comments welcome!

# Answer
> 3 votes
Fundamentally, hexagon height fields have the same issue that rectangles do; it's not really possible to ensure that a hexagon/rectangle will be entirely coplanar without putting some heavy restrictions on the possible shapes of the terrain, and on the editing of the terrain. That is, each time you move a single vertex, that change will "ripple out" across the entire map as each hexagon is "re-planarised", which in turn will move the vertices of its adjoining hexagons, which then necessitates those adjoining hexagons to be re-planarised, and so on.

If your goal is really just to have a coplanar area within the hexagon, then you might consider creating a second hexagon inset within each hexagon, with the inner hexagon having its own unique vertices (which we can therefore freely make coplanar without influencing any neighbors), and with a strip of triangles stitching the inner (planar) hexagon to the exterior (non-planar) hexagon. That would let you keep the free-form height field, while also letting you make an absolutely flat area in the middle of each hexagon, if you should wish to.

---
Tags: procedural-generation, rts, terrain-rendering, hexagonal-grid
---


# Question
Title: Is there any potential downside to procedurally programmingh in DirectX 11, without classes?
I'm learning DirectX 11, and I hope to start a simple 3D engine, some day. I'm following a tutorial series, and I realised that I have no need to create any class to maintain my code. The tutorials also use this procedural approach, but I don't copy and paste the tutorial code; I try to understand the tutorial, and then try to code the new stuff in my way.

I can have the code *understable*, and working well, with just functions and global variables. When I have enough knowledge of the API, and I want to start creating my own library, could this procedural approach have some downside? Should I start writing some classes?

# Answer
> 1 votes
The only real reason to write API code in classes vs. free functions (I hope you're grouping them in namespaces!) is so that you can swap in concrete API code if you decide to switch implementations.

To do this, you have interfaces for all your API-specific objects (renderer, mesh, texture, etc.).Program all your high-level code (like models, lights, materials) to these interfaces.

```
// The renderer interface.
// Your game code should work with this and not the concrete implementations.
class IRenderer
{
public:
    virtual void Render() = 0;
};

```

Now, write concrete implementations for these interfaces, one implementation per API.

```
// The Direct3D 11 renderer.
class D3DRenderer : public IRenderer
{
public:
    virtual void Render()
    {
        // Clears the screen.
        context->ClearRenderTargetView(renderTargetView, { 0.0f, 0.5f, 1.0f, 1.0f });

        // Render the rest of the scene...
    }

private:
    ID3D11DeviceContext *context;
    ID3D11RenderTargetView *renderTargetView;
    // Other API-specific data...
};

// The OpenGL renderer.
class OpenGLRenderer : public IRenderer
{
public:
    virtual void Render()
    {
        // Clears the screen
        glClearColor(0.0f, 0.5f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Render the rest of the scene...
    }
};

```

Somewhere in your engine, you also have some sort of abstract factory that is able to create all of these concrete implementation objects for you. When initializing the game, you pick which API to use and set up your factory to create the objects that conform to that API. Your high-level code can now work with objects like meshes and textures without needing to know which specific API you're using.

```
// The abstract factory.
class IEngineFactory
{
    virtual IRenderer *CreateRenderer() = 0;
};

// The D3D11 factory.
class D3DEngineFactory
{
    virtual IRenderer *CreateRenderer()
    {
        return new D3DRenderer();
    }
};

// The OpenGL factory.
class OpenGLEngineFactory
{
    virtual IRenderer *CreateRenderer()
    {
        return new OpenGLRenderer();
    }
};

```

This is useful for porting your code to other platforms. For example, your Windows binary uses DirectX and your Unix binary uses OpenGL.

---
Tags: directx, software-engineering
---


title: Collision Detection Tips

text:
# Question
Title: Collision Detection Tips
I need collision detection for my 3D racing game but it isn't going well right now. I think I understand the concept of testing boxes and generating a response, however implementation part is a nightmare for me. OpenGL makes everything more complicated than it has to be.

How can I use a shape that is constructed with glVertex\*? Should I create the bounding boxes with some Vector3D class?

# Answer
At the end of your question you're on the right track; object-oriented programming is your friend here. You'll want to create various mathematical classes, like vectors and matrices, or use a pre-existing math library like glm to save yourself the pain of mistyped indices or an improper `w` component.

From there, you can create various classes that represent your collision structures, probably your standard AABBs and OOBBs, and then write the algorithms for testing for collisions between them.

The important thing to remember is that OpenGL is strictly a rendering library. It handles graphics, nothing else. This means that the other subsystems of your game may take on whatever architecture you want them to; the only restriction that OpenGL places you under is that your data can be easily transferred into a format that OpenGL expects. To give examples, an array of floats for vertex data, texture coordinates, normals, etc; most often an array of floats.

To put it another way, you don't want to think of how GL calls like `glVertex*` will factor into the design of your physics shapes, because OpenGL is an entirely different subsystem. Instead, think of what's easiest for you to work with in the context of physics, and then determine how you want to render that data.

Here's an example: let's say you decide you represent your AABBs using four values: the center of the bounding box (as a 3D point), and its width, height, and depth. When it comes to rendering this box (probably in a debug rendering situation), you can construct your vertices on the fly, with the following pseudo-code:

```
draw function:
    - compute the 8 corners of the box using the center and dimensions
    - assemble this in the triangle format OpenGL expects
    - push the generated data to OpenGL for rendering

```

Note that for data like models, things are very different. Models don't have a functional purpose other than visually representing something in the game world, so their data representation is heavily tied to the rendering engine. Hence, models are specified with the very same data that will be pushed to the renderer.

To sum up, for something that is not functionally tied to rendering - in your case, physics structures - ignore rendering while you design it. If you have a physics structure that you want to render, determine the best way to do so without compromising a representation that is easy for your physics system to digest. OpenGL is actually quite unrestrictive when you think about it, because all it requires are numbers.
> 4 votes

---
Tags: opengl, collision-detection
---


title: Precomputing SSAO causes driver timeout

text:
# Question
Title: Precomputing SSAO causes driver timeout
I was trying to do a pre-calculations of an SSAO effect by rendering normals and depth on a cubemap and doing a second ssao pass on each of these faces. The problem is I'm getting a timeout: "the nvidia opengl driver lost connection with the display driver...", when using high resolutions. Is there a good way to do such calculations without having to tweak registry values? I want this to be able to work for other people too.

In essence I'd love if there was also a way to add something like a loading bar so that people don't think the program crashed or something.

# Answer
What you want to do is make sure you present something to the screen during this process, because it's essentially the time between those that Windows is looking at. Rendering a progress bar between each cube map face should be enough to do the trick in your case as you aren't too far over the limit. I believe the default limit is two seconds per frame.

However, make sure you test it on low end hardware as that will take even longer and be more likely to timeout.

Alternatively pre-compute the cube maps on your PC, and save them out. That way you cut down on the loading time for everyone as well as avoiding the TDR.
> 3 votes

---
Tags: opengl, nvidia
---


# Question
Title: How can I measure the execution time of some code?
How can I capture how long something takes to complete and log it to the output window (in Visual Studio)?

Is there a special library for this?

```
clock_t start, end;
double cpuTime;

start = clock();

//....bit to be timed

end = clock();

cpuTime= (end - start) / (CLOCKS_PER_SEC);

OutputDebugString(TEXT("Time: %d", cpuTime));

```

This code might work but where does it come from? A special include?

# Answer
Your clock code comes from `#include <ctime>` and OutputDebugString comes from `#include <windows.h>`.

OutputDebugString will not print anything if there is no debugger available.

If you want platform independent code you might want to take a look at boost timers.

If you don't like boost and need nano precision on multiple platforms, the keyword on Windows is QueryPerformanceCounter and for Linux and BSD you want to use clock\_gettime().
> 8 votes

# Answer
I noticed you tagged your post SDL, so you can call SDL\_GetTicks() which will return the number of ms since your program started. Print this to the console or a file at the start of the section you want to time and then print it at the end, calculate the difference between them and you've got your timing.

Or assign it to a variable at the start, then calculate the difference between the start and the current time at the end: SDL\_GetTicks() - startTime, and print this to the console/file.
> 2 votes

# Answer
You could use a profiler. In the general case, a profiler will tell you where the slow parts of your program are. But it's not always helpful - enabling profiling generally slows your program down but does not slow time down, nor slow your graphics or other hardware down, so it can give a distorted picture.

It's also worth noting that you can't usefully time a simple, fast operation, because it will be too fast to measure accurately, and in a single run the effects of (e.g.) CPU caches may give a misleading picture.

If it's something big that takes, say, 50ms, then it's ok though.
> 0 votes

---
Tags: c++, sdl
---


# Question
Title: Astar heuristics closing in on an answer before searching around to find nodes with lower movement costs
I am having some trouble with my A\* path finding. everything works fine and the path is always found. However, my game is a open map space strategy game. There are no walls etc to navigate around. Now, the movement cost along the navgrid is the same unless the agent chooses to navigate thro a 'jump gate' (in which case the cost is 100 times cheaper. almost always the better option).

I have a problem where the heuristics will narrow in directly towards the answer rather than searching around for a better solution. If my heuristics function always returns 0, then I always get the correct route, however with no heuristics I need to search the entire map and this makes it far too slow.

As you can see, the top agent ignores the jump gate and flies directly towards the destination, completely ignoring the gate way. The bottom agent opts to use the gate way (only because its heuristics was causing it to search in a north-west pattern anyway.

What are some possible solutions?

# Answer
> 5 votes
I assume you are using simple pythagorean distance as your heuristic. In that case, the answer is simple - this is not an admissible heuristic (meaning it overestimates distance), and A\* is not guaranteed to give an optimal answer. It overestimates because your heuristic is more or less equal to "flying in a straight line", while jump gates are - as you say - a 100 times cheaper solution.

There is some academic theory behind A\*, which includes formal definitions of "admissible heuristics" and proofs of when A\* is guaranteed to return optimal solutions. If you're interested, the wikipedia page is a good place to start.

As for solutions, I wouldn't recommend changing the heuristic. It's fine. I would rather try a compound search - issue two search queries at the same time, one using "conventional flight" and one using warp gates (to the nearest warp gate, jump to warp gate heuristically closest to target, fly from warp gate to target). This assumes all warp gates are connected; I they are an interconnected network, you'll need to issue a small search in warp-gate space.

Anyways, of the two search queries you issued, whichever finishes first is optimal.

EDIT: After your comment about there being multiple warp gates from A to B, I think your search space is different than you think - you should be thinking in terms of a graph of nodes, not a flat area. Really, since there are no obstacles, there are only a few important points for pathfinding - start point, end point and warp gates. The ship can fly between these freely (normal flight or, between certain pairs of points, warp jump), so they are edges in your graph. They have well defined distances. You probably can't use A\* in such an environment, but as long as the number of warp gates isn't too high, Dijkstra's should suffice.

# Answer
> 2 votes
The special case with the warp gates makes it impossible to make A\* work with a formal heuristic as Liosan explained perfectly. So you will need to try something else. First of all we note that since there are no obstacles this isn't really a hard pathfinding problem since we have an almost perfect heuristic for finding the path without using the warp gates. The problem is knowing if going via a warp gate is faster.

Say we want to go from A to B we want to know two things:

* The cost trough normal space: Euclidean distance (ED)
* The cost via one warp gate: ED to entrance + warp-gate cost + ED from exit to target

Since your guess on these distances is so good you can create an 'Heuristic' that is almost always right, it computes the cost to the target directly (in O(1)) and the lowest cost via one warp gate (in O(N) where N is the number of warp-paths). If you take the minimum of these two for the cost of the node A\* will converge on either the direct path (if that is cheapest) or on a path via one warp-path (if that is cheaper).

Now this doesn't account for when a path via 2 or more warp-paths is cheaper than the direct approach. This unfortunately is a very hard problem since there are 2^N possible combinations of warp-paths to take. You can try an un-optimal approach by starting the algorithm from above all over again when exiting a warp-path, it will then either directly go to the target or take another warp-path which should most of the times be OK. But if there is a path of multiple warp-path that starts of in the wrong direction this will never work.

Note: this is just me thinking a bit about the problem, no guarantees, proofs or test-code here :)

# Answer
> 1 votes
A\* is an optimization of Dijkstra's algorithm, it works only when you can guarantee a minimum travel time between any two nodes. With wormholes you can't make that guarantee, so you should switch to Dijkstra.

---
Tags: path-finding
---


title: Map is rendering too slow

text:
# Question
Title: Map is rendering too slow
I have a basic 20x20 array that stores the map for my game. It either has a 1 or 0 to say a path and a non path. When I draw it on the screen, It seems to take to long to draw one at a time and looks like a snake is being loaded on the screen. I need them drawing faster.

# Set up the screen array

```
for(int i=0; i<sizeOfArray; i++)
    {
        for(int j=0; j<sizeOfArray; j++)
        {
            if (LevelOne[i][j]==0)//Path
            {
                screenChunks[i][j].Set(i*40,j*40,"Path.bmp", screen);
            }
            if (LevelOne[i][j]==1)//Wall
            {
                screenChunks[i][j].Set(i*40,j*40,"Wall.bmp", screen);
            }
            if (LevelOne[i][j]==2) //Hero
            {
                screenChunks[i][j].Set(i*40,j*40,"Hero.bmp", screen);
            }
        }
    }

```

# Draw the sprites

```
for(int i=0; i<sizeOfArray; i++)
    {
        for(int j=0; j<sizeOfArray; j++)
        {
            screenChunks[i][j].Draw();
        }
    }

    //Dynamically drawn each time
    SDL_FillRect(screen,0,0);

    //Hero Start Position
    hero.Draw();

    SDL_Delay(60);

```

# Sprite.cpp Draw Method

```
void Sprite::Draw()
{
SDL_Rect offset;

//Give the offsets to the rectangle
offset.x = PosX;
offset.y = PosY;

//Blit the surface
SDL_BlitSurface( sprite, NULL, Screen, &offset );

Height = offset.h;
Width = offset.w;

SDL_UpdateRect(Screen, 0,0,0,0);

```

}

# Sprite Setter

```
void Sprite::Set(int posX, int posY, string imagePath, SDL_Surface *screen)
{
PosX = posX;
PosY = posY;
ImagePath = imagePath;
Screen = screen;

if(ImagePath == "")
    return;

char * writable = new char [ImagePath.size()+1];
strcpy (writable, ImagePath.c_str());

temp = SDL_LoadBMP(writable);
sprite = SDL_DisplayFormat(temp);
SDL_FreeSurface(temp);
// free the string after using it
delete[] writable;
}

```

# Answer
Loading an image from disk every time you need to draw it is a bad idea. Terrible, in fact. Try loading once and reusing it.

Also, please have a look at calling `SDL_UpdateRect(Screen, 0,0,0,0);` on every sprite draw...

BTW, if you're doing the whole "writable" thing because `ImagePath` is an `std::string` and `SDL_LoadBMP` accepts `char*`, then you should google the c\_str() method.
> 6 votes

# Answer
For loading images only once, check out https://stackoverflow.com/questions/1729699/how-do-i-correctly-use-sdl-freesurface-when-dealing-with-a-vector-of-surfaces which introduces the idea of an image\_cache.

I've expanded on this on my blog here and then again once I'd updated my design to break up the class into smaller more manageable pieces here
> 1 votes

---
Tags: c++, sdl
---


title: What kind of projection is used here?

text:
# Question
Title: What kind of projection is used here?
Tibia is a 2d game, but it's sprites are drawn using certain kind of orthographic projection that is not the same I'm used to:

test http://dl.dropbox.com/u/62862049/Screenshots/97.png

I'm trying to figure out what projection is used here. I've guessed the following:

```
project(x,y,z) = (x-z/sqrt(2), y-z/sqrt(2))

```

It produces a circle very similar to that wheel, and alright cubes, but the spheres are not projected as perfect circles like the globe and the crystal ball on the picture above.

test http://o7.no/TfNmfZ test http://o7.no/TfMZSA test http://o7.no/TNCuCt

So which is the actual projection that game is using?

# Answer
You guessed properly. The orthographic projection you came up with is the one used for most of the objects. You can tell because parallel lines in the X, Y or Z directions all become parallel lines, indicating that there is no perspective projection. Also, horizontal lines remain horizontal, meaning that X' does not depend on Y. Similarly, Y' does not depend on X. You empirically found the remaining values of the projection matrix.

As for the spheres, it's probably an artist's decision to render them as spheres instead of ellipsoids because they would otherwise look weird. The waterwheel aspect ratio is much more correct in that sense.
> 7 votes

# Answer
I'd say that is mixed projection, indeed a lot of the items seem to follow the formula you describe, but with pre-rendered sprites one is not bound to follow one specific formula. I guess the creators simply thought that a non-round sphere looked stupid. Lots of 2D games is made with some mixed projection where stuff that looks stupid in the base projection is rendered in a different fashion.

Edit:
Actually, looking a bit further it seems that the projection varies from item to item, if you assume that the box to the right is as tall as it is wide, then it is around `(x-1/3*z, y-1/3*z)`, but the water wheel and the house seems to be close to your suggestion.
> 1 votes

---
Tags: 2d, 3d, graphics, sprites, projection
---


# Question
Title: Why do mesh classes still contain vertex arrays if VBO's exist?
I find I'm a bit confused about the practical use of resource management in combination with memory not tied to the CPU. Correct resource management is often recommended in game tutorials, books and on websites to ensure the same heavy data is not loaded in memory more than once, but cached and passed out whenever needed. This seems to be a valid idea and I've built a couple of resource management classes more than once.

Resource caches work perfectly for, say, level data or audio files, but my understanding always comes crashing down as soon as we're talking about memory residing on the GPU (vbo's, textures). It would seem to me that a mesh resource class should have to store nothing more than a vbo index, yet every mesh class I look at (e.g. Ogre3D) manually stores vertex lists in mesh classes. I can't seem to grasp why that is done. What's the use of vbo's if you're storing the mesh data in your usual memory anyway?

This question is not about how vbo's work (I understand them conceptually), but more about how they're practically applied in game development.

Could someone please elaborate?

# Answer
> 7 votes
Basically, it's not easy to get the vertex data *back* from the video card once it's there. Keeping the vertex data available to the CPU allows for a number of things, here are a few:

* As melak47 suggests, it allows the developer to free up video memory by freeing a VBO, while being able to quickly replace the data without needing to read from disk again.
* It allows for vertices to be added or removed. Dynamic meshes may have vertices that need to be added or removed. For example, a chunk of dynamic terrain that needs to have the effects of an explosion applied to it.
* It allows for modification of positions or other attributes. This could be applying a formula/algorithm to alter the position, texture, color or other attribute of some or all of the vertices. Perhaps an object that morphs between different shapes.
* These buffers can also be used just for the initial creation of the VBO. You need somewhere to store your vertices as you build them up. These buffers could easily be used to store them, then you know the size of the data to send to the graphics card. And they could be cleared after if you no longer have need of them.
* It also allows you to create render paths without VBOs (although these aren't as necessary today as they used to be), and if you lose context for some reason (like alt-tabbing) re-creating the VBOs is easier.

All in all, having the vertex data close to the CPU allows the developer more options for what to do with the data. It makes more sense than automatically discarding the data, and leaves the choice up to the developer.

---
Tags: gpu, assets, vbo, memory
---


# Question
Title: What are file formats that store skeletal movements, and are there databases of them?
I have a set of 3d vectors representing the positions of a character's hand, foot, shoulders and so on. Is there any kind of easy to read file I can use to animate those with walking, standing, jumping etc motions? Is there a database with some of them?

# Answer
Most 3D animation/modelling programs support BVH file format for motion captured skeletal animations. There is free BVH database at https://sites.google.com/a/cgspeed.com/cgspeed/motion-capture/cmu-bvh-conversion and you can quickly test the downloaded animation at http://www.akjava.com/demo/bvhplayer/
> 5 votes

---
Tags: 3d, animation, skeletal-animation
---


# Question
Title: Getting .mesh & .skeleton from Blender2Ogre export
I have downloaded the add-on blender2ogre from this source : http://code.google.com/p/blender2ogre/

And I have created a simple mesh, with walking animation (similar to the gingerbreadman tutorial). My question is, whenever I want to export the project, I can only see the `.scene` export format. There is no option whatsoever to export as `.mesh` and `.skeleton`. Also, how can I export the walking animation separately, in other words, if my project have couple more animation, how can i separate those during export?

# Answer
> 1 votes
Maybe this thread on the OGRE Forum will help you:

> \[...\] If you want to export more than one animation and give them names you need to convert your actions to nla strips:
>
> go to the nla-editor, choose an action and hit the 'snowflake'-button next to it. this will create an nla-strip based on the action. Note that blender will create a new nla-track for each new nla-strip. you can keep the strips in different tracks or move them into one and delete the others.
>
> The exporter will export every nla-strip as an animation and give the animation the strip's name. One thing to pay attention to is, that nla-strips that are overlapping on the time-line will influence each other when exporting. The newest version of the exporter has an option to disable this influence. \[...\]

---
Tags: blender, ogre
---


title: Entity property system

text:
# Question
Title: Entity property system
In lieu of a typical implementation of entity-component systems, I've gone the data-oriented route described by Jason Gregory in *Game Engine Architecture*. This works really well for common properties that need to be present in practically every entity, like position, model information, and health.

```
// Common properties
namespace Entity
{
    Vector position[MAX_ENTITIES];
    int health[MAX_ENTITIES];
    Model::ID model[MAX_ENTITIES];
}

```

But what about when it comes to specific information like character status, AI behavior modifiers, and NPC descriptions? Only a handful of entities need this kind of information: who would expect a barrel to give out quests? It needs to be discrete for each entity, so flyweighting is ruled out.

```
// Rare properties
namespace Entity
{
    // Character stats
    int strength[MAX_ENTITIES];
    int intelligence[MAX_ENTITIES];
    int charisma[MAX_ENTITIES];

    // AI behaviour
    int aggressiveness[MAX_ENTITIES];
    int recklessness[MAX_ENTITIES];
}

```

Should I just grit my teeth and make every entity a blob of the same data? Or is there something else I can do to create distinctions between entity types?

---

**Edit:**

Here's a method I'm now considering. Hopefully I can program the systems to make use of this layout while still avoiding memory problems.

```
// Common entity data
bool            Entity::active      [MAX_ENTITIES];
Vector          Entity::position    [MAX_ENTITIES];
Quaternion      Entity::orientation [MAX_ENTITIES];
Vector          Entity::scale       [MAX_ENTITIES];

// Entity handles
Model::ID       Entity::model       [MAX_ENTITIES]; // Index into the Model::X properties
NPC::ID         Entity::npc         [MAX_ENTITIES]; // Index into the NPC::X properties
Script::ID      Entity::script      [MAX_ENTITIES]; // Index into the Script::X properties
Status::ID      Entity::status      [MAX_ENTITIES]; // Index into the Status::X properties

// Models
Material::ID    Model::material     [MAX_MODELS];
Mesh::ID        Model::mesh         [MAX_MODELS];
Skeleton::ID    Model::skeleton     [MAX_MODELS];

// Materials
Texture::ID     Material::colorMap  [MAX_MATERIALS];
Color           Material::diffuse   [MAX_MATERIALS];
Texture::ID     Material::normalMap [MAX_MATERIALS];
Color           Material::specular  [MAX_MATERIALS];
Shader::ID      Material::shader    [MAX_MATERIALS];

// You can see where this is going...

```

The benefits of this are that you only need to specify the data for the components you need, and it works well with my resource systems (which operate via handles). It also allows me to process each mesh in the same way, each animation in the same way, etc.

I'll post more if I run into any issues.

# Answer
> 2 votes
You could possibly use an entity system. I am not referring to your current implementation of an entity-component system. An entity system is designed to take away the use of inheritance of your entities (game objects), so that you may define complex ones.

If you don't already know... An entity system is a design that is split up into three major parts. The first part would be an entity, this defines an object in a scene/world, it is typically represented by an integer (as it's identifier), and nothing else\*. The second part of an entity system is components, these are usually represented by a data structure. A component could store practically anything, such as mesh, transform (position, rotation, scale, etc.), collision information, etc. One thing to note is, that a component, as I said, only stores data and does not contain any logic. The last part of an entity system is the systems, a system defines logic for your game. For example, say you wanted to move all the entities with an InputComponent and a PositionComponent, you would create a MovementSystem, which defines methods to move the entities (via the PositionComponent, typically through a function called processEntities or update).

\*entities do not store a list of their owned components

**NOTE:** An entity system is not an object oriented desgin, you could implement one in a procedural language, such as C. However, that doesn't mean you have to avoid classes all together, infact, they could benefit you.

**ALTERNATE IMPLEMENATIONS:**

There are various alternate implemenations you will find on the web, some examples are:

* components don't only define data, they also define logic, this is used with the Unity3d game engine (I personally dislike this design, but it works)
* entities store a list of their components (in my opinion, this is a very bad design, as you could benefit from storing it in one location)

**EXAMPLES**

A very famous Java implementation, the Artemis framework: http://gamadu.com/artemis/

A C++ implemenation (this library is mine): http://github.com/miguelishawt/anax

**FURTHER READING**

There are various links on entity systems (on the bottom of the page) here: http://gamadu.com/artemis/tutorial.html

---
Tags: c++, entity-system, data
---


# Question
Title: What happens to a D3D11 application when Windows hibernates?
In D3D9 there was the concept of a "device reset". When a device reset occurred textures created with D3DPOOL\_DEFAULT had to be recreated, but textures created with D3DPOOL\_MANAGED didn't, because, according to MSDN, a duplicate copy is kept in system memory.

In D3D11, the concept of a device reset has much less prominence. But since the video card loses power during hibernation, textures must be stored somewhere else beforehand.

So how does Windows 7 preserve video card resources during hibernation?

* Is it like D3DPOOL\_MANAGED where a duplicate copy is wastefully kept in system memory,
* or does it only copy resources back from video memory immediately before hibernating, then returns them to video memory after resuming?
* Or do such resources need to be manually recreated and I'm missing something in the API?

It looks like graphics drivers implement DxgkDdiSubmitCommand to allow data to be copied to and from video memory, but it's unclear whether Windows actually does this when hibernating.

# Answer
System memory also loses power during hibernation, as the system is completely powered off during hibernate. Windows deals with both system memory and video memory the same way: it dumps them to disk. Hence, it is only copying out video memory when necessary, when hibernation is invoked.

If you meant stand-by mode, where the system is put into low-power mode but not shut down, then the system memory retains its contents. The GPU can either also be put into a low-power state similar to the CPU (if the GPU supports it), allowing it to keep its video memory contents (which of course happens "for free" for shared-memory integrated GPUs), or the GPU memory can be transparently saved out to system memory when the system goes into stand-by with absolutely no need for any work on the part of applications. When the system comes out of stand-by and the app starts accessing its GPU data again, the OS will stream those resources back into video memory automatically.

For "Hybrid Sleep," which is a combination of the two, Windows will dump the video memory to disk along with system memory, while otherwise putting the system into normal stand-by mode. That simply allows the system to deal with power-loss during stand-by mode by simply booting up as if you had hibernated.

**This is all possible because WDDM completely virtualizes video memory.** Your application does not and need not care whether any particular texture or buffer is actually in video memory. WDDM will move your resources out of and into video memory as it sees fit, and it all happens transparently to the application.

This allows a large number of applications to share the GPU. It allows the OS to stream out data from background apps that have D3D11 contexts but which aren't being actively used (e.g., the desktop when you're playing a full-screen game). It also of course allows transparent support for hibernation/sleep.
> 6 votes

---
Tags: directx, directx11
---


# Question
Title: How to linearly "blend" between multiple 3D points?
I have a set of 3D points that I need to "blend" between. Lets say I have points \[A,B,C\] and I have the amount I want to blend each as \[0.5, 0.2, 0.8\], how can I blend between these points with the amount I need?

Obviously if I just had 2 points I could use the vector math `(A + (B - A) * ratio)`.

**Method 1:** I'm currently using a weighted average, which I suppose gives me the weighted center, but I need to try different blending styles to see visually which looks best.

**Method 2** What If I did this:

1. Calculated a difference vector, each 3D point against the default point (I do have a default point)

`A - Default`
2. Then multiplied this difference with the blend amount

`(A - Default) * Amount`
3. And added these up, would that work? What result would I get?

`(A - Default) * A_Amount` \+ `(B - Default) * B_Amount` \+ `(C - Default) * C_Amount`

# Answer
> 5 votes
It is called a barycentre. Here your point is:

```
P = (A * A_ratio + B * B_ratio + C * C_ratio) / (A_ratio + B_ratio + C_ratio)

```

Badly, Wikipedia have no dedicaced page for this, so you'll have to understand the explanation of center of mass, which is just a generalization of barycentres applied to physics.

EDIT: your second method is equal to:

```
P - default

```

Proof:

```
((A - def) * A_r + (B - def) * B_r + (C - def) * C_r) / (A_r + B_r + C_r)
= (A * A_r + B * B_r + C * C_r) / (A_r + B_r + C_r) - def * (A_r + B_r + C_r) / (A_r + B_r + C_r)
= P - def

```

---
Tags: 3d, animation, geometry, blending, tweening
---


title: GLUT Window not responding

text:
# Question
Title: GLUT Window not responding
I'm trying to calculate the delta time of my program. In main, I call:

```
glutInit(&argc, argv);

glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);

glutInitWindowSize(250, 250);
glutInitWindowPosition(100, 100);

glutCreateWindow("OpenGL Renderer");

InitGL();

glutDisplayFunc(DrawGLScene);
glutReshapeFunc(ReSizeGLScene);
glutIdleFunc(idle);

glutMainLoop();

```

My idle func:

```
void idle(void)
{
    int time;
    time = glutGet(GLUT_ELAPSED_TIME);
    delta = time - lastTime;
    lastTime = time;
    glutPostRedisplay();
}

```

I have these global variables:

```
int lastTime;
int delta;
float rtri; //Angle for triangle
float rquad; // Angle for quad

```

In the render method, I call:

```
// ...
glRotatef(rtri, 0.0f, 1.0f, 0.0f);
// ...
rtri += 0.2f * delta;
rquad -= 0.15f * delta;

```

Whith this code, I can't resize the window and if I press the close button, the window isn't responding anymore.

How can I fix this?

# Answer
> -2 votes
A friend helped me fixing it. He wrote a new Sample using double buffering. If you are interested, you can see the code at Pastebin.

---
Tags: c++, glut
---


# Question
Title: Game Center: Leaderboard score inconsistencies
## Background

I'm currently developing a simple library that mirrors Game Center's functionalities locally. Basically, this library is a system that manages achievements and leaderboards, and *optionally* sync it with the Game Center. So, if the game is not GC enabled, the game will still have achievements and leaderboards (stored inside a plist). But of course, the leaderboards will then only contain the local player's scores (which is kind of useless, I know :P).

---

## Problem

Currently I have coded both of the achievements and leaderboards subsystems. The achievements subsystem have already been tested and it works. I'm currently testing the leaderboards subsystem using multiple test user accounts. I loaded the test app on a device and on the simulator, both logged in with 2 different user accounts. Then I performed these steps:

1. I first used the device to upload a score.
2. Then, I ran the simulator, and *the score submitted by the user on the device is shown*. Which is cool.
3. Then, I used the simulator to upload a score. *But on the device, still, only one score is listed.*

I checked on the Game Center app (to see if the bug lies within my code), and I got the same thing. Under "All players", there is only one score on the device, but there are 2 scores on the simulator. I wanted to make sure that the simulator is not causing this, so I swapped the users on the device and the simulator, and the result is still the same. In other words, the first user is oblivious of the second user's score, but the second user can see the first user's score.

*Then I tried with a third user.* The result: the third user can only see the scores of the first user and himself. The second user still sees the scores of the first user and himself. The first user only sees his own score.

Now here comes the weird part. I then make the first user and the second user befriend each other. The result: *under "Friends", the first user can see the second user's score*, but under "All Players", the first user's score is the only one listed.

---

## Screenshots

The first user sees this:

The second user sees this:

---

**So, is this a normal thing when using sandboxed GC accounts?** Is this behavior documented somewhere by Apple?

# Answer
I think the inconsistency is due to the fact that the server-side scores are not updated in real-time upon submission, because I came back to check after a day, and found out that the the scores were consistent.
> 1 votes

---
Tags: ios, game-center
---


# Question
Title: Ready to use leaderboard service. Is any?
I'm looking for ready to use thirdparty leaderboard service where player's achivementes and scores can be placed. I'd intagrate it into my game to allow players push scores and locate themselves in the tables of tops. It would be nice whether anybody experienced share some points with me.

# Answer
> 2 votes
I've had good luck with ScoreLoop. They may just be mobile, but worth checking out.

http://www.scoreloop.com/developers/social/

# Answer
> 0 votes
That's quite a coincidence, since we at Mochi Media are just about to release our Scores API: https://www.mochimedia.com/community/forum/topic/beta-testers-wanted-new-mochiscores-unity3d-api

There's a doc draft for them, it includes a link to try it out: https://gist.github.com/4356705.

Just keep in mind it's not a release yet, we'll ship a better version in a couple of days. The client side code is not polished yet, but the server code has been working for several years with our Flash API.

UPD: I looked up your background and figured you're a Java developer. Since our Unity code is written in C#, it shouldn't be hard for you to re-use the API inside Java.

# Answer
> 0 votes
Try playtomic.com. They have a good API which matches your requirements.

---
Tags: leaderboards, achievements
---


# Question
Title: Should I get this game development diploma after I finish my CS undergraduate program?
I am currently pursuing a computer science bachelor's degree. I've always wanted to enter the game development industry, and a friend of mine suggested this diploma at KDU university after my bachelor's. It's in a different country, but I want to travel anyway so I don't really mind that.

From that link, the courses are:

* Introduction to Computer Games
* Fundamentals of Programming
* Personal Development and Leadership Skills I
* Technopreneurship
* Computing Mathematics
* Graphics & Animation Basics
* User Interface Design
* Object Oriented Systems Analysis and Design
* Multimedia Authoring
* Networking and Operating System
* Fundamentals of Object Oriented Programming
* Database Systems
* Games Architecture and Design
* Java Programming
* Games Programming I
* Internet Technology and Application
* Games Programming II
* Audio and Visual Game Elements
* Artificial Intelligence for Games
* Games Mechanics
* Internship Personal Development and Leadership Skills II Project

I know some of these topics already through my CS degree -- databases, object-oriented programming and artificial intelligence for instance are all part of my degree. Plus, for example, I know the basics of graphics, like OpenGL, and animation through translation, rotation, and scaling.

Do you guys think it would be worth it? All the *similar* courses I've taken in my current degree were "general" stuff, not oriented towards games.

Game development is the job I really want, but if I couldn't get a job in it, or enroll in something in it, I ll probably end up in some other industry, and game development will probably end up being just a hobby.

# Answer
I'm not in the industry currently but I took a bachelor of game's graphics programming after doing a normal IT one. In my case it was at the same university so I could transfer credits and skip the classes I tool already. Both of them counted as an IT degree so technically I have 2 degrees for the same things.

I just had to take a few game related classes like Real-Time Rendering (OpenGL). And then there where the gamedev specific classes was mostly team focused and included writing modules for Unreal, NeverWinter Nights 2 and a main project (it was open to what your group wanted to do, I did the all the programming of a game engine from scratch in C++ and OpenGL with Bullet Physics integration, simple QT UI for the editing, Lua scripting and such so it was a fairly heavy semester but fortunately it was the only class I was taking due to the course credits. The game it self was kind of crap but it was more of a technical demo and I learned a lot doing it.

Personally I think you would probably be better of spending your time on putting together some projects that you can show prospective employers. Grab a copy of Game Engine Architecture (theres also 3D Game Engine Architecture which is a totally different book but not bad either) and read through and experiment with the techniques that are used. You can come up with a project that 1 person can tackle and get even paid for. Lots of of the game jobs are for phone apps now days. Otherwise you can go the indie route. What ever it is, keep it simple, if your mainly a programmer try and choose something with a minimal art style since doing both is going to be time consuming, play your strengths, don't over optimize (a simple game might not need any optimization), don't try and build an awesome fully featured game engine just come up with a game design and code what features are needed. Then when you go for a full job you have that to stuff to show people. Otherwise do some experimental coding and put some up on github of wherever, just things like some example multiplayer networking code, custom memory allocators, or whatever. Even if you end up not going for game jobs it's still basic useful programming (games tend to cover a fairly large chunk of programming concepts).

Also think about if you want to write a game engine yourself. Many game jobs now days are grabbing something like the Unreal engine and using that. But those tend to reduce what a single programmer can do since most of the programming is done just leaving scripting. Maybe an engine that's a bit more DIY like XNA (MonoGame might be better since MS stopped supporting XNA), Ogre3D, Torque3D, libgdx or Unity (not actually sure how DIY Unity is). Those will stop you getting bogged down on the simple stuff like how to put pixels on the screen and allow you to do the higher level stuff without it being completely predone.

Finally are you a programmer, is that what you want to do? Understand that many positions are more scripting rather than engine internals since they use prebuilt engines. Perhaps you are more interesting in things like gameplay, level design, the art stuff (meshes, textures, character creation and so on).
> 0 votes

# Answer
Seems like that diploma is a lot about basic programming. As far as you have learned what you should in your bachelor it's hard to classify that part as anything better than a waste of time. So if you want a game diploma, you should find one that is aimed at programmers, or see if it would be possible to take only part of the course.

That said, I think the best thing you can do after getting your bachelor is to get a job. After finishing your bachelor, the thing you need the most in order to land a job in the game industry is not a game course, it is real world experience, even if that experience doesn't look remotely like games.
> 5 votes

# Answer
Those classes look like (below) BSc level so it seems like a waste of time if you already have a BSc in computer science. There are several institutes that have a MSc Game & Media technology programme, try looking for those or other MSc programs at credible instutites. Also definitely watch this before deciding: http://penny-arcade.com/patv/episode/on-game-schools
> 3 votes

---
Tags: education
---


# Question
Title: Why is keeping a constant FPS harder than keeping high FPS?
I've noticed this ever since I started playing games, and now see it in my own experiments. If I don't do any capping my game runs at 200~250 FPS, with random drops to 150FPS, but if I cap the FPS to 60 using a simple precision timer + sleep method, the game will sometimes (much more frequently than I want) render at ~40FPS during complex scenes.

I suspect this is simply because my process gets dequeued by the OS during the time I used to spend rendering the other 140 frames, meaning there's more context switches going on, as well as allowing other processes to steal all the cores and do CPU-intensive tasks in them. At the same time, this doesn't feel right, and one would think modern OS's are able to do scheduling that is good enough to avoid that.

So, my question is, are there any techniques to optimize my game for constant FPS rather than high-but-with-lots-of-variation FPS? Should I just make sure my game logic is being updated in a constant rate and don't worry about render rates?

Here's how my FPS-limiting code looks like (somehow pseudo code):

```
const maxFrameTime = 1/DESIRED_FPS; // say 60

while(running()) {
     now = query_precision_timer();
     thisFrame = now - lastFrame;
     lastFrame = now;

     while(thisFrame > 0.) {
          Update();

          thisFrame -= maxFrameTime;
          now += maxFrameTime;
     }

     Render();
}

```

# Answer
> 8 votes
Depending on how you're measuring FPS, your individual frame time may be spiking as high in both the "150FPS" and "40FPS" cases (missing the 16ms limit for a smooth 60fps and, assuming a 60hz refresh rate, having an effective display time of 33ms / 30fps for that individual frame.) This may be partially obscured by the higher framerate version having enqueued more updated frames, and thus still having something to swap in on the next vsync. Some back of the envelope math: 250fps ~ 4ms/frame. If 13 of those spike up to 33ms instead, we'll still get 150 frames in a second: Solving x for (1000-x\*33) / 4 = (150-x)

A huge chunk of this can be caused by your code blocking (creating textures, doing file IO, paging data back in, locking in-use textures, even simply allocating while another thread holds the relevant lock...) or even just having a lot to do (unfortunately syncronized timers, sudden bouts of pathfinding, etc...). If you want to try to iron these out, rule 1 is to use a profiler. Rule 2 is to use a profiler. Rule 3 is to use multiple profilers (both to inspect possible graphics API related hitching with vendor GPU profiling tools, and to inspect inspect other possible causes with standard CPU time profiling. (You may wish to create a setup where the profiling results of spiking frames are automatically recorded and the rest discarded... having lots of snapshots will help you determine if it's spiking in the same place all the time or not.)

I'll further note that most games cap to 60FPS by way of vsync, not timer. Even the highest precision timers can have problems on some systems, be it unreliability (because e.g. CPU cores are clocked at different rates) or low precision (even if your API exposes microseconds, that doesn't mean you're getting microsecond precision -- you might not be even getting millisecond precision, depending on the API and hardware). While I wouldn't bet money on it, it's entirely possible your timing code is currently your entire problem when targeting a smooth 60fps. I'd wager it's at least part of your problem, however.

# Answer
> 2 votes
I don't see protection again spiral of death in your code.

You understood the concept very well. You even decoupled the render cycles from the logic/simulation update cycles.

I would suggest to try this, rename maxFrameTime to desiredTimeStep or timeStep.

And change this:

```
while (thisFrame > 0.)

```

To this:

```
while (thisFrame >= desiredTimeStep)

```

What is Spiral of Death? Well, when you do thing like this:

thisFrame = now - lastFrame;

What happen when the player pauses the game for a lot of time and when resuming the delta between now and lastFrame is a really big number? because the game was not updating (consuming that time) for a lot of time and it accumulates. The result is that your while (thisFrame \>= desiredTimeStep) will run hundreds or even thousands of iterations until thisFrame is less than desiredTimeStep (lees than 0. in your original code). This can cause all types of undesired effects, like an enemy that was far away come and kill the player without the player can do anything about it because the game is running hundreds of updates before render, and the player don't get and updated view of what is happening.

Tip: you can implement this protection as a simple if statement. After calculation of thisFrame and before entering the inner while loop, check if thisFrame is more than your maximum allowed frame time, and if greater cap it to you maximum allowed. The reason to tell you to rename your maxFrameTime constant to desiredTimeStep is that maxFrameTime is a name more intuitive to implement protection again spiral of death, while desiredTimeStep is a more intuitive name to refer to the expected step between frames. Note that the maximum allowed frame time must be various times greater than desiredTimeStep, to allow resync when the game lagged for some reason but preventing hundreds of iterations of the inner loop. I'm happy with 250000000 nanoseconds.

Note: pause by player may not be the better example of when spiral of death can occur, because your game may be stopping only the inner loop when paused and not the outer loop, allowing the thisFrame to continue being calculated even when paused. So you avoid spiral of death that way, but it still can occur if your game lag for some reason (you opened a heavy program while game still running in a machine that can run your game smoothly only if no other applications are running at the same time).

If you want to improve your main loop even more, please, read this: http://gafferongames.com/game-physics/fix-your-timestep/

---
Tags: architecture, optimization
---