title: Model in Blender GLSL to XNA HLSL

text:
# Question
Title: Model in Blender GLSL to XNA HLSL
Is it possible to make model in Blender, with enabled GLSL, add multiple textures, etc, and then just load it in XNA, where's own HLSL? Will it work?

# Answer
> 2 votes
In a word, No. But to get you started, you will need to use custom export scripts in Blender (I export to FBX format), and a custom content pipeline processor if you want to import the GLSL/materials/effects. This sounds like a lot of work; but at least now you know what you're googling for.

---
Tags: xna, xna-4.0, hlsl, glsl, blender
---


# Question
Title: How to implement a track for a wipeout-style game on a mobile device?
I was wondering what is the best way to manage a 3D track for a game with the same mechanic as Wipeout on a mobile device. Build a track out of multiple segments and load new segments as the player advances or build just one single mesh, maybe with multiple level of details ?

I'm very unfamiliar with this kind of problems so suggestions for other approaches are welcome.

# Answer
> 3 votes
For 3D games, usually you implement two tracks : one with very basic level of detail (just a floor and 2 walls) that you use to compute the collisions and physics. Then you add another data, probably with different LODs for rendering, that you can load as the player advances.

Also if your game stays basic, meaning you keep the same width along the whole track, you can just store a 3D curve, and use it for the collisions.

---
Tags: 3d, racing
---


# Question
Title: 2D Procedural Terrain Generation - Guaranteeing connectedness?
I'm working on a 2D platformer in XNA. One of things I'd like to be a main design characteristic is procedural content generation. The first step of that is to procedurally generate the terrain. So, I've done loads of research on how to generate Perlin noise, smooth it out, play with parameters and all that jazz. I've also spent loads of time at pcg.wikidot.com. The problem I have is generating a level that is 100% connected. Meaning, it's possible for the character to get from the left part of the level all the way to the right part.

Right now, I use the perlin noise to generate a sprite when the noise value at that point is \< 0.

Here is a video of the issue I'm having (please excuse the crazy background issues and the fact my character gets stuck when I generate a new level).

http://screencast.com/t/uWJsIGLoih

As you can see in the video, the terrain looks interesting enough, but you can't do a whole lot because the Perlin noise compartmentalizes the level into small, random chambers.

I attempted to perform a random walk and overlay the perlin noise on top of it, so I guarantee a path from left to right. The issue with that is illustrated below: http://screencast.com/t/ilLvxdp3

So my question is: What kinds of things can I do to ensure the player can get from the left part of the level to the right part of the level?

# Answer
In using the word *connectedness*, you've come within a hair's breadth of the tool best suited to determining a solution: graph theory.

Connectedness is a property of graphs. Graphs can be either connected or disconnected (as you're experiencing, AKA a multigraph). Any game level, in any number of dimensions, can be represented as a graph, and logically, this is often the best way to manipulate them. Your game world is a graph in terms of the adjacency between the individual building blocks in your world; and also at the level of connectivity between your various areas. You can use the former to derive the latter.

There is a crucial point to consider when doing working with (2D) levels as graphs, and that is *planarity*. Depending on your requirements, planarity may or may not be a concern. Given your use of noise, I expect the latter, however I outline the options here so that you know what they are.

**Planar graph** \- simplest example is a labyrinth. A labyrinth differs from a maze in that it contains no branchings -- it is *unicursal*. If you were to take a solid block of shrubbery(!), and generate a labyrith through it, then at no point could a turning that the labyrinth takes, run into an existing path. It's a bit like a game of Snake, really -- if the path is the snake's body, it cannot be allowed to bite/intersect itself. *Further*, you could have a planar maze; this would branch, but at no point could the branches be allowed to intersect existing parts of the maze already generated, just as with a labyrinth.

**Non-planar graph** \- Simplest example is a city street map. A city is essentially a maze. However, it is a highly-connected maze in that there are many individual road routes to get from one place to another. Moreover, a non-planar graph embedding allows crossings, which is exactly what intersections are. And as we know, a city is not a city without intersections. They are integral to traffic flow. In games, this can be good or bad, depending on your goals. Good level flow allows AI to act more easily, and exploration to be freer; while on the other hand it also allows a player to get from startpoint to goal quickly -- potentially too quickly.

This brings us to your approach, which is to use noise. Depending on Perlin noise output is interpreted, it can have some level of connectedness as the macro scale, but it is not designed for 1-connectedness (a single graph). This leaves you a few options.

1. Drop the use of Perlin noise and instead generate a random, planar (non-crossing), connected graph. This provides maximum flow control. However this approach is non-trivial, because graph planarity requires the identification and removal of the Kuratowski subgraphs K3,3 and K5; as well as producing a subsequent planar embedding; both of which are NP-complete problems. This is without a doubt the hardest approach, but it had to be mentioned first to know where you stand. All other methods are a shortcut of some sort, around this method, which is the fundamental math behind maze generation.
2. Drop the use of Perlin noise and instead generate a random, non-planar graph embedded within a planar surface (AKA a planar embedding) -- this how games like Diablo and the roguelikes can be made to work easily, as they both use a grid structure to subdivide a planar space (in fact, the vast majority of levels in the roguelikes DO allow crossings, evident in the number of four way intersections). Algorithms producing the connectivity between cells or template rooms are often called "carvers" or "tunnellers", because they carve empty space out of a block of solid rock, incrementally.
3. Do as option (2), but avoid crossings. Thus both embedding (level geometry) is planar, and the topology (level flow) is also planar. You will have to be careful not to generate yourself into dead-ends, if you wish to avoid crossings.
4. Generate your map using noise. Then, using a flood fill algorithm on every cell in your unconnected level (which is a graph, albeit multipart and grid-based), you can deduce all unconnected, discrete subgraphs within that greater multigraph. Next, consider how you want to connect each individual subgraph. If you prefer to avoid crossings, I suggest a sequential connection of these. If not, you can connect them any way you wish. In order to do this organically, rather than producing hard, straight passages, I would use some sort of coherence function to meld the closest points of each pair of subgraphs (if linking sequentially). This will make the join more "liquid", which is in keeping with the typical Perlin output. The other way you could join areas would be to nudge them closer together, so there is some minimal overlap of the empty spaces.
5. Generate an excessively large map using noise. Isolate all subgraphs as described in option 3. Determine which is the most interesting, according to certain criteria (could be size, or something else, but size would be easiest). Pick out and use only that subgraph, which is already completely self-connected. The difficulty with this approach is that you may find it hard to control the size of your resultant graphs, unless you brute force generate a really large map, or many smaller ones, to pick your perfect subgraph. This is because the size of the subgraphs really depends on the Perlin parameters used, and how you interpret the result.

As an aside to the last two, something I'm sure you have already done, but just in case not: Create a minimal Perlin noise test case in Flash. Play around with parameters until you get a higher degree of connectivity between your "island" areas. I don't think this could ever solve your problem 100% across all generations, since Perlin noise has no inherent guarantee of connectedness. But it could improve connectedness.

Whatever you don't understand, ask and I will clarify.
> 13 votes

# Answer
General approaches to this problem:

1. Construct the map in a way that guarantees connectedness from the start. Many of the dungeon generators on PCG wiki work this way.
2. Generate a potentially disconnected map, and then write something (maybe a pathfinder) that checks for connectedness. Throw away the maps that don't work.
3. Generate a potentially disconnected map, and then fix it up whenever it's not connected. Whenever your checking algorithms find an area that's impassable, blast tunnels, build bridges, add teleporters, etc..
4. Generate a potentially disconnected map, and then give the player tools to connect things when needed. Turn the disconnected map bug into a feature. Terraria, Minecraft, etc. do this.
5. Generate a potentially disconnected map, and then make the player restart or move to a different level if the level can't be completed. I believe some roguelikes do this.

I agree with Kylotan that a noise function probably isn't ideal, but noise functions can do a lot and you might be able to fix it up in some way. See this article for some ideas.
> 5 votes

# Answer
That video's just confusing, and I can't work out what you're trying to show with it to be honest. But I would suggest Perlin noise is probably the wrong algorithm for the job. It's designed for smoothly undulating continuous entities, whereas you're trying to make scattered and discrete entities. What would probably work better is using random values to re-arrange and adjust hand-designed arrangements of platforms to ensure that the resulting area is playable.

There's some information on how Spelunky did this here: http://tinysubversions.com/2009/09/spelunkys-procedural-space/
> 2 votes

# Answer
Try modifying the perlin value based on height, i.e. at the bottom add 1 to the noise value, at the top subtract 1 from the noise value, and in between linearly interpolate between 1 and -1. This way, at the bottom you will almost be guaranteed to get a value \>= 0 and at the top you will be almost guaranteed to get a value \<= 0.

This is assuming values \< 0 is supposed to be air. If I understand your description correct, you'll have to switch it around.

Cheers.
> 0 votes

# Answer
A simple approach that's easy for you to adopt given your existing code is to keep generating random maps until one meets your connectedness constraint.

You can likely quickly check your connectedness constraint using a flood fill from the starting position. Does it fill all the way to a legal end-point?

You can likely do thousands of such checks per second, so its likely a perfectly acceptable hack.
> 0 votes

---
Tags: xna-4.0, procedural-generation, terrain-rendering, platformer
---


# Question
Title: What is the best Android gaming engine for Billiards game?
What is the best engine/way to go with when implementing a 2D billiards game? I am thinking about Emini Physics Engine, which is free for use and stuff, but maybe you can give me some pitfalls about this engine and recommend some other or encourage me into using this?

# Answer
I would definitely recommend researching how to roll your own for this task. It is probably easier than you might think. There is still a lot of complexity there, but it would be a great learning exercise.

I highly recommend reading Pool Hall Lessons: Fast, Accurate Collision Detection Between Circles or Spheres by Joe van den Heuvel, Miles Jackson.
> 1 votes

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


# Question
Title: Component-based game object systems in practice
Let's see history of success. Which popular games (and game engines) were built using component-based game object system? Each answer should contain:

1. Game Title (one per answer)
2. Author / Company
3. Year
4. Development time (optional)
5. Link to postmortem (optional)
6. Links to docs/source code (optional)

# Answer
> 19 votes
**Resistance 1-2 (possibly 3)** (2006-2008) by *Insomniac Games*

Terrance Cohen lists these games in his A Dynamic Component Architecture for High Performance Gameplay talk from GDC Canada 2010.

Not sure if this was applied to the recent Ratchet & Clank games.

# Answer
> 18 votes
**Dungeon Siege** by *Gas Powered Games*

Scott Bilas released a lot of information about Dungeon Siege which featured component-based systems, amongst other things.

Dungeon Siege was released in 2002.

# Answer
> 13 votes
Unity3D uses a component-based system by default. It is superb for creating game entities from a text file and dependency injection.

```
function createEnemy() {

   // extract AI type for enemy
   // definition is a custom structure holding parameters to create the enemy
   var aitypename = definition.ai;

   // AIType can be an interface or abstract class
   // you can create a component from a string or from a type
   var ai : AIType = this.gameObject.AddComponent(aitypename);
   ai.setup(definition.ai_settings);

   // set rule for enemy when it is destroyed
   this.gameObject.AddComponent(definition.when_destoryed);

}

```

Those components could look like this

```
class AI_Scout extends AIType
{
  // called per update-frame on the game-object with this script
  public function Update() {
    // run Scout AI here
   }
}

class Spawn_Ammo_On_Destroyed extends When_Destroyed
{
   // automatically called by the engine when the game object this script is attached to is
   // destroyed
   public function OnDestroyed() {
    // spawn ammo
    }
}

```

# Answer
> 8 votes
1. Thief: The Dark Project
2. Looking Glass
3. 1996 - 1998
4. 2-ish years
5. Postmortem

# Answer
> 8 votes
**Tony Hawk Pro Skater 3**
Developer: Neversoft
Year: 2001
Time: About two years
Post Mortem: Evolve Your Hierarchy (probably the most linked component-based article)

# Answer
> 2 votes
To my knowledge the best project i have seen is Burger Engine. jst download the code and check how well they have implemented.The whole thing is data-driven from xml and they used very well entity based architecture.worth looking at it.

http://code.google.com/p/burger-engine/source/browse/

---
Tags: component-based, game-industry
---


# Question
Title: How can I achieve the realtime clouds/sky effect of Lumion?
Does anyone know how they do this? They're not truly volumetric - you can't fly through them - it's still a texture.

http://vimeo.com/16534222

It looks like it's a perlin based solution, but I really can't work out how they get the fantastic lighting! How can I achieve this effect?

To be clear, I'm not talking about the sky (which would be a variation on CIE/Preetham) or sun shafts or any other effect - i'm talking purely about the clouds, which are rendered straight to the skybox texture.

# Answer
> 3 votes
For realtime fog/cloud rendering you can take a look at this article from GPU Gems 3.

If you are looking for Sky / Atmospheric Rendering, over at vterrain they have a nice collection of articles.

For light/sun scattering I suggest you take a look at the blog of Fabien and again GPU Gems 3

---
Tags: sky, volumetric-light
---


# Question
Title: Where can I learn about Substance maps for 3ds Max 2012?
A new feature in 3ds max 2012 is Substance procedural textures.

Are there any good online libraries or resources for substance maps?

# Answer
Currently, Allegorithmic restricts who can publish Substances, so you can only get them from their sales points. TurboSquid Substances, Allegorithmic.com, and Unity's Asset Store.

They have signalled that they are reviewing this policy.

My personal opinion is that until they do, they have no hope of competing with FilterForge's business model (which encourages an ever-growing library of free filters, increasing the attractiveness of their product).
> 1 votes

---
Tags: textures, maps, 3dsmax, substance-engine
---


# Question
Title: How'd they do it: TF2 payload cart glow?
How did the creators of TF2 make the glow on the payload cart visible through walls? Is it possible to implement this in Unity's shaderlab?

# Answer
> 2 votes
To make a shader that only draws when occluded by other geometry, use ZTest Greater. To always draw, use ZTest Always. Ensure your shader is late in the render queue. The glow itself is a different problem, personally I like rim lighting effects for such things - like inner glow rather than outer glow.

---
Tags: graphics, shaders, unity, glow
---


# Question
Title: gluLookAt vs glTranslate + glRotate and camera transformation matrices
I'm getting my hands dirty in OpenGL and something is bothering me a bit.

It's my understanding from reading about the subject that a call to gluLookAt basically multiplies a matrix on the stack that moves the world in a way such as to "emulate" a camera. After my reading, I came under the impression that calling:

```
glTranslatef(0.0f, 0.0f, -10.0f);

```

then perform some drawing was equivalent to calling:

```
gluLookAt(0.0f, 0.0f, 10.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);

```

However it is not and I'm at a loss as to where the flaw is in my reasoning. I also tried manually computing a matrix from a position, a direction vector and an up vector but failed to find texts describing this process.

Can anyone shed some light on this? I'd much rather like to understand the underlying matrix creation process to create a transformation matrix that corresponds to an inverse camera transform, but just getting gluLookAt to behave the way I want would be great as well. Thank you.

EDIT: Turns out my mistake was that I mistakenly set the up vector to \[0, 0, 1\] instead of \[0, 1, 0\]. I'm checking the answer below to see if it's giving me satisfying results regarding matrix creation.

# Answer
I think that for creating the matrix you should get the front vector first, you do:

```
Vector3 vFront = Camera.vTarget - Camera.vPosition,
    vUp = Camera.vUp, vRight(0,0,0);
vFront.Normalize();
vRight.Cross( vUp, vFront ); // Up x Front = Right
vRight.Normalize();
vUp.Cross( vFront, vRight ); // Front x Right = Up
vUp.Normalize();

```

then you build the matrix from these vectors as follows:

```
Matrix4 m;
m._14 = m._24 = m._34 = 0.0f;
m._44 = 1.0f;

m._11 = vRight.x;
m._21 = vRight.y;
m._31 = vRight.z;
m._41 = - (vPosition.Dot(vRight));

m._12 = vUp.x;
m._22 = vUp.y;
m._32 = vUp.z;
m._42 = - (vPosition.Dot(vUp));

m._13 = vFront.x;
m._23 = vFront.y;
m._33 = vFront.z;
m._43 = - (vPosition.Dot(vFront));

```

I don't know much about what I'm talking about but my renderer works so chances are this is the right matrix formula.

No... actually you may need to transpose the result, depending on your math conventions.

I believe you could have an error with your current values because your camera "front" vector is aligned with the "up" vector, and if I guess well that could result in a zero-length "right" vector. Again I'm not sure if this is right...
> 6 votes

# Answer
In addition to Pablo's answer, this link describes what `gluLookAt` actually does.
> 1 votes

---
Tags: opengl, matrix, coordinates
---


title: Zoom to mouse cursor DirectX

text:
# Question
Title: Zoom to mouse cursor DirectX
I have a DirectX scene. I want zoom in using mouse wheel to the mouse location. I am able to zoom the view to center of screen but I need to zoom to mouse location. Please suggest how it can be done. Thanks

# Answer
> 3 votes
You need to send a ray from the mouse cursor along the camera view direction through the scene and see where it intersects (take the intersect position closest to the camera position) to know the 3D position. After that you can easily zoom in there by placing the camera closer.

This is often called unprojecting and can be done by fiddling a bit with your projection matrix and the screen coordinates of your mouse cursor.

---
Tags: directx
---


# Question
Title: Normal transformation and homogeneous coordinates
I'm very confused about the math behind the model/affine transformation expressed in homogeneous coordinates. Reading this article, I understood that a generic vector is transformed by multiplying it by the model matrix (M), while a normal must be multiplied by the inverse-transpose of the model matrix (M^-T) in order to preserve the dot product between P and N (this was wrong).

Now I don't fully understand how to use the normal. If I transform the normal I will obtain a vector that does not maintain the relation with its vertex.

Example: consider P and N in the 3D space, where dot(P,N) = 0. Their homogeneous representation P' and N' will have dot(P',N') = 1 because of the W component.

Now if I transform P' using the model matrix M I will obtain P'' = M\*P' which has the W component equals to 1, so going back to the 3D space can be easily done by taking the first 3 coordinates.

If I transform N' I will obtain N'' = M^-T * N' which does not have W = 1. I don't know how to take N back to the 3D space, keeping the dot product with P

Any suggestions?

---

I need to specify that when I refer to the homogeneous coordinates I'm not talking about the *perspective* transformation but the *affine transformation* (in opengl the modelview) that is still a 4D matrix composed by the linear transformation and the translation.

From the Nicol Bolas response I got that the 4th coordinate of a direction vector should be 0, that's because a direction vector does not participate in the translation. In this case the dot(P,N) = dot(P',N') = 0

---

**Integration to Nicol Bolas response:**

So basically the claim that *the normal must be multiplied by the inverse-transpose of the model matrix in order to preserve the dot product between P and N* was wrong (or incomplete). The article referenced is misleading.

If we consider *M* the model matrix that consists in a linear transformation *L* and a translation *t*

we have an inverse-transpose of

which multiplied by N' = \[N 0\]

This creates a bit of confusion because of the which is nor 0 or 1 and I couldn't figure out how to get a direction (*N'*) with the *w* component equals to 0.

The mistake is that we should not consider the translation *t* of the affine transformation for different reasons (too long to explain here).

So we should only consider the linear transformation *L* and make sure that dot(P',N') = dot(P,N)

Since L is in the 3D space, no homogeneous space is needed (or if it is used we need to set the *t* to 0). That's where the article was wrong

# Answer
> 11 votes
> consider P and N in the 3D space, where dot(P,N) = 0.

P is a position (I assume that's why you called it "P"). Taking the vector dot product of a position with a normal is generally meaningless.

A normal is a vector *direction*. A position is not a direction; it is a discrete location in a space. Now, you can *consider* a position to be a direction, but it certainly would not be a *unit* direction unless you normalize it.

At no time should you be performing a 4D dot product between a position and a direction; it is mathematically viable, but physically meaningless.

If you're thinking in terms of homogeneous 4D vectors, a direction is a 4D vector who's W is 0. You should only be taking the dot product of vector directions, and therefore, the W will always be zero. So they may as well be 3D vectors.

That's why the `gl_NormalMatrix` in old-school GLSL is a mat**3**, not a mat**4**. If you want to consider a position to be the direction from the origin of its space to a particular point, then you will generally just crop the W component off.

Really, unless you're actually thinking in terms of post-projective spaces (the space after you use a projection matrix), you shouldn't care about W or homogeneous coordinates. For positions, W is 1. For directions, there is no W, because they should be `vec3`'s. If you need to multiply them by a `mat4`, then their W is 0.

The article you linked to is way too math heavy, when the concept can be much more easily explained without plane equations and so forth. It's simply a matter of coordinate systems. Every position and directions has a coordinate system, a space. In order for the dot product between two directions to have a meaning, the two directions must be in the same space.

Therefore, if your light direction is in eye space, and your normal is in model space, then you need to either transform the light direction into model space, transform the normal into eye space, or transform both of them into some other space. Only then, once the two are in the same space (preferably a linear space), can you get a meaningful angle between the two vectors.

> while a normal must be multiplied by the inverse-transpose of the model matrix (M^-T) in order to preserve the dot product between P and N.

The inverse-transpose has nothing to do with preserving "the dot product between P and N". It has to do with scale transforms and how they interact with directions rather than positions.

---

For a rigorous mathematical discussion of the issue:

The 4D homogeneous representation of a 3D vector direction uses a W of 0. This is the root of your problem.

> Example: consider P and N in the 3D space, where dot(P,N) = 0. Their homogeneous representation P' and N' will have dot(P',N') = 1 because of the W component.

The homogenous representation of P, which is a vector position, has a W equal to 1. The homogenous representation of N, which is a vector direction, has a W equal to zero. 1 * 0 is still 0, and therefore the W term of neither P' nor N' will have any effect on the result of the dot product. There are no two 3D vectors P and N such that `dot(P, N) = 0` and that `dot(P', N') = 1`

So the example is simply impossible.

> If I transform N' I will obtain N'' = M^-T * N' which does not have W = 1.

N' has a W of 0. N'' will also have a W of 0, unless M is a very ill-behaved matrix. And if it is, then you've got problems.

> I don't know how to take N back to the 3D space, keeping the dot product with P

A homogenous coordinate system is a projective space. It is a space that represents a projection of one space onto another. In purely mathematical terms, the conversion from a homogenous coordinate system to a Cartesian coordinate system works by dividing the last coordinate into the rest. So, given a 4D homogenous position H, the Cartesian equivalent C is:

```
C.x = H.x / H.w
C.y = H.y / H.w
C.z = H.z / H.w

```

Now, because the W component of a position under non-projective transforms remains 1, you can just think of it as taking away the W. But in terms of rigorous 4D homogenous math, you're doing division.

If the homogenous representation of a vector direction always has W equal to 0, then how do you go back to Cartesian space? Speaking purely in terms of mathematics, you *don't.* A W of zero represents a "position" infinitely far from the plane of projection. Such a position cannot properly be represented in a Cartesian space.

Indeed, this "projection at infinity" is one of the reason why homogenous spaces are used. It's the only way to talk about such a concept and do math relating to it.

However, this inability to have homogenous vector directions is also why you generally do not put vector directions into homogenous coordinates. Oh, sometimes we put them in a `vec4` and stick a W = 0 in there, in order to multiply them with a 4x4 matrix. But that's the only reason we do it: to make the math work. It's not *really* a 4D homogenous direction; it's just a 3D vector that has a W of 0. The W being 0 is there to keep the translation component of the matrix from affecting the directionality of the vector.

It doesn't mean the same thing has having a 4D homogenous position.

Therefore by convention, you simply chop off the W when dealing with normals. Usually, graphics programmers just use a 3x3 matrix for normal transformations, unless they're not doing the inverse-transpose.

Note that you cannot really *project* vector directions, because projection is a non-linear transformation. Therefore, the transformation from homogenous to Cartesian space is non-linear. And directions can't really be non-linear. So again, there isn't really such a thing as converting a 3D direction into a homogenous direction and back again.

---
Tags: opengl, mathematics, normals
---


title: Windows-Linux cross platform game

text:
# Question
Title: Windows-Linux cross platform game
The answers to this cross-platform related question are useful, however I want my (C++) game to run on Windows and Linux (and be packaged for Ubuntu) only. I'm not interested in platforms like mobile or consoles.

Are there any specific tips or suggestions for this case?

Also, if I get the game to work on linux, is it difficult to add support for OSX?

**Updating with more information**:

It will be a 3D game simulating the motion of spacecraft in the solar system. We will use Ogre3D for the graphics. We're still in the design phase, so there's no code written yet.

# Answer
> 1 votes
One thing you might want to keep in mind from the start is that if your game relies on floating points physics calculations the behavior on one OS could be different than on the other without some careful considerations. This is not dramatic if your game doesn't rely on perfect synchronization across different platforms such as multiplayer RTS games and will only be apparent in some edge cases but it's still something I consider important to keep in mind ahead of time.

Other than that, using C++, cross-platform specifications (OpenGL if you ever need it, I don't know Ogre3D) and cross-platform librairies (and of course the STL where possible) should pretty much help you make your game platform-agnostic. Just make sure to abstract implementation details (Window management, threading, networking, etc.) during your conception and all you'll need is some solid testing on all platforms.

# Answer
> 2 votes
I currently work in the GIS industry, and so many of our software libraries (e.g. GDAL) are designed to be cross platform. **They cause nothing but headaches**

The best way to write applications intended for multiple platforms is to architect them such that platform dependencies are abstracted away completely. Write code that is easy to port, rather than cross-platform. You'll save yourself a lot of headaches and wasted time trying to figure out why you umpteen millionth`#ifdef WIN32` doesn't work properly.

---
Tags: c++, cross-platform
---


# Question
Title: How can a programmer learn to draw 2D assets?
Are there any good tutorials for someone who wants to create 2D graphical game assets? Drawing classes for absolute beginners, preferably teaching skills that can be as relevant as possible to games - drawing characters sideways/top-down, isometric, drawing textures and such.

# Answer
> 35 votes
First, you want to search for tutorials on the internet. Youtube is your friend. Seriously, it's probably the best way to learn drawing. It's easy to look at some really amazing drawing and say "oh, I could never do that, he's been doing that since he was a kid." But when someone slowly walks you through the steps and explains every part of the way, the mountain suddenly seems a lot easier to climb.

Next the problem is figuring out what to search for. You don't want to start off with the hard stuff, so don't go searching for "digital art" or "character design" as you will be lost very fast. There's a lot of tutorials out there that start off like "first draw a basic human figure" or "start by sketching out some buildings". Avoid those.

Now, a tutorial to get you started. First, search YouTube for "perspective drawing". It's a basic skill that's the first thing they teach you in any art class. Play around with this a bit, drawing 3D houses, etc. Now, try to find something in your house that's roughly box-shaped. Your speakers or desktop should work fine. Now draw it using perspective. What you just did is called "life drawing" which is basically where you draw something from real life. It's really important that you do this, because you figure out neat little things on your own when you draw real things.
Eventually, you'll get to the point where you can look at something and start thinking "how would I draw this?" That's important, because then when you need to draw, say, a potion for a game, you can look at a glass bottle and think about how to draw it, then apply that to your potion. Think of it like writing a "method" for drawing a bottle. You'd probably start out with a method called "DrawLine", use it for "DrawCylinder", then make "ShadeGlass" and combine "ShadeGlass" with "DrawCylinder" to get "DrawBottle".

Also, when you watch a tutorial you'll see that a lot of what you drew looks a lot messier or uglier than what you saw in the tutorial. Do not be worried, it's not that you're less creative or that you didn't follow the tutorial, you just haven't built up some of the basic skills that the artists in the tutorials have. An easy way to help this is to just draw lots of basic shapes over and over again. Keep a pad of paper next to you while watching tv, and during the commercial break see if you can draw 20 circles, lines, or squares. Think of it like learning the basic methods in a new language so that you don't have to look through pages of the documentation.

Another thing to watch out for is details. Say you're drawing a person. You decide to start with the head. So you start with drawing a circle. Then you think "oh, I've already got the circle, I'll give it eyes and a mouth!" Next thing you know, you've got a pretty good head, with hair, a nose, eyes, a mouth, ears, etc. So you start drawing the body. After doing some pretty good shoes and maybe a cool shoulder armor you realize that your drawing looks horrible. The head is too big, the legs are different sizes, and the feet look backwards. My point is that you have to focus on big shapes and try to resist the urge to start adding details.

Finally, learn to critique your own drawings. Don't just look at the person you drew and say "that's ugly". Pick out specific things to improve upon. Say "those hands could be better" or "the proportions seem kinda weird" or "The hair looks too fuzzy". Then look up tutorials for whatever you need to improve on. There's a lot of good resources out there, but you have to know what you are looking for. You wouldn't just search for "Making my program faster", you would look up "improving performance rendering triangle strips in XNA".

Anyways, assuming you already did perspective drawing, here's some things to search for to get stated. (inserting "tutorial" after all of these can give better results)

* 3D shading
* Figure drawing
* Gesture drawing
* Basic Pixel Art

Just with that stuff you should have a good month or two of stuff to practice. Try to keep sketchbooks, so that you can look back and see how much you've improved. If you want to look forward and see how good you can get, look up "speed painting" on YouTube. And if you are getting frustrated with all sorts of technical details and stuff, watch this video and try to have some fun.

Good luck, and make sure you draw often!

# Answer
> 8 votes
As a fellow programmer who has just recently begun to get a handle on hand-drawn art, I'll give you my 2 cents:

Note: I'm going to assume you mostly want to create characters and sets. IF not, ignore this answer :P

---

## Preface

So, first off, you'll want to know some basic anatomy. Know the proportion of each major part of the body (torso, neck, head, hands, upper and lower of limbs, etc). You'll want to know how each joint connects and it's axis and angles of rotation. And you'll want a basic idea of how the muscle groups work both relaxed and in flexion.

Secondly, you need to know to compare your work with one of a similar stage of production. By that I mean, if you're drawing in pencil, compare it to pencil sketches, not to an inked and coloured image (in order of production: Pencil -\> Ink -\> Colour -\> Composition).

Finally, the tools maketh the man. That's not to say that you can't be an artist without spending big money on pencils and brushes, but just understand that you'll struggle to get a decent drawing using just a pacer. Learning when to us different weights of pencil/brush are as important as knowing how to draw the lines.

The process of learning a particular form of art can be greatly accelerated by following a 3 stage process: Copy, Modify, Create

---

## Copy

Find an artist whose style you like, and just try tracing their artwork. What you should be aiming to do here is to get a feel for differences in aspects of the drawing such as smooth versus angular angle/curves, heavy/light lines, proportion, etc.
Once you've traced enough that your works are similar, try drawing it by reference. Place the original next to a blank sheet, and draw. Look at the original as much as you want, lay it over your copy to compare, but always draw free.

---

## Modify

Now, take one of their drawings, and modify it in some way. What you're doing here is trying to imitate their art style, using an existing piece as a template. As always, start with a small change (maybe change the pose of a hand, or the tilt of their head), then work up to a bigger change (change the pose of an entire leg, or arm), then finally a complete body pose.
By the time you're ready to move on, you should be able to look at a character they've drawn in a given pose, and draw it in a completely different pose.

---

## Create

So, by this stage, you can take an existing artwork, and draw it in a new pose. Now, start from scratch. Take an existing character, and with no exact reference, draw them from scratch.
Then, make a new character in the same style. Once you're happy with the result, guess what? You're an artist! =P

# Answer
> 4 votes
I would take the important facts from people who say it's too late, but also ignore them. When I started making games I wasn't very good at drawing, but still managed to learn what I needed. I'm never going to make the final graphics for any of my games in reality, but I learned enough to prototype my idea to the designers that I work with. This way you can still keep your "tone" and have someone who knows what their doing do the heavy lifting. I'de say my artist partner and music partners are the reason I got past the old days of having a cool game idea in very basic playable form. Actually the first game I ever finished was the first project I had the partners on.

That said, knowing how to prototype your art to keep your vision is very important if you have your own ideas.

My list:

* drawing - I bought a tablet pc. (ipad will work but that wasn't out then!) I was terrible at drawing so I traced a ton of concept art for games that I love. A few months later I could get my idea across without doing a stick figure which kills the vision.
* textures - lots and lots of texture packs. these things are great, why reinvent the wheel? If you find that you can't get what you want from that, start playing around with photoshop and all of the filters. A link http://vandelaydesign.com/blog/design/photoshop-textures/
* 2d sprites - again there are tons of these out here. For your own stuff, use a sprite editor. I don't have a preference as I do mostly 3d, but this one is on my computer. Seems good and fairly straight forward from the few times I've used it.
* storyboarding - I do this the most. I got anime studio 7 which is incredible. Basically the 3d bones concept but for 2d. Puts flash to shame for this purpose.

I'de say 3dbuzz and lynda are the most helpful resources for me as far as art in general goes. I spent about 200 hours on these sites and can get my ideas across to designers very well now. I still will never publish my art, real designers can do this stuff effortlessly.

# Answer
> 1 votes
Really short answer, given that I just wrote a longer one over here: The Natural Way to Draw, by Kimon Nicolaïdes, is a great book that also contains a study plan. Another good book is Harold Speed's "The practice & science of drawing".

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


title: Visual Design for AI

text:
# Question
Title: Visual Design for AI
i'm developing an editor for a game...

and tonight i have been thinking about implement a visual ai designer...

this is how i think it should be:

1. What kind of visual components are used in theses tools? (Timers, Counters, Conditionals,...)
2. About implementation, i'm using C# and xna, how can i save/load this graphs?

# Answer
> 2 votes
The Bitsquid Blog has a couple of interesting articles regarding their implementation of 'Visual Scripting':

http://bitsquid.blogspot.com/2011/05/flow-data-oriented-implementation-of.html http://bitsquid.blogspot.com/2010/09/visual-scripting-data-oriented-way.html

The second article relates closely to the second part of your question, where the blogger describes thoughts about saving/loading and implementation of the graphs produced by the scripting interface.

# Answer
> 2 votes
Visual Programming is a large subject. Even if you very tightly target just AI, you will probably need to handle generic logic anyway, which is where most of the work is.

And even then you'll probably always find your system just a little bit too limiting, so you either need to constantly expand it or end up with huge sprawling visual messes.

Kismet, in the Unreal engine, is one example of a visual programming language used for gameplay logic. Since Unreal SDK is free you should probably get to know it a bit before you start on your own work.

---
Tags: xna, game-design, ai, level-design, editors
---


# Question
Title: how can I move an actor in opposit direction of mouse's position in GameSalad?
I have a moving actor named ball and I want to move it in the opposite direction of my mouse's position.

In my code in Move To behaviour for X-axis location I write

> -game.mouse.position.X

and for Y-axis location I write

> -game.mouse.position.Y

But it's not working properly.

# Answer
the formula would be more or less like this (I don't know how GameSalad works):

```
finaldirection.X = - (game.mouse.position.X - ball.position.X);
finaldirection.Y = - (game.mouse.position.Y - ball.position.Y);

```

because if you substract a vector (v1=ball position) from other vector (v2=mouse position) you get a third vector in the direction from v1 to v2 (i think) then you multiply the vector by -1 because you want to go the opposite direction (which you were doing already)

You may want to make this a unit vector for then be able to multiply by the distance you want to move the ball (or the velocity/force to apply to it), you then divide it by its magnitude like this:

```
// find the magnitude of this vector
length = sqrt( (finaldir.x*finaldir.x) + (finaldir.y*finaldir.y) );
if( length != 0 )
{ // divide the vector by its length
   finaldir.x /= length;
   finaldir.y /= length;
}
else
{
   finaldir.x = 0;
   finaldir.y = 0
}

```

then you will have a final vector of length 1 so if you want to move it for example 15 units far in that direction you can do:

```
   ball.position.X += finaldir.x*15;
   ball.position.Y += finaldir.y*15;

```
> 1 votes

# Answer
The answer to this question is exactly the same as my answer to your other question, except you multiply the resulting per frame vector by -1.
> 1 votes

---
Tags: input, movement, gamesalad
---


# Question
Title: Finding which side one point is from another point
I have a simple question I think, if point a is to the right of another point I a dirx to be 1, otherwise -1. Likewise for a diry var, if it's above the other point I want it to be -1 otherwise 1. This is what I've worked out so far:

```
dirx = (abs(disx+1)/(disx+1))*-1;
diry = (abs(disy+1)/(disy+1))*-1;

```

The disx and disy are the distance from each other on x and y. I have a +1 to keep from having a division by 0 error, lastly I'm \*-1 it all so that it'll match the coordinate system of the game screen where something higher has a lesser value than something lower.

My problem is that I'm still getting a division by 0 error with this code, I'm not sure why as I even added +1 to make sure it wasn't possible???

# Answer
if disX = -1, then you'll always get a divide by zero error using that code.

If you're programming in a c-based language, just use the ? operator, a la:

```
if(disX == 0)
{
  dirX = 0;
}
else
{
  dirx = (disX > 0) ? 1 : -1;
}

```
> 2 votes

# Answer
If I understood your question correctly you just wanted to normalize a vector.

let me break your question into 3 parts :

1. why do you get division by zero?
it's simply because either `disx` or `disy` values could be exactly (-1). in that situation you computer will start computing `(abs(-1+1)/(-1+1))*-1` which is basically `(0/0)*-1`!
2. how to find sign of a number (or how to normalize 1D vector)?
let's say you have a number 'X' and you want to check if this number is negative or positive. usually there is a function in math libraries named `sign` or `sgn`. They implement that function like this:

```
int sign(int x)
{
    if (x > 0)
        return 1;
        else
        if (x < 0)
            return -1;
        else
            return 0;
}

```

note that there is one extra condition where X is exactly zero, in that case sign function **should** return 0 since x doesn't have any sign!
3. how to normalize a 2D Vector (or a vector in higher dimensions)?
the basic idea is to create a vector which has a length of exactly 1 so the first step is to calculate length of current vector.

```
length = sqrt(vec.x^2 + vec.y^2 + vec.z^2 + ...)

```

the next step is to shorten (or stretch) your vector so that it's total length equals to exactly 1. and here is how it's done:

```
vec.x = vec.x / length;
vec.y = vec.y / length;
vec.z = vec.z / length;
.
.
.

```

again note that length is always some positive value but it can be equal to zero (where all elements in your vector are exactly zero). you have to check if a vector's length is zero you can't compute a normalized vector!
> 0 votes

# Answer
What you need is the Cross Product of the two points and check if it is bigger or smaller than zero (zero means it is on the same line):

Point a Point b

cp = a.x\*b.y - a.y\*b.x;

For example:

a= (2,5); b= (3,4) cp = 2\*4 - 5\*3 = 8 - 15 = -7

as cp \< 0 the point a is on the left of point b

Your function can thus just do this to return -1 or 1:

```
cp = a.x*b.y - a.y*b.x;
if(cp<0)
   return -1;
else
   return 1;

```
> 0 votes

---
Tags: mathematics, coordinates, linear-algebra
---


title: Sphere collision response

text:
# Question
Title: Sphere collision response
I have simple mechanism for testing of two balls colliding:

```
private static boolean isColliding(float firstBallX, float firstBallY, double firstBallRadius, float secondBallX, float secondBallY, double secondBallRadius) {
       final double a = firstBallRadius + secondBallRadius;
       final double dx = firstBallX - secondBallX;
       final double dy = firstBallY - secondBallY;
       return a * a > (dx * dx + dy * dy);
   }

```

And it works great. One of the balls is moving and the other (second one) is static. I have two questions.

When a collision occurs, how do I change the movement of the first ball (the moving) one to its logical path? I suppose I should change the direction somehow, but cannot figure out how...?

The other question is how do I tell the static ball, after the collision move? And what is its path, direction and staff...?

Thanks in advance.

# Answer
Its called elastic collision.

Here are some similar questions:
> 12 votes

---
Tags: java, collision-detection, graphics
---


# Question
Title: How can I find a point on a line when I have only two other points?
I have a straight line passing from points A(2,-1) and B(4,5). I want to find a point C that is on the line and outside A-B.

# Answer
> 5 votes
$$ \begin{align} P &= t (B-A) + A \\ P\_x &= t (B\_x - A\_x) + A\_x \\ P\_y &= t (B\_y - A\_y) + A\_y \\ \end{align} $$ $$ \frac {P\_x - A\_x} {B\_x - A\_x} = \frac {P\_y - A\_y} {B\_y - A\_y} $$ $$ \begin{align} P\_y &= (P\_x - A\_x) \times \frac {B\_y - A\_y} {B\_x - A\_x} + A\_y \\ &= (P\_x - 2) \times \frac {5 - -1} {4 - 2} + -1 \\ &= (P\_x - 2) \times \frac 6 2 - 1 \\ &= (P\_x - 2) \times 3 - 1 \\ &= 3 \times P\_x - 6 - 1 \\ &= 3 \times P\_x - 7 \end{align} $$

\\$A\\$ and \\$B\\$ are points. In this case \\$A\\$ = (2, -1), \\$B\\$ = (4,5) \\$P\\$ is the point you are looking for.

\\$A\_x\\$ is the coordinate \\$x\\$ of point \\$A\\$. In this case \\$A\_x = 2\\$.

# Answer
> 0 votes
If I understand you right, you have point A on coordinates (2,-1) and B on (4,5). You want to find point C, if you know for example x coordinate?

You can compute direction vector from A to B, which is: B - A = (2, 6), then normalize it, so you get: (1/sqrt(10), 3/sqrt(10)). If you have for example that x coordinate of point C (lets say its for example 8), you divide this by x coordinate of direction vector and multiplz by y coordinate of direction vector. You get: 8 / 1 * 3 = 24. So point C has coordinates (10, 24).

# Answer
> 0 votes
To find points that lay on a line that passes through two known points you use linear interpolation.

---
Tags: mathematics, linear-algebra
---


title: Secondary monitor freezes game window

text:
# Question
Title: Secondary monitor freezes game window
I was bored and dragging my game window around the screen and noticed something interesting.

When I drag my game window over to my secondary monitor, the screen updating just completely freezes.

Is there something I need to do to enable updating on a screen other than the primary monitor?

# Answer
> 2 votes
This is a ERR in Pygame i'm sorry to say. Had this major problem when developing a toolkit for a company back in the days.

Edit: if the first "bug-ugly-fix" doesn't work, try my second suggestion!

The fix was sort of easy tho (if it works for you, this is NOT logical because it doesn't have anything to do with the actual problem BUT it worked for me, for some reason and), all you have to do is (before you call the render function):

```
# At the very top of your code, import:
from pyglet.gl import *

# then put this after clear() and before you draw anything:
glEnable(GL_BLEND)
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glEnable(GL_LINE_SMOOTH)
glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE)

```

If i'm not mistaken this should work just fine, if that doesn't work then you can always force the application to start up on the second monitor if you know that it will always be located on it, that way you "start" the renderer on the second monitor and thus making that the primary monitor for the application, to do that, simply do:

```
class gfx(pyglet.window.Window):
    def __init__(self):
        super(gfx, self).__init__(sizeX, sizeY)
        self.platform = pyglet.window.get_platform()
        self.Disp = self.platform.get_default_display()
        self.Screen = self.Disp.get_screens()[screen_nr]

    ...

```

That should do the trick for you :)

# Answer
> -1 votes
Assuming you are using two separate graphics cards for the monitors in question, you have bound to the primary graphics card on the main monitor, and then drag it to the monitor the second card is rendering with. on -most- systems you will just take a huge performance hit as it still renders on the primary graphic card but then copies the data to the other one for display. In your case however it would seem its not capable of doing that.

All I know however is the hardware flow behind it, not the python and pygame software on top of it all.. But I would assume this hardware issue is why you are seeing your issues.

---
Tags: python, pygame, screen
---


title: Enemy mathematical behavior

text:
# Question
Title: Enemy mathematical behavior
I'm really trying to up my game in game mathematics and now I'm working on enemy movement and a bit of AI. I have an enemy with two modes attack and avoid, based on an integer avoid variable that's either 1 or 0.

On avoid I want it to hover by the player, moving back and forth at a distance until it is set to avoid.

On attack I want to go close at a steady pace say an x and y velocity of 12, then once it reaches a certain distance to gain speed.

I have disx and disy variables that have the distance from each other for each coordinate. I also have a totDis variable with the normal a^2 + b^2 = c^2 formula. I'm pretty sure I'll need another variable that I'll have to change depending on the distance that effects the speed.

It kinda feels like I have all the pieces to the puzzle, I just don't know how to put them together though lol.

I'd like to be able to do this as mathematically as possible and I don't want anyone to give the the answer or do it for me. I was hoping if anyone could give me pointers or tips or just ideas on the directions I can go myself because I really want to have an understanding of this. I hope this is specific enough, if not I'll try to edit my question for you.

# Answer
You're looking at programming Steering Behaviors \- (see this also). Matt Buckland's book is good for this, but in my opinion the code he provides is a bit sticky and overdoes it with the C++ templates (source is on the website).
> 2 votes

# Answer
i think a good approach is Behaviour Trees

http://www.sgtconker.com/2009/10/behavior-tree-overview-placeholder/

http://magicscrollsofcode.blogspot.com/2010/12/behavior-trees-by-example-ai-in-android.html

http://cmpmedia.vo.llnwd.net/o1/vault/gdc10/slides/ChampandardDaweHernandezCerpa\_BehaviorTrees.pdf

This way you can focus in each behaviour and you can add new behaviours easily.

You need nothing too complicated, so you only have to implement what you need.

In your case, you will need to define this or more behaviours: Avoiding, GoingToAvoid, AttackWithCare, AttackingCrazy...

* Avoiding can have a time counter to determine how much time is avoiding.
* GoingToAvoid can be similar, but moving enemy as you need.
* AttackWithCare, moves the enemy towards the player at desired speed, when distance is short enough change the behaviour to AttackingCrazy
* AttackingCrazy, moves the enemy at increased speed
> 0 votes

---
Tags: algorithm, ai, movement, linear-algebra
---


title: Crafting recipes: storage and quering

text:
# Question
Title: Crafting recipes: storage and quering
Consider the following situation. In a game you can perform crafting: i.e. create new items from existing ones (like in Minecraft). I have following game entities (simplified):

* *item*: Atomic part.
* *recipe*: A list of *items* resulting in other list of *items*.

What would be best structure to store all the recipes in the game? I consider using SQLite database for storing it. However game is not a general type application, so, would it be better to use XML + in-memory structures for storing it?

A database has some major advantages to me, it's much more "DRYer" in my opinion. You also can query it. But I doubt if direct database performance is sufficient for smooth gameplay. On the other hand you can use say, XML to store all of the recipes and use in-memory storage and query it with LINQ. If finally it all results in in-memory structures then database seems to have much overhead, since it's used just as a storage. Or is it still better to use DB?

**Solution:**

For now I've decided to stick with XML as storage for recipes. The major advantage of XML for me is that the final solution is more portable to other platforms since XML is more widely available.

# Answer
> 3 votes
I would suggest, if you're looking to have a database structure, then you could employ the following:

2 Tables, Items and Recipes

Items has the following columns: ItemID (int), ItemName(varchar) and optionally IsComplex (bool) \[that last column is purely for efficiency later on, not used in this example, but I'm sure you could see how it could save time later on\].

For Recipes, use the following column: ResultantItemID (int), IngredientID (int), amountNeeded (int)

In Recipes, ResultantItemID and IngredientID form a composite key.

So, say for example you had a recipe for apple pie that required 5 apples, a pie base and an oven.

**Items Table**
*ItemID, ItemName, IsComplex*
1, "Apple", No
2, "Pie Base", No
3, "Apple Pie", Yes
4, "Oven", Yes

**Recipe Table**
\*ResultantItemID, IngredientID, amountNeeded
3, 1, 5
3, 2, 1
3, 4, 1

If you wanted to know the ingredient needed for an apple pie, just query the recipe table `where ResultantItemID = 3 (Apple Pie's ID)`

You might also want to add an "Is Consumed" column to the recipe table to indicate whether the ingredient is used up (apples, pie base) or not (oven).

# Answer
> 5 votes
Don't use database, unless you need millions of recipes. Maybe not even then.

You don't need to run complex queries against it. You don't need to store gigabytes of recipe data. Most probably, all your recipes will fit in memory 10 times over and still leave enough for all your needs.

Unless you have insanely high number of recipes, or you work on a platform with ridiculously low memory, you'd be better off reading recipes from in-memory storage.

And for long-term storage, I suggest XML - it's very easy to work with in C# and you'll appreciate its extensibility when you need to add that one special recipe that just happens to require something beyond simple ingredients.

---
Tags: c#, xna, databases, xml
---


title: Events, Posting vs Queuing

text:
# Question
Title: Events, Posting vs Queuing
I'm implementing a messaging system and I'm wondering about how I should handle events. Should I post them and send them to the appropriate listeners as soon as I receive them, or should I queue them and only dispatch when I am prompted to (most likely by the main game loop)?

---

**Edit:** *More info*

My game is a 2D platformer, so performance isn't going to be very hard to achieve. Considering what Roy T. said, I guess I might as well send out the event as soon as it is posted; there doesn't seem to be a need to queue it (unless I'm missing something, of course).

# Answer
We really need more info, but if you're writing a really fancy system a dispatcher would be nice since then you can prioritize events (network events could have a higher priority than chat events for example).

However a real dispatcher is probably going to be overkill and might even make stuff slower because of the sorting on priority and if you don't think it over carefully enough you might starve low-priority events.

Anyway, with more info we can make a better guess what would be better.

Edit:

As a response to you adding information: no it doesn't seem like you need a proper dispatcher :)
> 3 votes

# Answer
You might want to have both available, and use the correct one for the current listener. For instance, your entity system might want to know immediately to remove an enemy, so it doesn't get updated and moved, but your inventory system might be able to wait as the player won't be able to use the item until the next frame anyway.

So on binding to the event, the listener should specify when it wants to be updated:

* immediately
* at the end of the frame
* at the start of the next frame
* just before the listener's next update
* etc
> 5 votes

# Answer
C# event listeners are invoked in subscription order, immediately when the event occurs. I would do the same. I am using these in my 2D game, and it is working out great so far.
> 2 votes

---
Tags: architecture, events
---


# Question
Title: Is there a rule of thumb to scale up the environment by 33%?
I was reading an article on Gamasutra called A Rational Approach to Racing Game Track Design, and I found the following:

> A commonly acknowledged rule for third person games is that the environment should be scaled up by a factor of around 33 percent (on page 2)

I am just curious: has anyone else heard of such a rule, and if so, where else could I find references to it?

# Answer
> 10 votes
In cinema, photography and game design, it's fairly common-held knowledge that certain type of perspective and movement can cause objects to seem out of scale with each other, or simply to receive less attention from the viewer.

The solution to such a problem is to play with scale empirically until things "look right". I've not heard of an exact formula or precise set of numbers for it.

So to answer your questions, playing with scale to make set compositions look better or to alter the audience's visual attention is a well known trick. The 33% stipulation is just something this guy picked up which works for a particular scenario.

I agree with Patrick Hughes though, if you're not sure if it will work with you, try it yourself. Just don't be afraid to try values other than 33%

# Answer
> 7 votes
Build a mock up and run through your environment just to see what it feels like. Build several tests, try them all. You can't blindly use rules from someone else when it comes to making YOUR game feel good, there is only testing with players and iteration. You could use someone else's rule of thumb to build one of your tests, of course.

Maybe later, based on tests for your game, this percentage will become one of your ruies.

Don't jump the gun with rules of thumb! (and don't mix metaphors, ahem)

# Answer
> 4 votes
http://www.gametrailers.com/video/expanding-horizons-dark-sector/29795

I remerber hearing about this before. Check minute 1:50 (Things next to you need to be 1:1 scale and as things become further away the need to be scaled up).The guy also mentions that the developers of max payne also talked about this issue maybe you could look that up. Of course they are talking about third person shooters I don't know if this correspond your issue.

---
Tags: game-design, level-design, racing
---


title: What are "frame rate" and "fps?"

text:
# Question
Title: What are "frame rate" and "fps?"
Can someone give me a detailed explanation about frame rate and fps concepts?

# Answer
"Frame rate" and "FPS" (frames per second) are usually the same thing. A "frame" is usually a single image in the series of images presented to your screen rapidly so as to give the illusion of motion in your game, and so the terms generally refer to how many of those images your game can simulate and produce within one second.

FPS is often used as a crude measurement of performance, but it's important to remember that it's a non-linear measurement: the difference between 30 and 60 FPS is much larger than 60 and 90 FPS.

Occasionally you will see the term applied in a context where "frame" doesn't refer directly to a unit of graphics/simulation processing overall, but to something narrower in scope. The idea is the same, though: how many of these steps does the program produce within one second.
> 38 votes

# Answer
FPS = frames per second. A frame is basically your screen with something drawn on it. 60FPS means that something draws on your screen 60 times in one second. Because our eyes (or should I say the image processing cortex in the brain) is limited, if you draw something on very fast and move it each time - it will seem like it moves to our brain. That's how cartoons are done.
> 0 votes

# Answer
A "frame" is once around the game loop:

```
while( game_running ):
    update()
    draw()

```

**update()** involves things like

* Reading user input
* Computing enemy next moves

**draw()** is just drawing the current state of the game, as computed by **update()**.

So here a "frame" is BOTH an update/draw cycle. FPS (frames per second) is a rough measure of how many times you can do your basic game loop per second, so by that its a *rough measure of game performance*.

Any number of things can be the bottle neck in your **frame rate**. It could be the CPU intensive AI code. It could be your collision detection routines before you added a reasonable space partitioning scheme. It could be the GPU itself.

If it contains an accurate physics solver, your physics solver will need to perform more than one iteration step per "frame" displayed (CarSim for example requires something like 1000 iterations every 1/60 second, simply to retain stability in the solution).
> 0 votes

---
Tags: game-loop, frame-rate
---


title: Vector field based game engine

text:
# Question
Title: Vector field based game engine
Does an engine using a vector field exist?

What I mean is that instead of calculating intersections, for example one could calculate the vector field generated by gravity and for the ground and let the object follow those fields.

What are the advantages and drawbacks of this kind of game engine?

# Answer
> 2 votes
The more vectors you have, the more you have to store, and the more floating-point operations you (potentially) have to do. I have no doubt that this method would require a vast number of vectors. Why instance vectors that may never be used? It wouldn't make sense from am efficient space/time usage perspective.

Intersection checks cannot possibly be replaced by your proposed field physics. In classical mechanics, at a human scale, objects will not noticeably affect each other by gravitic forces in any case. The only time they are going to "push away from one another" is when they are intersecting in your simulation, then and only then. Thus there is no way a field-based approach could eliminate the need to perform intersection checks (in whatever form).

The discrepancy between what you are imagining and the reality of computer simulations, is as follows:

A simulation runs through some finite number of steps per time interval (whether these steps are variable or equal duration is irrelevant). Based on this, objects must "jump" a certain distance in each time step -- this process is not analog -- based on their velocity, no matter how small. So logically there are always going to be cases where an object may potentially "jump into" and intersect another, hence the need for intersection checks.

The real world, on the other hand, doesn't work in the same way that computer simulations do, because real-world time is (in practice) analog. So the machine that is the universe, so to speak, resolves collisions in a different manner, using something like the approach you propose. Atoms never really collide, they just apply forces that grow stronger and stronger the closer you force them together. That means that objects, which are made of atoms, obey similar rules: forces are applied on a continual, analog basis between every object in existence -- so the physicists tell us.

P.S. Subject to the eminent Martin Sojka's proofreading for errors of a physical or mathematical nature. ;)

---
Tags: vector
---


title: 2D top down movement

text:
# Question
Title: 2D top down movement
I'm trying to make my first real time game.

I'm having problems with the movements using the mouse though. If close to theX axis, the player is moving fine, but if close to the Y axis(going southwards) he moves fast even though I'm taking into consideration the x coordinates.

Edit: I rewritten the code following your advice and the answer below. I hope it's better written now.

```
 if(input.isMousePressed(Input.MOUSE_LEFT_BUTTON))
    {
            mousex = input.getAbsoluteMouseX();
            mousey = input.getAbsoluteMouseY();

            if(mousex<= gc.getWidth()/2f)
                mousex = x - (gc.getWidth()/2f - mousex);
            else
                mousex = x + (mousex - gc.getWidth()/2f);

            if(mousey<= gc.getHeight()/2f)
                mousey = y - (gc.getHeight()/2f - mousey);      // calculate the x and y needed to move to
            else
                mousey = y + (mousey - gc.getHeight()/2f);      // mousex and mousey in relation to the map and not screen position
                                                                            // because screen scrolls
            System.out.println("mousex: "+mousex+"mousey: "+ mousey);
            int delta_x=(int) (mousex-x);
            int delta_y=(int) (mousey-y);
            double rotangle = Math.atan2(delta_y,delta_x);
            double rot = Math.toDegrees(rotangle);
            if(rot==0)
                rot=0.1;
            texture.setRotation((float) rot+90);
    }

    if( (Math.abs(x-mousex)>1))
    {
        this.moveForward(0.2f, texture.getRotation(), delta, null);
    }
    else
        if( (Math.abs(y-mousey)>1))
        {
            this.moveForward(0.2f, texture.getRotation(), delta, null);
        }
        else
            this.setX(mousex);

    }

```

# Answer
> 3 votes
For this answer, I'm going to assume that you want the player avatar to move towards the mouse cursor at a fixed top speed. That's the best I could gleam from your explanation/code, if it is incorrect, please inform me as such and I'll rework the answer:

Note: `topSpeed` is a constant defined elsewhere.

```
int currentX = this.getX();
int currentY = this.getY();
int deltaX = mouseX-currentX;
int deltaY = mouseY-currentY;
float angle = atan2(deltaY, deltaX);
float magnitude = sqrt(deltaX*deltaX + deltaY*deltaY);
magnitude = Min(magnitude, topSpeed);
this.setX(currentX+cos(angle)*magnitude;
this.setY(currentY+sin(angle)*magnitude;

```

---
Tags: java, movement
---


title: Random enemy placement on a 2d grid

text:
# Question
Title: Random enemy placement on a 2d grid
I want to place my items and enemies randomly (or as randomly as possible). At the moment I use XNA's `Random` class to generate a number between 800 for X and 600 for Y. It feels like enemies spawn more towards the top of the map than in the middle or bottom. I do not seed the generator, maybe that is something to consider.

Are there other techniques described that can improve random enemy placement on a 2d grid?

# Answer
Random placement doesn't look random enough to the eye. You'll probably want the enemies spaced out a bit more evenly. Take a look at this article about Poisson disk sampling, or read about blue noise.
> 16 votes

# Answer
Shawn Hargreaves to the rescue!

http://blogs.msdn.com/b/shawnhar/archive/2009/12/17/the-psychology-of-randomness.aspx http://blogs.msdn.com/b/shawnhar/archive/2010/09/10/links-5-charles-bloom-on-randomness.aspx

When you think random ditribution, you really mean even distribution. .Net's Random is thinking random. You need something else to even it out. The Poisson disk sampling method amitp linked to looks perfect for your needs.
> 7 votes

# Answer
The following C# code will generate a set of uniform points for you:

```
Random rand = new Random(); // creates a new random number generator with a time-based seed
int X, Y;
for(int i = 0; i < numberOfPoints; i++)
{
  X = rand.Next(800); // generates a random int between 0 and 799, inclusive
  Y = rand.Next(600); // generates a random int between 0 and 599, inclusive
  AddPointToSet(X,Y); // write this method however you want
}

```

Note that when you use the Random() constructor with no parameters, the Random object you create is seeded based on the time, so it's going to be essentially random unless you're doing it repeatedly with very little time in between calls.
> 0 votes

---
Tags: xna, 2d, sprites, random
---


# Question
Title: Is it possible (from the vertex shader) to always draw at specific pixels?
I am wondering if I can (if possible) make a vertex shader that will always make the pixel shader draw everything in 1 pixel, at position 0,0.

I know this sounds crazy, but it's needed in the situation I'm in right now.

Let's say that I am drawing a line with 2 vertices that each have the color blue. For every vertex, I tried attaching a TEXCOORD that specifies what pixel I want this vertex to be drawn in. However, I can't get this to work.

The reason I am doing this is that I am making experiments where the physics of my game (which is very intensive) is drawn onto a texture, and handled by the GPU.

# Answer
> 1 votes
You may want to take a trip over to http://gpgpu.org/ where they specialize in just what you're doing, offloading a bunch of computation onto graphics processors. And also here http://www.khronos.org/opencl/ where the rubber meets the road.

I realized that that wasn't much of a direct answer except to say that there are nicer API than raw texture map writes. What you're trying to do is entirely possible and in fact there is a whole array of twisty, turny, squeezy, stretchy model manipulations that rely on modified vertex processing. If you render to a quad with an identity projection the correspondence between UV and calculated output pixel remains constant, also set point sampling and other appropriate flags that would modify or post process the output to the texture.

---
Tags: xna, c#, physics, xna-4.0
---


# Question
Title: Does this constitute as copyright infringement?
Say there is a card game, and it has cards that arc out, and has certain types of memberships with certain features such as premium members being allowed to chat, or use private game rooms etc. If I, from scratch created a card game (for example, Hearts) that had similar arced cards, and had similar basic and premium memberships, but used all my own, graphics, sound, and theme, would this constitute as copyright infringement? Where is the line drawn for this sort of thing?

Thanks

# Answer
From what I've been reading I think that the things from the game protected by copyright are everything related to the art of the game, such as the music, graphics, the name, the text that constitutes the story within the game, etc.

There is also this approach to program code that it allows to be copyrighted as it is (ie. it protects from copying it as with copy and paste) but the way it works, whatever it does can't be copyrighted.

For protecting "ways of doing things" such as an algorithm or data formats, I believe patents can be used, but they are very different from copyright, you have to pay to maintain the patent and there are many restrictions about what you can or can't ask for patenting.

I'm not a lawyer and laws are not the same even international treaties are handled different from place to place, so if you are really concerned you should ask a lawyer. I think you won't have any problem unless you are actually copying original things which are noticeable for someone who doesn't know about game development, because afaik game mechanics can't be copyrighted.
> 2 votes

---
Tags: game-design, game-mechanics, legal
---


# Question
Title: 3ds max "thread stiching" plugin for cloths or furniture
i\`m trying to find a plugin or way to add 3D thread stiching to a mesh.

It would be perfect if you could creat thread stiches along edges in "editpoly" mode. I know that you can somehow do this in Z-Brush with customized alpha brushes but in my opinion its a bit complicated. I could also imagine alining a editable spline along a mesh edge. Important for me would be that this "unknown tool" would also add the displacement on the canvas and the stiches so i can use "render to texture" to give seems realistic look. Thisway you could always creat perfect stiches with realistic looking displacement like in the picture below without to much affort.

http://www.esunroof.com/contrast\_stitch.jpg

http://t1.gstatic.com/images?q=tbn:ANd9GcQplgCvhur-ynthz15Qdaqpv1QRwkG4K6sjhVjDqzzxm6OaY9Bt

would be awesome if you know a way to do this, Thanks a lot lot :)

# Answer
If this is for use in a game, there is no way you'd add that as mesh geometry.

This is almost an example case for the use of bump/normal/displacement maps.

These would allow you to keep the geometry of a model simple, but the texture maps you apply to it would add the seams and stitches.

In that case, photoshop (or GIMP if you're cheap) is your friend, along with NVidia Texture Tools which allow you to create a normal map from a texture. So, you could get an image of a real stitch, and generate a normal map from it.
> 1 votes

---
Tags: textures, 3dsmax
---


title: Path planning for volumes in games

text:
# Question
Title: Path planning for volumes in games
How would you path plan a volume for a game?

For example a 1 km cube with tunnels and caverns. Also the terrain is destructible.

You have walking and flying modes.

I would separate it into phases. Create a volume of the open space. Find a path that takes into account dynamic destruction.

Performance is a huge concern and the ability to find paths that are used in a short time.

Concrete example: Mine something deep in the ground efficiently.

The ground is destroy-able. "Caverns" are easy to dig areas. Mining is like flying. Need to see with sensors. The dataset is huge. Need to construct a transportation path to the target. May be multi-agent.

# Answer
> 3 votes
Dynamic pathfinding, to be reasonably performant, requires an algorithm specifically suited to this, like D\* (Dynamic A\*).

Beyond this, you may be able to find a way to perform hierarchical pathfinding. This way you have a simpler path at a lower resolution, and more complex subpaths at higher resolutions. By substituting any higher-resolution path subgraph into the lower resolution master graph, you can elaborate your path to whatever resolution you wish.

Lower resolution pathfinding is obviously great, as you can do minimal pathfinding until such time as you enter another subregion, and then perform more indepth pathfinding at that region's subdiv level.

As for the actual algorithm used to perform tunnelling through your 3D space, the biggest potential problem you'll face with this is entering 3D "dead-end" areas that you cannot get out of without crossing another passage (graph segment). See my recent monologue on planar graph embeddings here.

# Answer
> 1 votes
If by destructible terrain you mean major changes to the huge multilevel environment, this will be tough as hell, especially for walking units. It would be wise to divide flying and walking units from the very beginning, so they will have the separate graphs.

I can't say I know a definitive solution for the walking units. Depending on amount of the agents, potential terrain changes and cube node resolution, you may or may not want to use D\*. In essence, D\* is a brute force A\*. Like Nick hinted, brute forcing just one step ahead may result in a lot of "dead-ends", since without the whole path you won't be able to immediately tell whether next node is correct or not. Also you will have to think about path cache and its partial invalidation, so you don't have to brute force constantly on per-agent basis. Overall, it's not going to be easy and may become too CPU heavy.

Going with A\* instead, the simplest case would be to limit your terrain destruction to minimum and get away with hierarchical pathfinding, like "coarse" A\* and some form of local avoidance. I guess it's not an option, so you may try to convert your cube's ground and walls into a navigation mesh and then change it part by part. Navmesh calculation is not fast of course, but there is a room for various optimizations to avoid complete recalculation of the said mesh upon a terrain change. General idea is to perform a local mesh updates, so only the affected regions of a navigation mesh will be changed when terrain destruction occurs. It could be done using adaptation of the construction of Voronoi diagram, but it is not a "solved area". It won't be easy either, since you'll have to speed up the navmesh recalculation, but if accomplished, path finding will be fast and reliable.

Graph for air units is much simpler. Basically, you will have to find all "air space" and convert it into the graph. Since your caverns are dynamic, the most obvious choice is to base this graph on a cube's octree. Use octree leaf centroids (point in the middle of the leaf cube) as a basis for calculating nodes and filter out all centroids in the obviously invalid positions. Check resulting centroids to remove all that are inaccessible from their neighbours. This is going to be very fast, so your major concerns remain within ground pathfinding.

# Answer
> 1 votes
I have an open source implementation of pathfinding on a 3D grid as part of my voxel game SDK. It's an implementation of the A\* algorithm intended exactly for minecraft-style environments and voxel terrain.

It's not a dynamic algorithm as other people have suggested, so I can't help you there. I guess it depends how dynamic you world really is. It could also use some performance improvements as it can currently take a couple of seconds to find a path maybe 100 voxels long, but you may be able to run it on a down sampled version of your volume (through take care during the downsampling as valid paths may be created/lost).

You can see it in action here http://www.youtube.com/watch?v=C8y0OzL0zpM (that's not my game though), and get the source from http://www.thermite3d.org.

# Answer
> 1 votes
If you're world is already build from discrete blocks, then it makes sense to use them as the basis for your navigation.

Pathfinders are easy, fast pathfinders a bit harder. Path following and responding to the changes in the world is the real nastiness.

There are a couple of question which can help you narrow down the potential solution: \- what kind of NPCs you are trying to simulate? \- how long paths are you searching? \- how accurate paths you need?

If you have short paths and you're fine with "better than steering" quality, local grids \[1\] are good choice. They are super fast, you can make it work both 2D and 3D. You can get local grid data directly from your volume data, so the nav graph should stay in sync with the dynamic changes easily.

The problem with local grids are that if you have local minima in your world which is larger than your local grid, the agent may get stuck. It is possible to do tricks like add bread crumbs on locations where you detect local minima and try to avoid those locations when searching.

If you need long paths, I suggest some kind of hierarchical scheme. HPA\* should give you good ideas how to create sparse nodes in grid a world. Local grids can solve the path finding between the high level nodes. When you make changes to the world, you will need to locally change the coarse nodes too. You can also use the nodes to detect dynamic changes in the game world, and replan the path.

If you have dynamic world, pathfinding becomes statistics. There is no more any guarantees if the agent will find its way. Keeping track of the changes in the world is really hard and replanning when something goes wrong is sluggish.

Eskil rides with this idea in Love MMO, and his path finder is just random sampling with utility function (so is his action selection :)). I would recommend to do that first if it fits your game style.

\[1\] http://digestingduck.blogspot.com/2010/03/local-navigation-grids.html

# Answer
> 0 votes
You want to adopt a navigation mesh, or, if the world is particularly noisy on the vertical rather than just platforms or if flying mode is more than just jumping or hovering then you might use navigation volumes.

Detour is a lib for path-finding that allows you to update the navigation mesh live. I've never used it, I don't know how it works at your scale. A hierarchical system seems like a good idea.

Good reading when you contemplate writing your own is recent research of symmetry breaking. Well worth a thoughtful read!

Consideration has to be given to whether fog-of-war should affect pathfinding decisions. It may be that if asked to move to a new area a unit should move in a straight line until it meets obstacles, or it may be that the unit should make a route with full map knowledge. That's a game choice.

Fun reading: Fixing Pathfinding Once and For All

---
Tags: 3d, performance, path-finding, planning, voxels
---


# Question
Title: How useful would it be to know a scripting language when developing an iOS game?
> **Possible Duplicate:**
> Why do we use scripts in development?

I just starting learning iOS game development. I plan to make games using the cocos2d framework. While reading game dev related articles, blogs, books.. I've noticed scripting languages (such as Lua) are often used in game development. I'm wondering if it's worth taking the time to learn a scripting language. What's the role, usefulness of a scripting language in writing a game?

# Answer
Scripting is generally used in bigger projects to allow non-programmers to easily add content to the game. This can be new quests, interfaces, gameplay for levels, etc.

A scripting language in itself shouldn't be difficult for a programmer to learn, what will take time is the integration into your game framework.

Whether it's worth it or not is really your descision; if you want to easily add content to your game it could be a good idea to use scripting, it's also a good thing to know how these things work.

On the other hand for a smaller project, it's probably not worth it.

The big problem is that scripts generally take a lot of execution time if interpreted at game-time; for an iOS game this could be a bad idea if your game is going to be complex.
> 5 votes

---
Tags: ios, cocos2d, scripting
---


# Question
Title: How can I animate a recursive algorithm?
Say I have a recursive algorithm, for example one that generates a random tree:

```
// Pseudocode, just a simple algorithm: it isn't perfect.
function generate_branch(angle, length, current_depth, max_depth) {
  var branch = Branch(angle, length); // creates a new branch
  if (current_depth == max_depth) {
    return branch;
  }
  current_depth++;
  // random_int(min, max)
  branch.subbranches[] = generate_branch(random_int(0, angle + random_int(-30, 30)),
                                         random_int(0, 20)
                                         current_depth,
                                         max_depth);
  // ^^^^ recursion
  return branch;
}

var trunk = generate_branch(0, random_int(10), 0, 5);
RenderTree(trunk);

```

The problem is that this will render the entire tree in one frame. If I want to animate this (i.e. grow the tree over time), how would I do that? What is the best way to do this?

The game uses a game loop.

# Answer
You store the current depth of every branch for each node, and append Rendertree to render all nodes up to a specific depth, given as a parameter.

This way, you can show each depth level seperatly.

Pseudocode could be like this:

```
Generate tree

While(GameLoopRunning)
  begin
    for i := 0 to maxdepth do
      begin
        RenderTree(trunk, i)
        delay(250); //should not be like this, will block entire game loop.
      end
  end

```

Edit: You might want to use some kind of timer to fire some kind of GrowNow!-Events to your game logic in order to avoid the for-loop and delay in your main game loop.
> 1 votes

# Answer
What you can do is save a stack of the process you need to do (with all the parameters and depth), and only process one branch at a time, which will add one or more other branch to the stack.

This way you'll draw one step at a time. Of course you can choose to process more than one branch from the stack at a time or wait a delay between each process.
> 0 votes

---
Tags: graphics, algorithm, animation, timer
---


# Question
Title: Game Loop: Should resources be initialized in the game loop or in the respective classes? (both?)
For example, lets say we have an enemy class in my Android game project. I am initializing the enemy bitmap to be used with certain sprites in my game loops init. I am then calling the respective classes init, which is passed this loaded bitmap.

What is the process associated with initializing resources and classes in the game loop?

If I am totally off course just point me in the right direction.

Thanks! :D

# Answer
> 2 votes
Whenever I question myself questions like this I try to look at existing examples. In about every game you get a loading screen before the actual game starts -\> the loading starts before the actual has started. So all the loading should preferably happen before the gameloop.

When your running a game and a new object is created, which also needs a new resource(let's say a png file for a sprite). You could refer to the already loaded file to prevent loading at run time. Which files should be loaded before beginning a level should be defined somewhere in your level data.

There are scenarios where you are unsure which assets you will use though (dynamically created world for example). I use the following method for this:

\[pseudo code\]

```
Class ContentManager()
   {
       Array assets = new Array();

       public static Sprite getSprite(string spritename ){ //or sprite id or whatever unique identifier

           for (Sprite sprite : assets){

               if(sprite.name == spritename){

                   return sprite;
               }
           }

           //it's not found in the list, so let's load it
           Sprite newsprite = Loader.load(spritename);
           assets.push(newsprite);
           return newsprite;
       }
   }

```

In short: add every loaded asset to an array. When you need to use an asset, check if it's in the list. Return the sprite if it's there, or load it and add it to the array if it's not found.

# Answer
> 3 votes
Initialization should not happen in the game loop, you'd end up loading the same resource over and over again.

For a resource like an image associated with a class you should make a static field for holding the reference to the resource. You must load the resource only once. You could do this separately, or you could check during instance initialization if the resource has been loaded or not and then load it if need be.

---
Tags: android, game-loop, loading
---


# Question
Title: Octree contains tris, shapes, models or both?
Right now, each node of my octree contains a `list<Triangle*>` (pointers to mesh triangles).

So basically an octree query returns poly soup.

Sometimes I want to query the octree for entire objects however. Each Tri has a pointer to its "owner object", but should I park the object references in the same octree (ie give each node a `list<GameObject*>` or maintain a completely different octree altogether?

# Answer
> 2 votes
The thing is, your object octree's final structure is going to be different than your poly octree's structure, because the objects are larger than the polys in your soup. So I think it might be wise to aim for a separate octree. After all, octrees are an optimisational bit of architecture. If aiming for faster throughput, I would definitely duplicate the octree so each one fits it purpose. Space optimisation, as you know, is not usually our primary concern as game developers :)

---
Tags: octree
---


title: moving glDepthMask into a shader

text:
# Question
Title: moving glDepthMask into a shader
Can a fragment shader make per-fragment decisions on whether the fragment updates the depth buffer or not, even if the fragment is not discarded and the color is written?

# Answer
I don't think so. If you don't write into `gl_FragDepth`, OpenGL writes the interpolated depth. There is no magic "discard" value you could write into `gl_FragDepth` and like you yourself say, `discard` also discards colors.

And as a side note I'm also sure to have read, that if you write into `gl_FragDepth` in one dynamic branch of a shader, you have to write into it in all branches, otherwise the results are undefined. But maybe this has changed on newer hardware.

**EDIT:** Maybe you can use a (though quite strange) workaround using `ARB_shader_stencil_export` extension (or perhaps some newer core version supporting it). In the first pass disable depth update (depth mask false) and write a special stencil value (maybe 1) for the fragments you want to write the depth for and another (0) for the ones you don't. Then in the second pass you draw the scene/objects/whatever again enabling depth write and configuring the stencil test to only pass where the stencil buffer is set. So only the depth of the fragments you (dynamically) selected are written. But the two-pass nature of this might bring some problems whith "underdraw" that shouldn't be, as in the first pass no fragment writes any depth value.
> 2 votes

---
Tags: opengl, glsl
---


# Question
Title: Correct way to abstract an XBox Controller
I've got a XBox360 controller which I'd like to use as input for an application.

What I can't work out is the best-practice way to expose this via an interface.

Behind the scenes, the class which handles the controller(s) relies on polling button state.

I initially tried something link:

```
Event ButtonPressed() as ButtonEnum

```

where `ButtonEnum` was `ButtonRed`, `ButtonStart`, etc...

This is a little limited in that it only supports button presses, not holds / patterns (press twice, etc.)

The next idea was to simply expose the button state to the app eg

```
Property RedPressed as Boolean
Property StartPressed as Boolean
Property Thumb1XAxis as Double

```

This is very flexible but really it forces too much work into the app and requires the app to poll - I'd prefer event driven if possible.

I considered adding multiple events eg:

```
Event ButtonPressed(Button as ButtonEnum)
Event ButtonPressedTwice(Button as ButtonEnum)
Event ButtonHeldStart(Button as ButtonEnum)
Event ButtonHeldEnd(Button as ButtonEnum)

```

but this seems a little clunky and was a real pain on the "Bind button" screen.

Can someone please point me at the "correct" way to handle inputs from controllers.

NB: I'm using SlimDX inside the class which implements the interface. This allows me to read state very easily. Any alternatives which would solve my problem are also appreciated

# Answer
> 22 votes
There is no one perfect mapping that gives you a platform specific abstraction, because obviously most of the identifiers that make sense for a 360 controller are wrong for a PlayStation controller (A instead of X, B instead of Circle). And of course a Wii controller is another thing altogether.

The most effective way I've found to deal with this is to use three layers of implementation. The lower layer is entirely platform / controller specific, and knows how many digital buttons and analogue axes are available. It's this layer which knows how to poll the hardware state, and it's this layer that remembers the previous state well enough that it knows when a button has just been pressed, or whether it's been down for more than one tick, or whether it's not pressed. Other than that it is dumb - a pure state class representing a single type of controller. It's real value is to abstract the nitty gritty of querying the controller state away from the middle layer.

The middle layer is the actual control mapping from real buttons to game concepts (e.g. A -\> Jump). We call them impulses instead of buttons, because they're no longer bound to a particular controller type. It's at this layer you can remap controls (either during development or at runtime at the user's behest). *Each platform has its own mapping of controls to virtual impulses*. You cannot and should not try to get away from this. Every controller is unique, and needs its own mapping. Buttons may map to more than one impulse (depending on the game mode), and more than one button may map to the same impulse (e.g. A and X both accelerate, B and Y both decelerate). The mapping defines all of that, but is simply a list of inputs (in terms of buttons or axes) to outputs (in terms of digital or analogue impulses).

The upper layer is the game layer. It takes impulses, and doesn't care how they were generated. Maybe they came from a controller, or a recording of a controller, or maybe they came from an AI. At this level, you don't care. What you care about is that there is a new Jump impulse, or that the Accelerate impulse has continued, or that the Dive impulse has a value of 0.35 this tick.

With this sort of a system, you write the bottom layer once for each controller. The upper layer is platform independent. The code for the middle layer only needs written once, but the data (the remapping) needs redone for each platform / controller.

# Answer
> 1 votes
Honestly, I'd say optimal interface would depend heavily on the usage in game. However, for a general usage scenario, I'd suggest a two-tier architecture which separates event based and polling based approaches.

The lower tier could be considered the "polling based" tier, and exposes the current state of a button. One such interface could simply have 2 function, `GetAnalogState(InputIdentifier)` and `GetDigitalState(InputIdentifier)` where `InputIdentifier` is an enumerated value representing which button, trigger or stick you're checking against. (Running GetAnalogState for a button would return 1.0 or 0.0, and running GetDigitalState for an analog stick would return true if over a preset threshold, or false otherwise).

The second tier would then use the lower tier to generate events upon state change, and allow elements to register for callbacks (C# Events are glorious). These callbacks would include events for press, release, tap, longhold, etc. For an analog stick, you could include gestures, e.g. QCF for a fighting game. The number of events exposed would depend on how detailed of an event you want dispatched. You could just fire a simple `ButtonStateChanged(InputIdentifier)` if you wanted to handle everything else in separate logic.

So, if you needed to check current state of an input button or control stick, check the lower tier. If you wanted to simply fire off a function upon an input event, register for a callback from the second tier.

---
Tags: architecture, input, design-patterns, xbox-controller
---