# Question
Title: GLSL, all in one or many shader programs?
I am doing some 3D demos using OpenGL and I noticed that GLSL is somewhat "limited" (or is it just me?). Anyway I have many different types of materials. Some materials have ambient and diffuse color, some materials have ambient occlusion map, some have specular map and bump map etc.

Is it better to support everything in one vertex/fragment shader pair or is it better to create many vertex/fragment shaders and select them based on currently selected material? What is the usual shader strategy in OpenGL or D3D?

# Answer
The answer is, it kinda depends.

Basically there are two schools of thought; small, optimal shaders for everything and the uber-shader camp.

The small shaders are just that; do one thing, and do it well. Uber-shaders either control their functionality at runtime through uniforms, or compile into a bunch of different shaders through preprocessor macros (and/or generated shader sources).

The optimal solution is probably neither, but some kind of hybrid. Perhaps a few uber-shaders or uber-shaders combined with specialized shaders for some cases.

**Small shader**

Pros:

* Likely to be faster/more optimal
* Does just what you want it to do
* Can do weird, custom stuff easily

Cons:

* Easily gets out of hand, especially when the number of features grows
* Probably more work, unless you have a very small number of shaders

**Uber-shader**

Pros:

* Everything in one place
* More artist-friendly (using feature A with feature X for the first time doesn't necessarily require coder time)

Cons:

* Longer shader compile times
* Less optimal results (esp. if uniforms are used to switch features on/off)
* May be more difficult to debug/optimize
> 15 votes

---
Tags: opengl, 3d, shaders, glsl
---


# Question
Title: Is finding graph minors without single node pinch points possible?
Is it possible to robustly find all the graph minors within an arbitrary node graph where the pinch points are generally not single nodes? I have read some other posts on here about how to break up your graph into a Hamiltonian cycle and then from that find the graph minors but it seems to be such an algorithm would require that each "room" had "doorways" consisting of single nodes.

To explain a bit more a visual aid is necessary. Lets say the nodes below are an example of the typical node graph. What I am looking for is a way to automatically find the different colored regions of the graph (or graph minors)

# Answer
> 1 votes
You're essentially looking for short interior paths.

I'm assuming that you have a planar embedding of your graph and can determine the circumference. An interior path is a path between nodes that doesn't contain edges on the circumference. The short paths you're looking for have the following properties:

1. They're between two nodes that are both on the circumference, but not adjacent
2. They're the shortest path between those two
3. They're shorter than a non-interior path
4. They're shorter than an adjacent path (one between one of the original nodes and a neighbor of the other)

Your "pinch points" are of course special cases where that length is zero.

Now, how would you determine such short interior paths? It's not horribly inefficient to create a NxN table listing the shortest interior paths between all N edge points. So, just get the local minima from that.

---
Tags: ai, path-finding, graph, graph-theory
---


# Question
Title: Better way to generate enemies of different sub-classes
So lets pretend I have an enemy class that has some generic implementation and inheriting from it I have all the specific enemies of my game. There are points in my code that I need to check whether an enemy is a specific type, but in Java I have found no easier way than this monstrosity...

```
//Must be a better way to do this
if ( enemy.class.isAssignableFrom(Ninja.class) ) { ... }

```

My partner on the project saw these and changed them to use an enum system instead

```
public class Ninja extends Enemy {
    //EnemyType is an enum containing all our enemy types
    public EnemyType = EnemyTypes.NINJA;
}

```

```
if (enemy.EnemyType = EnemyTypes.NINJA) { ... }

```

I also have found no way to generate enemies on varying probabilities besides this

```
for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        enemy = createEnemy(types.getEnemyType());
        break;
    }
}

```

```
private static Enemy createEnemy(EnemyType type) {
    switch (type) {
        case NINJA:
            return new Ninja(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case GORILLA:
            return new Gorilla(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
        case TREX:
            return new TRex(new Vector2D(rand.nextInt(getScreenWidth()), 0), determineSpeed());
     //etc
    }
return null
}

```

I know java is a little weak at dynamic object creation, but is there a better way to implement this in a way such like this

```
for (EnemyTypes types : enemyTypes) {
    if ( (randomNext = (randomNext - types.getFrequency())) < 0 ) {
        //Change enemyTypes to hold the classes of the enemies I can spawn
        enemy = types.getEnemyType().class.newInstance()
        break;
    }
}

```

Is the above possible? How would I declare enemyTypes to hold the classes if so? Everything I have tried so far as generated compile errors and general frustration, but I figured I might ask here before I completely give up to the huge mass that is the `createEveryEnemy()` method. All the enemies do inherit from the Enemy class (which is what the `enemy` variable is declared as). Also is there a better way to check which type a particular enemy that is shorter than `enemy.class.isAssignableFrom(Ninja.class)`?

I'd like to ditch the enums entirely if possible, since they seem repetitive when the class name itself holds that information.

# Answer
Actually, everything you mentioned is possible:

```
Class<?> cl = Class.forName(className);
Constructor<?> ctor = cl.getConstructor();
DesiredType object = (DesiredType) ctor.newInstance();

```

or with 1 line:

```
return (DesiredType) Class.forName(className).getConstructor().newInstance();

```

You can even have arguments passed to the constructor. See this: https://stackoverflow.com/questions/6094575/creating-an-instance-using-the-class-name-and-calling-constructor

Getting the class name of a created object instance is also possible with: obj.getClass.getClassName()

However I think you should avoid using this kind of code too much, because it is prone to errors, e.g, if you refactor the name of one of your classes, the IDE won't change it in that code.
> 5 votes

# Answer
Like joxnas says in his comment, you can create an array or collection of `Class<?>` objects (or `Class<Enemy>` may be more useful) as your `enemyTypes`. Creating an `Enum` to describe the type seems to me to be a duplication of information that is already there.

There is a subtle difference between `enemy.class.isAssignableFrom(Ninja.class)` and `enemy.EnemyType == EnemyTypes.NINJA`. The former will match subclasses of `Ninja` (or more generally anything assignable from a `Ninja` as the name suggests) whereas the latter will not. Another alternative that is equivalent to the latter is `enemy.getClass() == Ninja.class`. Choosing what operation to perform based on the type of the object is what polymorphism does best and it is *usually* preferrable to 'switching on type' as you are doing. I don't know your particular use cases and nothing is a silver bullet but it would be worth investigating. Instead of this:

```
if (enemy.getClass() == Ninja.class) {

    // Throw shuriken
    // Dodge

} else if (enemy.getClass() == Gorilla.class) {

    // Throw banana
}

```

which will need to be updated every time you add a new enemy class, consider adding abstract `throw()` and `dodge()` methods to the `Enemy` class/interface and just do this:

```
enemy.throw();
enemy.dodge();

```

I'm not going to go into how to dynamically instantiate objects because I think joxnas has covered that but I'll note that by using a collection of `Class<Enemy>`s instead of the `Enum` you can avoid the need to switch on type during instantiation which could be reduced to this:

```
for (Class<Enemy> type : enemyTypes) {
    if ((randomNext = (randomNext - getFrequency(type))) < 0) {
        enemy = type.newInstance();
        break;
    }
}

```

Granted it is a little more complex when you add exception handling and the ability to pass arguments to the constructor.
> 3 votes

# Answer
Basically I'd question your approach in general, subclassing is in this case not a good idea, from my point of view.

I think to avoid this glitch, you could start using a single enemy class that you can instantiate in a simple way to prevent this inheritance relation which causes you problems later on. Furthermore you could introduce a configuration mechanism, maybe using xml, where you describe your enemies and their attributes. For instantiation then you can create a new randomly chosen enemy from the existing templates, without having to worry about the actual creature type.

For an example you could look into the way the Stendhal project does it:

If you then still need to differentiate things like behaviour, you need to decompose this into singular components from which you can construct your enemy instances.
> 2 votes

# Answer
You could add some type of flag(maybe an int or short) to each enemy type. Then check the flag for which type it is.
> 0 votes

---
Tags: java, android
---


title: Pitch camera around model

text:
# Question
Title: Pitch camera around model
Currently, my camera rotates with my model's Y-Axis (yaw) perfectly. What I'm having trouble with is rotating the X-Axis (pitch) along with it. I've tried the same method for `cameraYaw()` in the form of `cameraPitch()`, while adjusting the axis to `Vector.Right`, but the camera wouldn't pitch at all in accordance to the Y-Axes of the controller.

Is there a way similar to this to get the same effect for pitching the camera around the model?

```
// Rotates model on its own Y-axis
    public void modelRotMovement(GamePadState pController)
    {
        Yaw = pController.ThumbSticks.Right.X * MathHelper.ToRadians(speedAngleMAX);

        AddRotation = Quaternion.CreateFromYawPitchRoll(Yaw, 0, 0);
        ModelLoad.MRotation *= AddRotation;
        MOrientation = Matrix.CreateFromQuaternion(ModelLoad.MRotation);
    }

    // Orbit (yaw) Camera around model (camTarget is the model's position)
    public void cameraYaw(Vector3 axis, float yaw)
    {

        ModelLoad.CameraPos = Vector3.Transform(ModelLoad.CameraPos - ModelLoad.camTarget,
            Matrix.CreateFromAxisAngle(axis, yaw)) + ModelLoad.camTarget;
    }

    public void updateCamera()
    {
        cameraYaw(Vector3.Up, Yaw);
    }

```

# Answer
It looks to me like all you would need to do to pitch around an object is call the cameraYaw method with as first argument Vector3.Backward. This way you will rotate around the Z axis (pitching) instead of around the Y axis (yawing).

If you want to both pitch and roll at the same time you will need to create an arcball camera. I've written a code snippet for XNA that gives you a very simple arcball camera. Just set the look at to where your model is, use zoom to zoom out from your model and start manipulating the pitch and yaw variables http://roy-t.nl/index.php/2010/02/21/xna-simple-arcballcamera/

To not leave you with just a link here is the most important part of the code.

```
            //Calculate the relative position of the camera
            position = Vector3.Transform(Vector3.Backward, Matrix.CreateFromYawPitchRoll(yaw, pitch, 0));
            //Convert the relative position to the absolute position
            position *= zoom;
            position += lookAt;

            //Calculate a new viewmatrix
            viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);

```

As you can see I first transform a vector that points to (0,0,1), *that is towards the player sitting behind the monitor*, given a yaw, pitch and roll. After that I still have a normalized vector but it's pointing to where I want the camera to be. I then scale the vector so that the camera is the distance from the model that. After that I move the vector so that it orbits the model instead of (0,0,0). Finally I create the viewmatrix that you can pass to your effect.
> 1 votes

---
Tags: xna, camera, rotation
---


# Question
Title: Circular movement - eliminating speed ups near Y = 0
I have a basic algorithm to rotate an enemy around a 200 unit radius circle with center 0. This is how I'm achieving that:

```
if (position.Y <= 0 && position.X > -200)
{
   position.X -= 2;
   position.Y = 0 - (float)Math.Sqrt((200 * 200) - (position.X * position.X));
}
else
{
   position.X += 2;
   position.Y = (float)Math.Sqrt((200 * 200) - (position.X * position.X));
}

```

It does work, and I've ensured that at no point does either X or Y equal NaN. However, when Y approaches 0, it seems to go significantly faster. This surprises me, because the Y values are locked to the X, which is being incremented by a steady amount. What can I do to smooth the speed?

# Answer
The problem here is that sqrt(a*a + b*b) is non behaving in the way you expected it is non-linear as you can clearly see here:

I don't see any immidiate way on how to fix this. (To be honest I'm surprised this worked in the first place). But I can give you the standard algorithm to accomplish this. This will also keep speed constant and you can use the values of the cos and sin operations later to rotate the player towards the center of your circle.

```
float time; //use gameTime.TotalGameTime.TotalSeconds and update it every frame
float speed = MathHelper.PiOver2; // in radians per second, this is 1/4 of a circle per second atm
float radius = 200.0f;
Vector2 origin = Vector2.Zero; // change this if you want your circle's origin elsewhere

position.X = (float)(Math.Cos(time * speed) * radius + origin.X);
position.Y = (float)(Math.Sin(time*speed) * radius + origin.Y);

```
> 4 votes

# Answer
Y values are locked to f(x). f(X) does not equal X therefore Y is not locked to X.

You need a constant angular delta, which can be achieved by using a pair of sin/cos functions:

```
x = sin( time * speed + offset ) * radius + center_x;
y = cos( time * speed + offset ) * radius + center_y;
OR
x = cos( time * speed + offset ) * radius + center_x;
y = sin( time * speed + offset ) * radius + center_y;

```

Both ways are valid (first one - logically, like a clock, second - mathematically), they just change starting point (top for first, right side for second) and default direction (when speed is positive, clockwise for first, counter-clockwise for second). Speed and offset are measured in radians.
> 1 votes

---
Tags: xna, movement
---


# Question
Title: Are the first three values that describe a 3D plane actually a 3D vector?
A 3d plane is typically defined as `a,b,c,d`. Are `a,b,c` actually the `x,y,z` coordinates of a 3d vector, with `d` defining the rotation of the plane, something like axis-angle rotation data?

# Answer
> 23 votes
The four-variable representation of a plane is the coefficients in the equality

$$ax + by + cz = d$$

This can be seen as \\$N = (a, b, c)\\$ being a normal vector and \\$d\\$ being a *distance from the coordinate origin* (in units of the-length-of-\\$N\\$), and we can also write this equation as

$$N \cdot P = d,$$

where \\$P = (x, y, z)\\$ is the point which the equality tells us is or isn't on the plane.

This representation *does not allow* defining a specific “origin of the plane” — mathematical planes don't have origins. (However, it happens that since \\$N \cdot P = d\\$, if we set \\$P = (d\left|N\right|^{-2})N\\$, then we get a specific point on the plane: the point which is nearest the origin *of the coordinate system*.)

If you change the = to \< or \>, you describe a "half-space", which can be used for things such as an infinite floor in a physics engine; the opposite half-space is obtained by negating both \\$N\\$ and \\$d\\$.

# Answer
> 3 votes
*"Typically"* is a quite subjective word, in my experience there are different way to describe a plane in a 3D space that are more common because of the properties that such constructions show.

About your question, there is away to use 4 real values to determine a plane in a 3D space. As you pointed out, a,b,c may be the components of a vector that is perpendicular to the desired plane. If **N** =(a,b,c) is our perpendicular vector, you may find a point in your plane that is **P** = *d* **N** for some *d* real and positive. Here you say that *d* is the distance from the origin in term of **N**; if **N** is a unit vector, then *d* is the distance between the origin and your plane in the way that the term *"distance"* is commonly meant.

Surprisingly you can define any possible **oriented** plane bacause you can use a negative values of *d*; doing so you loose the direct meaning of *d* as distance until you put it in an absolute value (*|d|*).

# Answer
> -1 votes
As far as I know a plane is usually defined by a position, for telling us where the origin is, and a normal pointing upwards from the plane to tell us what orientation we have. It's common practice to use two vectors for this.

With four variables you don't have enough variables to define a plane that doesn't have an origin at (0,0,0) or not enough variables to account for all rotations.

The minimum we would need for a plane in 3D euclidean space with an origin that's not at (0,0,0) and can be oriented in anyway we want is 5. Imagine the unit sphere, we need 3 variables to define where the origin of the unit sphere is (X,Y,Z). Then we need two variables to define where the 'up' of the plane is. We can do this by using the vector described by going from the origin of the sphere towards it's surface given a latitude and longitude.

How you would reconstruct a plane with only four variables I don't know. Maybe you're working in a narrow domain (the plane is always at (0,0,0) and the four variables are a quaternion?) or the variables aren't scalars? In what context are you using this a,b,c,d?

---
Tags: 3d, geometry
---


# Question
Title: Checking if an object is inside bounds of an isometric chunk
How would I check if an object is inside the bounds of an isometric chunk? for example I have a player and I want to check if its inside the bounds of this isometric chunk. I draw the isometric chunk's tiles using OpenGL Quads.

My first try was checking in a square pattern kind of thing:

```
e = object;
this = isometric chunk;

    if (e.getLocation().getX() < this.getLocation().getX()+World.CHUNK_WIDTH*World.TILE_WIDTH && e.getLocation().getX() > this.getLocation().getX()) {
        if (e.getLocation().getY() > this.getLocation().getY() &&   e.getLocation().getY() < this.getLocation().getY()+World.CHUNK_HEIGHT*World.TILE_HEIGHT) {
            return true;
        }
    }
    return false;

```

What happens here is that it checks in a SQUARE around the chunk so not the real isometric bounds. Image example: (THE RED IS WHERE THE PROGRAM CHECKS THE BOUNDS)

What I have now:

Desired check:

Ultimately I want to do the same for each tile in the chunk.

EXTRA INFO:

Till now what I had in my game is you could only move tile by tile but now I want them to move freely but I still need them to have a tile location so no matter where they are on the tile their tile location will be that certain tile. then when they are inside a different tile's bounding box then their tile location becomes the new tile. Same thing goes with chunks. the player does have an area but the area does not matter in this case. and as long as the X and Y are inside the bounding box then it should return true. they don't have to be completely on the tile.

# Answer
```
e = object;
this = isometric chunk;

```

//for readability(long version)//

```
pointX = e.getLocation().getX();
pointY = e.getLocation().getY();

chunkSizeX = World.CHUNK_WIDTH  * World.TILE_WIDTH;
chunkSizeY = World.CHUNK_HEIGHT * World.TILE_HEIGHT;

chunkCenterX = this.getLocation().getX() + chunkSizeX / 2.0;
chunkCenterY = this.getLocation().getY() + chunkSizeY / 2.0;

deltaX = pointX - chunkCenterX;
deltaY = pointY - chunkCenterY;

if(deltaX < 0) deltaX *= -1;
if(deltaY < 0) deltaY *= -1;

//these two are floating point number

distanceX = deltaX / chunkSizeX;
distanceY = deltaY / chunkSizeY;

if(distanceX + distanceY < 1.0) return true
else return false;

```

Basically, imagine each player starts in the center of the chunk. Assuming the player can only move: up, down, left and right and speed is adjusted proportionally when moving on the y-axis to:

```
TILE_HEIGHT / TILE_WIDTH * X_AXIS_SPEED

```

She will need at least n steps to get out of the player will need exactly n steps to get out. of the chunk area. I will not prove this unless requested. Therefore, we just check if the player took 100% of the necessary steps to get out of the chunk.
> 3 votes

# Answer
Have a look to my answer to Finding out which tile a mouse click landed in. Your error here is to forget that the isometric has a different coordinate system from the one used on the screen.

You should consider to store the players coordinate position in term of isometric coordinates; the position in term of (x-tile-index-and-fractions,y-tile-index-and-franctions) may work and help your game logic to be thought of as if it lives in an isometric world.
> 3 votes

---
Tags: opengl, java, isometric, tilemap, bounding-boxes
---


# Question
Title: What RPG game engine in JavaScript could I use?
I am trying to build an RPG using `HTML5/JavaScript`. Can anyone point out a few game engines for developing RPG in JavaScript

# Answer
> 3 votes
A quick google search lead me to the page below, where you can find a list of JS game engines. While not every engine on the list is specifically designed for RPGs, you should be able to quickly determine which engines may fit your needs.

https://github.com/bebraw/jswiki/wiki/Game-Engines

---
Tags: html5, rpg
---


# Question
Title: How do I import Motionbuilder animation into my game?
I have an animation sequence for a 3D model built in Autodesk Motionbuilder. How would import the data for the sequence into my java game for my model? Is there any tutorial on how to accomplish this? I already have my 3D model loaded into the scene.

# Answer
Every game company has its own trick and method. The way I think you should do it is to export each frame and then load each frame in order to your java application. This process is called animation.
> 0 votes

---
Tags: java, 3d, models
---


# Question
Title: Can I use GLFW and GLEW together in the same code
I use the g++ compiler, which could be causing the main problem, but I'm using GLFW for window and input management, and I am using GLEW so that I can use OpenGL 3.x functionality. I loaded in models and then tried to make Vertex and Index buffers for the data, but it turned out that I kept getting segmentation faults in the program. I finally figured out that GLEW just wasn't working with GLFW included. Do they not work together?

Also I've done the context creation through GLFW so that may be another factor in the problem.

# Answer
GLFW can be used with GLEW:

http://www.glfw.org/faq.html#2\_15

> 2.15 - Can I use GLEW with GLFW?
>
> Yes, as long as you include the GLEW header before the GLFW one. The GLEW header defines all the necessary magic macros to make sure the gl.h that GLFW attempts to include doesn't interfere.
> 7 votes

# Answer
I have been encountering some problems too.

What I have found is if you don't specify the context version or use core profile it seems to load the latest version of OpenGL without issues.

The glew error might be because of it using the older glGetString(GL\_EXTENSIONS) rather than glGetStringi. You might be able to work around it by using glewExperimental=true before calling glewInit(). See here.

Otherwise you can drop GLEW all together and use the official Kronos OpenGL extension header glcorearb.h (previously it was gl3.h). That won't load 3rd party extensions but it seems to work fine for what I have been doing (not sure if it's suitable for large projects or not it's only listed as a reference implementation).

Also make sure you have called glewInit(). You can check if an extension is enabled with:

```
if(glGenBuffers) {
   //
}

```

Otherwise GLEW has its own way using glewIsSupported("GL\_ARB\_vertex\_buffer\_object")
> 1 votes

---
Tags: opengl
---


# Question
Title: Can I name a team with the name of their city to avoid trademark issues?
I was wondering, if you want to make a NBA game on smartphones, without the license held by *EA*, the first solution seems to name your teams with a different name, such as "Chicragro Brulls" (this is just for the example), but would it be possible to just call your team with the name of the city, such as "Chicago vs. Dallas" ? I know the first solution was chosen by *Pro Evolution Soccer*, would you know any other game that don't use a license?

# Answer
*I am not a lawyer. This is not legal advice. Blah, blah blah...*

Obviously this all depends on where you are doing business, but regardless, I'm going to play devil's advocate here and say that while city names are not protected trademarks, you can still be taken to court based on *likeness* of the name. Especially if you use the same team colors, and so on.

If you want to be on the safe side, just come up with a few dozen new team names and let players rename them. If the player wants to make the Chicago Bulls, then they can name the team that and setup the jersey colors to match.

Better yet, don't even try and compete with EA Sports (and the other AAA sports-realism game studios) and build a basketball game that is more unique: like a bunch of gangs playing street-ball where there are no real rules except put the ball in the hoop. That sounds like way more fun anyway. ;-)
> 2 votes

# Answer
I'm not a lawyer, so this is just my interpretation of the law. Before you release anything, talk to a lawyer. Your legal decisions are your own.

Names of cities are not protected trade marks (yet?), you can use them how you like. You may also look into giving the city name as the default and allowing the player to change the name of the team if they desire.

As far as other games that may employ similar methods, I don't know, and it's not really on topic for the site.
> 2 votes

---
Tags: legal, licensing
---


# Question
Title: Rendering two textures with blending and alpha test
What I am looking for is the following: I have a circle on a square image, alpha is 0 at the corners

and also a square shadow, alpha is 0 everywhere else

I would like to have as final result a blending of these two renders, plus the shadow not being rendered outside the circle

How could I achieve that?

# Answer
What you probably want is a stencil buffer. Render your circle with stencil write, and then change opengl state so that only the bits that have the stencil bits on should be updated, and then render your shadow thingy.
> 2 votes

---
Tags: opengl, textures, blending, transparency, jogl
---


title: Sorting objects before rendering

text:
# Question
Title: Sorting objects before rendering
I'm trying to implement a scene graph and in all the articles i've come across there is talk about object sorting. So you'd sort your objects by "material" for example. Now untill i sat down and started implementing it, i kind of took this for granted, because it made sense. But now i'm wondering what does sorting actually change?

In my engine, i have a manager for UBOs, i use those to store data that'll be shared between programs, at the moment that only involves time, camera and projection matrices and lights (i'm not worrying about managing which lights affect which objects ATM).

Now for each model i have to change the model to world matrix uniform, no sorting is going to change that. So is the jump from changing this matrix to also setting a material for each object that bad?

I **vaguely** remember reading somewhere that each time you change something in the pipeline, it has to get flushed and that can cause performance issues. But for each drawing call i'm setting up a model to world matrix anyway, so what sense does it make to ever be concerned about this?

BTW is there any information about whether changing a uniform and calling glBufferSubData is more (or less) expensive.

# Answer
> 4 votes
You definitely want to sort to batch together materials. If you can, you can also use instancing to batch together geometry (e.g. If you have X number of the same objects).

There's also still value in sorting by depth, too. You must sort back to front for transparent objects (ignoring several advanced techniques that remove that need, in limited circumstances).

There's also value in sorting opaque objects front to back, as that allows early-Z to greatly reduce the fragment shader overhead of your scene.

# Answer
> 3 votes
Sorting objects purely by depth has a huge value, especially on binning or tiled rendering architectures.

Sort solids front to back, transparencies from back to front.

When rendering, the stuff that's closest to the camera and solid gets rendered first, and anything else that occupies the same space will be rejected by an early z-buffer check.

If the graphics architecture has some kind of hierarchial or low resolution z-buffer, the geometry may get culled even before anything gets rendered.

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


# Question
Title: How to draw unlimited FPS on Mac OS X with OpenGL?
I d'like to draw as many frames as possible with OpenGL on Mac OS X to measure the performance on different scenes. What I've tried so far:

1. Using a `CVDisplayLink` that has `NSOpenGLCPSwapInterval` set to 0, so it does not sync with the Display. But with that it's still stuck at max 60FPS
2. Using normal -drawRect: with a timer that fires 1/1000sec and calls `-setNeedsDisplay:` Still not more than 60FPS
3. Same as 2. but I call -display in the timer callback. With that I get the FPS above 60, but it still stops at 100-110 FPS. Although the frame rate should easily be at 10times more.

Andy idea how I can really draw as many frames as possible?

# Answer
> 1 votes
This stack overflow answer has some calls you can use to disable vsync..

https://stackoverflow.com/questions/10866561/cocoa-opengl-unlocked-framerate/10881400#10881400

..not sure if that changes anything though. One API should work just as well as another.

---
Tags: opengl, macos
---


# Question
Title: How do I create a fire sphere (fireball) in opengl? (opengl Visual C++)
I'm making an evil Pacman in OpenGL and I need to make my spheres look like a fireballs, does anyone know how I do that?

And what material colour should I use?

Also, is there a colour palette to change the colour of my materials?

This is how I create a sphere:

```
GLfloat mat_ambient[] = { 0.25, 0.25, 0.25, 1.0 };
GLfloat mat_diffuse[] = { 0.4, 0.4, 0.4, 1.0 };
GLfloat mat_specular[] = { 0.774597, 0.774597, 0.774597, 1.0 };
GLfloat mat_shine = 0.6;

glMaterialfv (GL_FRONT, GL_AMBIENT, mat_ambient);
glMaterialfv (GL_FRONT, GL_DIFFUSE, mat_diffuse);
glMaterialfv (GL_FRONT, GL_SPECULAR, mat_specular);
glMaterialf (GL_FRONT, GL_SHININESS, mat_shine * 128);

glPushMatrix();
glTranslatef(x,y,0);
glutSolidSphere(size, 20, 10);
glFlush();
glPopMatrix();

```

# Answer
Unless you have a reason for your fireball to be actual geometry, I'd opt for a simple 2d impostor instead.

There's a simple photoshop tutorial for making fireballs here: http://sol.gfxile.net/firey/index.html

The resulting image looks like this:

To animate the fire, just overlay a few textures like that with additive blending and rotated around the z axis. Maybe add a particle system for flair.
> 3 votes

# Answer
Search for "Realistic and Controllable Fire Simulation" on Google.

http://www.cs.sunysb.edu/vislab/wordpress//papers/VoxelsOnFire.pdf is one example

For starters, you should set a simpler object, that you create from triangles (not the GLUT ones) and think of ways of animating fire. There are way too many possibilities: particle effects, voxels, shaders. Google for any of these ways of simulating fire.. your question is more about explaining/doing a tutorial on how to implement such an effect, so it can't be answered here. Good luck in selecting your tools ;)
> 0 votes

---
Tags: c++, opengl
---


# Question
Title: iOS Game Center - Quit turn-based games for previous version of app
I have a game on the iOS App Store that uses Game Center for turn-based multiplayer (GKTurnBasedMatch). I recently updated the app with a new game mode and I had to change the network protocol for that to happen. As a result I marked my new version as incompatible with the old one. That is, you cannot see the old games within the new app and you cannot initiate a game with someone with the old version of the app. This works as expected. However:

**The old games remain active after updating. There seems to be no way to quit them.** What is worse is that **they still count to the maximum number of games you can start**. I have been contacted by players that can only start 1-3 games without hitting the roof.

Have anyone experienced this before? Is there any way to quit the games?

Thanks in advance

# Answer
> 0 votes
Contact Apple tech support. Submit a TSI and request that they terminate the active games.

Additionally you can see if your question has been answered already, or ask your question on the Apple developer forums.

---
Tags: iphone, ios, multiplayer, turn-based, game-center
---


# Question
Title: Is it possible create an HTML5 mobile game without the user having internet connection?
I trying to make a app for the Play Store and App Store. My app will be 2D, but will have 3D effects. Is it possible to program it in HTML5 without the user having internet connection? Also, are there any good tutorials on HTML5? Thank you in advance.

# Answer
In theory with HTML5 you get what you need to code what you want to do, but you can't create an app with just a pure HTML5 codebase, you need to interface your code with native code in a way or another. The real solution that can fit your case is using an HTML5 framework like phonegap. It's the easiest and shortest way in your case.
> 3 votes

# Answer
You can in principle, create an offline HTML5 application, as descibed, for example, here:

http://www.w3.org/TR/offline-webapps/#offline

This involves creating some manifest file, or something.

However, I've no idea what the platform support for this is like. You'll have to find out if it works for you.
> 1 votes

---
Tags: html5
---


# Question
Title: Possible to draw a select portion of a render target? (in XNA)
I'm going to try to do this in reverse fashion and skip straight to the punch line, and then give the back story afterward:

Is it possible to, after drawing a scene to a RenderTarget2D, only draw a select portion of the RenderTarget2D, if I don't want the entire thing?

I'm using xTile to manage world data in my game (it's a great piece of work, colinvella \[xTile's author\] has made an amazing product), and for the most part it works great. xTile supports parallax effects in its layers to add some wonderful depth to 2d scenes, which was great, until I implemented a dynamic split-screen system into my game. Wanted to make a co-op game that wouldn't require players to be in close proximity to each other, so I made it so that if the players separate too far apart, the singular full-screen viewport 'snaps-apart', and is replaced by two split-screen viewports, which then smoothly transition to their respective player targets. The effect is pretty smooth aside from the part where the parallax backgrounds become skewed once the viewports split, because xTile's ratio for handling parallax effects is dependent upon viewport size. This is unfortunate, because the effect would otherwise be really snazzy, but the backgrounds become pretty heavily affected when the game goes from single-viewport to multi-viewport. So, Colinvella suggests using rendertargets to record the scene at full viewport size, and then only drawing a portion of it. But as far as I can tell, that isn't even possible? That being said, I've never even used render targets before, so I'm still learning, hence the question here.

# Answer
> Is it possible to, after drawing a scene to a RenderTarget2D, only draw a select portion of the RenderTarget2D, if I don't want the entire thing?

I believe so.

This is mostly speculation (with a bit of logic thrown in) since I haven't tried any of this. However, `RenderTarget2D` inherits from `Texture2D`. That being said, if you only wanted to draw a portion of a particular render target, you should be able to cast the render target to a texture, then draw that texture with a sprite batch instance with a source rectangle parameter. Something like:

```
Texture2D texture = (Texture2D) myRenderTarget2D;
SpriteBatch.Draw( texture, destRect, sourceRect, Color.White );

```
> 0 votes

---
Tags: xna, 2d, xna-4.0, rendertargets
---


# Question
Title: Calculate the intersection depth between a rectangle and a right triangle
I'm working on a 2D platformer built in C#/XNA, and I'm having a lot of problems calculating the intersection depth between a standard rectangle (used for sprites) and a right triangle (used for sloping tiles). Ideally, the rectangle will collide with the solid edges of the triangle, and its bottom-center point will collide with the sloped edge.

I've been fighting with this for a couple of days now, and I can't make sense of it. So far, the method detects intersections (somewhat), but it reports wildly wrong depths. How does one properly calculate the depth? Is there something I'm missing?

# Answer
I think your first problem is that you haven't quite stated your objective precisely. How exactly is the rectangle supposed to collide with the triangle? What exactly do you want the method to return? The code you linked is actually only returning a single number (since the `X` of the returned `Vector2` is always 0). Your intention seems to be that this number be the distance that `_rectB` would need to move straight up in order to escape the triangle.

Per your request, I'm going to write it so that the method returns the `Vector2` the rectangle would need to move to escape the triangle, where interactions with the sloped edge are moved directly up (or down) enough to extract the midpoint of the bottom (or top) edge from the triangle without reference to the left or right edges. In effect the sloped edge treats the rectangle as though it is a vertical line segment. Note that this will give very strange behavior near the pointy corners of the triangle; to fix this you would want to make those corners interact with the rectangle as though it were actually the diamond formed by the midpoints of its edges. I'll leave that modification to you.

Also, you haven't described what the properties of your triangle object mean; `Left`, `Right`, `Top`, and `Bottom` are clear enough I suppose, but `Slope` and `B` aren't, and if they mean what I suspect, you have a lot of redundancy in the class which might be confusing you.

In your place I would define your `Triangle` blocks just like `Rectangles`, but with a couple of added flags to say which half of the `Rectangle` is real. Hereafter I'm going to write the section for when the bottom-right half of the rectangle is used. You should not have trouble mirroring the algorithm for other choices.

```
if (tri.UseBottom) {
    // check for collision with the bottom
    if (rect.Top > tri.Top && rect.Top < tri.Bottom &&
        rect.Left < tri.Right && tri.Left < rect.Right) {
        // rect top is inside triangle, shove it down
        return new Vector2(0, tri.Bottom - rect.Top);
    }
    if (tri.UseRight) {
        // check for collision with the sloped edge
        float rectMid = (rect.Left + rect.Right) / 2;
        if (rectMid > tri.Left && rectMid < tri.Right) {
            // check bottom against sloped edge
            float triHeightAtMid =
                triTop + ((tri.Right - rectMid) / (tri.Right - tri.Left)) *
                         (tri.Bottom - tri.Top);
            if (rect.Bottom > triHeightAtMid) {
                // midpoint of bottom inside triangle, shove it up
                return new Vector2(0, rectBottom - triHeightAtMid);
            }
            else {
                // midpoint of bottom above triangle, no collision
                return new Vector2(0, 0);
            }
        }
        // rect midline not inside triangle, check for collision with the right
        if (rect.Left > tri.Left && rect.Left < tri.Right &&
            rect.Top < tri.Bottom && tri.Top < rect.Bottom) {
            // rect left is inside triangle, shove it right
            return new Vector2(tri.Right - rect.Left, 0);
        }
        // checked all 3 edges, no collision
        return new Vector2(0, 0);
    }
    else {
        // ...
    }
}
else {
    // ...
}

```
> 1 votes

# Answer
Sounds like you're trying to implement sloped terrain? I tackled the same thing not long ago, and it's a real pain. Try not to think of the triangle as a 'right triangle'. Think of it as a box with a line passing through it. Once you've established that it's a line, then you can ask yourself, 'what's the slope of the line?'. Presumably in this case, it's probably 1/1 (1 rise over 1 run, being as typically a right triangle has a 45-degree slope). Then, the part you're probably missing is simple slope-intercept form:

y = mx + b (or in other parts of the world y = mx + c).

More simply put, DesiredLocationOfBottomOfRectangle = Slope(rise/run)\*GivenXValue(probably the center of the rectangle) + PointAtWhichLineIntersectsYAxis.

This will give you the location at which the corresponding y location would be with the provided x location. If specifically you are interested in knowing the depth of the intersection of your rectangle into the triangle, you could probably take the value returned from the equation, and subtract it from the current y coordinate of the intersecting edge of the rectangle.
> 1 votes

---
Tags: xna, collision-detection
---


title: Audio programming resources

text:
# Question
Title: Audio programming resources
I've been very interested in the last few months about getting in to audio programming (I'm from a musical background). I've been a .NET developer for two years and have also done some objective c for an iPhone app recently. I realise I would probably need to work on my C++ chops and have been having a play around with FMOD EX and doing a lot of research into the industry.

I was just wondering if anyone could suggest some good resources for audio programming (be they websites, podcasts, books, videos, online courses etc). Anything from Fourier analysis, low level coding, audio engine creation to audio APIs. I just want to learn as much as possible!

Thanks in advance.

# Answer
Most of the entries in the Game Programming Gems series of books have an entire section dedicated to audio programming. For an overview of some of the topics covered, check the following link:

http://www.aiwisdom.com/audio\_all.html

The list is not complete, as it lacks the entries in the 7th and 8th books, so cross check it with the complete table of contents provided by Zolomon in the comments:

http://zolomon.com/gpg/index.html

The Game Developer Magazine also has a monthly column on audio programming:

http://www.gdmag.com/
> 5 votes

# Answer
The Audio Programming Book by Richard Boulanger and Victor Lazzarini MIT press
> 3 votes

# Answer
There's a couple different areas for audio: DSP algorithms vs asset management and intelligent audio playback.

DSP is about filters and fourier transforms and HRTF and all that fun stuff.

Good DSP Resources:

* Rab already mentioned this, but it's so good I have to repeat it. The Audio Programming Book by Richard Boulanger and Victor Lazzarini is probably the best place to start. Also functions as a pretty thorough introduction to C. The beginning may be a little slow for you, but it discusses some (occasionally outdated, occasionally not, but always useful and interesting) C idioms as well as introduces some sound fundamental things about sound you may not have gotten before.
* musicdsp.org: An archive of algorithms, usually in C
* MUSIC-DSP mailing list at Columbia
* dspGuru Tutorials
* Who Is Fourier?: A really interesting book written to give you real fundamental understanding of the fourier transform. Written purely with the intention of exploring how to explain complex mathematical concepts to young students. As a result, if you're a little weak on your higher level math, this will help you grok everything.
* Digital Signal Processing Primer by Ken Steiglitz
* Since you've done Objective-C work, check out Apple's AudioUnit Programming guide

On the other side of things, "asset management" is a little vague and mostly has to do with dealing with container formats, codecs, and streaming. Perceptual codecs is the real meat to study here. Fortunately I don't have much to offer there (seems like you need a PhD to understand most of that stuff). But there's plenty of libraries/APIs for getting the job done:

Intelligent audio playback is other fun stuff. This isn't terribly mathy like DSP is, and what you end up doing a lot of the time is dealing with voice management and music cues. There's not as much specific technical knowledge, it's more about design, and creating the tools and playback systems to support that design.

> ...Brian Schmidt's immortal comment "Anyone who still thinks there's a 1:1 relationship between a sound and a WAV file just doesn't get it."

Download Wwise and just start reading their docs for both the authoring tools and the API. Do the same for FMOD Designer and FMOD Studio.These give you an idea of "upper tier" tools that game sound designers use to implement content.

Another good one to check out is Fabric. Basically, Unity's audio pipeline kinda sucks, and this plugin tries to make it better. You can get an evaluation version for free.

As a musician, imagine the ideal interface you want to describe interactive game music and sound effects with, that's what these tools aim to provide. If you're familiar with what's already out there and how it supports sound designers and composers, then you can start to think of your own solutions for how to do things better.

Other resources:

* Peter "pdx" Drescher wrote an awesome article about implementing the FMOD Designer API on Android with JNI.
* IASIG and iXMF, the as-yet-unfinished interactive music specification standard with some interesting ideas.
* Game Audio Relevance Assorted bits of game sound design and audio programming
* The Game Audio Tutorial A book aimed at teaching sound designers to implement sound in UDK while teaching game sound design principles. A lot of it is about fighting UDK's audio and Kismet, but once again it's useful to see things from the non-programmer side.
* http://www.procedural-audio.com/ \<- Self-explanatory link
> 3 votes

# Answer
Sure thing, as you mentioned API's I'm going to have to mention openAL and FMOD was already mentioned.

Here are some resources for OpenAL:

http://www.edenwaith.com/products/pige/tutorials/openal.php
http://enigma-dev.org/forums/index.php?topic=730.0

Some FMOD resources:

A quick guide to FMOD

http://www.gamesounddesign.com/forum/viewtopic.php?f=4&t=241 (I had this lying around and have not inspected the tutorials too much)

http://jerome.jouvie.free.fr/nativefmodex/tutorials/Tutorial03.php

Fast Fourier Transform:

http://www.fftw.org/
http://www.codeproject.com/Articles/9388/How-to-implement-the-FFT-algorithm
http://www.drdobbs.com/cpp/199500857

Also some general info about how Audio is represented:

Link

These are pretty much all the links i had lying around and some I had googled but I hope they at least help a little.
> 2 votes

# Answer
OpenAL has been mentioned - the other big library is XAudio 2 which you can use for x360 and pc development - although I believe OpenAL is supported on x360 as well it will undoubtedly be a layer over the top of XAudio 2
> 0 votes

---
Tags: c++, audio, sound
---


# Question
Title: Proper way to use a RenderTarget2D to draw multiple textures?
In the process of trying to resolve a split screen issue, I've been trying to use a RenderTarget2D to draw a portion of my scene to a Texture2D, and then again to another Texture2D, but the end result of both Texture2D's is coming out the same. Can anybody tell me what I'm doing wrong?

```
Texture2D camera1Render;
Texture2D camera2Render;

                GraphicsDevice.SetRenderTarget(RenderTarget);
                GraphicsDevice.Clear(Color.Transparent);

                map.Draw(mapDisplayDevice, Camera1, new Location(0, 0), false);

                camera1Render = RenderTarget;

                GraphicsDevice.Clear(Color.Transparent);

                map.Draw(mapDisplayDevice, Camera2, new Location(0, 0), false);

                camera2Render = RenderTarget;

                SetRenderTarget(null);

```

# Answer
> 3 votes
RenderTarget2D is a reference type and you seem to be treating it like a value type.

You have 2 references (camera1Render, camera2Render) to a reference type (RenderTarget) so the same object is referenced by all 3 variables, this is why the Texture2Ds are the same. Anyways since RenderTarget is a Texture2D so you can just do the following and simply use the RenderTarget as a Texture2D in a sprite batch or wherever you need.

```
RenderTarget2D camera1Render;
RenderTarget2D camera2Render;

GraphicsDevice.SetRenderTarget(camera1Render);
GraphicsDevice.Clear(Color.Transparent);
map.Draw(mapDisplayDevice, Camera1, new Location(0, 0), false);
SetRenderTarget(null);

GraphicsDevice.SetRenderTarget(camera2Render);
GraphicsDevice.Clear(Color.Transparent);
map.Draw(mapDisplayDevice, Camera2, new Location(0, 0), false);
SetRenderTarget(null);

```

---
Tags: xna, 2d, xna-4.0, rendertargets
---


title: two-part dice pool mechanic

text:
# Question
Title: two-part dice pool mechanic
I'm working on a dice mechanic/resolution system based on the Ghost/Echo (hereafter shortened to G/E) tabletop RPG. Specifically, since G/E can be a little harsh dealing with consequences and failure, I was hoping to soften the system and add a little more player control, as well as offer the chance to evolve player characters into something unique, right from creation. So, here's the mechanic: Players roll 2 separate d12 against each of the two statistics for their character (each is a number from 2-11, and may be rolled above or below depending on the nature of the action attempted, rolling your stat exactly always fails). Depending on the success for that roll, they add dice to the pool rolled for a modified G/E style action.

The acting player gets two dice anyhow, and I am debating offering a bonus die for each success, or a single bonus die for succeeding on both of the statistic-compared rolls.

Once the size of the dice pool is set, the entire pool is rolled, and the players are allowed to assign the rolled dice to a goal and a danger, one to each. Assigned results are judged as follows:

1-4 means the attempted goal fails, or the danger comes true.

5-8 is a partial success at the goal, or partially avoiding the danger.

9-12 means the goal is achieved, or the danger avoided.

My concerns are twofold:

Firstly, is the two-stage action too complicated, with two rolls to judge separately before anything can happen?

Secondly, are the statistics involved going too far in softening the game? I've run some basic simulations, and the approximate statistics follow:

```
                 2 dice     (up to) 3 dice      (up to) 4 dice
failure          ~33%            ~25%               ~20%

partial          ~33%            ~35%               ~35%

success          ~33%            ~40%               ~45%

```

I'd appreciate any advice that addresses my concerns or offers to refine my simulation (right now the first roll is statistically modeled as sign(1d12-1d12), where \>0 is a success).

# Answer
You mention 2d12, this would imply rolling 2 dice that have 12 sides each, I believe you really mean 2d6 which would be rolling 2 dice with 6 sides each, this would give you a value between 2 and 12 fitting into your rule setting better.

You also assume that rolling two dice will give you 33% chance of getting each number between 1 to 12, in fact you can't even get the number 1 (since neither dice can roll a 0).

To calculate the odds of something (the long way) you can draw the results onto a paper in a tree structure. Start with a dot in the middle of one of the sides of a paper, then draw 6 lines out from that, write the numbers 1 to 6 at the end of these lines. Now draw 6 lines from each number and write 1 to 6 at the end of these lines. You will now have a tree with a root to one side, and 36 leaves on the other side. Go from the root up to the leaves and add the numbers as you pass them by, this will give you 36 sums of all the possible rolls two dice can do. Now count the number of sums that are below 4 and write this down. Do the same for 5-8 and 9-12, the end result of this will be the following table:

```
Failure   6 16.7%
Partial  20 55.6%
Success  10 27.8%

```

Should you continue this tree for another dice roll you would get 216 sums and the following table:

```
Failure   4  1.9%
Partial  52 24.1%
Success 160 74.1%

```

As you can see, since your now rolling 3 dice you can only get 4 failures, this is because the lowest any of them can roll is 1 which sums up to 3, this only gives 2 failing rolls, all 1's or two 1's and a single 2. And since the highest values, added together, winds up being 18, which is 50% higher than your maximum for two rolls, you get a lot more successes compared to two rolls.

Needless to say, with 4 dice you can only fail by rolling four 1's (1 roll out of 1 296, or 0.07% chance).

I would suggest only using two dice rolls and instead add a fixed number to the roll, this way it won't cascade out of control.

```
Failure   2-5   27.8%
Partial   6-8   44.4%
Success   9-14  27.8%

```

By adding 1 to the dice rolls for each success from your stat system you would get the following chances:

```
          Dice    Dice+1  Dice+2
Failure   27.8%   16.7%    8.3%
Partial   44.4%   41.7%   33.3%
Success   27.8%   41.7%   58.3%

```

My suggestion is to map out your rolls very carefully using these probability trees so you know how your changes affect the outcome.
> 6 votes

---
Tags: game-design, game-mechanics, statistics
---


# Question
Title: Kinect joint coordinates and XNA animation
I have written a program to record the x,y,z coordinated of the Hand joint and I want to animate my models 2D or 3D according to these coordinates. . .However the output of the x,y,z coordinates are fluctuating from -0 to 1 but not more than that..

So i assume I will need to multiply them back with the screen width and height, however it still doesnt seem to animate according to the original x,y,z points

Any transformations I might be missing out?

```
        protected override void Update(GameTime gameTime)
        {

            position += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;

            //// TODO: Add your update logic here
            using (StreamReader r = new StreamReader(f))
            {
                string line;
                Viewport view = graphics.GraphicsDevice.Viewport;
                int maxWidth = view.Width;
                int maxHeight = view.Height;

            //    int i = 0;
                while ((line = r.ReadLine()) != null)
                {

                    string[] temp = line.Split(',');

                int x = (int) Math.Floor((float.Parse(temp[0]) * 0.5f) + 0.5f) maxWidth);
              int y = (int) Math.Floor((float.Parse(temp[1]) * -0.5f) + 0.5f) * maxHeight);

                    motion.Add(new Point(x, y));
            //        Console.WriteLine(temp[0] + "," + temp[1] + "," + motion[i].X+ "," + motion[i].Y);
            //        i++;

                }

            }

//            foreach (Point s in motion)
            {

                position.X = motion[i].X;
                position.Y = motion[i].Y;

            }

  //

            i++;

            a_butterfly_up.Update(gameTime);

            a_butterfly_side.Update(gameTime);

            G_vidPlayer.Play(mossV);

            base.Update(gameTime);
        }

```

# Answer
> 1 votes
It may be 0 most of the time, as you cast to int before you multiply (btw. your brackets are somehow messed up anyway). Maybe try this code instead:

```
   int x = (int) (float.Parse(temp[0])* maxWidth);
   int y = (int) (float.Parse(temp[1]) * maxHeight);

```

Regards!

EDIT:

Your code looks a bit messed up: At the beginning you use `position += spriteSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds;` which make not really sense to me as you overwrite position later on. I am not able to test much on my current machine, so I will give you a pseudo code snippet of how I would address this problem:

int your objects add: Vector2D position; Vector2D target;

```
public void Update(GameTime gameTime)
{
     if position!= target
        position+=target-position*gameTime*speed;
}

```

In the main loop do the following:

```
protected override void Update(GameTime gameTime)
{
    Get the target location from your stream
    Set the target of the desired object to the retrieved point
    Update every object
    base.Update(gameTime);
}

```

This is full pseudo code but might give you a headstart to implement the movement.

Regards!

# Answer
> 0 votes
This seems to work well for now . .however I dont understand the Why need to multiply or add 0.5f to the maxWidth or maxheight. . .

```
    using (StreamReader r = new StreamReader(f))
    {
        string line;
        Viewport view = graphics.GraphicsDevice.Viewport;
        int maxWidth = view.Width;
        int maxHeight = view.Height;

        while ((line = r.ReadLine()) != null)
        {

            string[] temp = line.Split(',');

            int x = (int) Math.Floor(((float.Parse(temp[0]) * 0.5f) + 0.5f) * maxWidth);
            int y = (int) Math.Floor(((float.Parse(temp[1]) * -0.5f) + 0.5f) *maxHeight);

          motion.Add(new Point(x, y));

        }

    }

        position.X = motion_2[i].X;
        position.Y = motion_2[i].Y;
        i++;

```

---
Tags: xna-4.0, kinect
---


# Question
Title: Game resource timers - general implementation
I'm interested in understanding how resource generation timers work on many of the mmorts type games out there. I can't wrap my head exactly around how the timers are synched with servers, especially with multiple users. If I need to provide more details, please let me know.

Thanks!

# Answer
> 12 votes
You mean games like Ogame? In my opinion it is best to calculate the value when it is needed, not on a regular event as Jari Komppa suggested. You could even go a step further and calculate the value on a client side sometimes.

In case of Ogame:

1. Imagine that server increases amount of resources every minute for millions of users (where probably half or more are inactive). It's an overkill.
2. Now imagine the server stores some value for every planet, named "last\_calc" with a timestamp value. Everytime someone attacks the planet, the server will:
    * get "last\_calc", mine levels and resources from database
    * calculate time\_delta = (current\_time - last\_calc)
    * calculate new resources: new\_deuter = deuter\_mine\_level * time\_delta; new\_metal = metal\_mine\_level * time\_delta;
    * (in case of Ogame in above point you would also need to check if a particular mine is upgraded during time\_delta, and if so, divide the time to two parts: one before mine upgrade, second after, then do the calculation as above with first part, increase mine\_level, do the calculation again, and sum up both values)
    * add new resources to old resources, divide them by 2, then save these value as both, current planet resources and attacker's loot.
    * (again, in Ogame it's a little more sophisticated - you need to check if attacker's fleet have enough capacity)
    * update last\_calc to current\_time
3. Now imagine a user is only spying on a planet. Such actions can occur much more often, then attacks, maybe even 100 times more often, so to keep things optimized, server will:
    * get last\_calc and old resources from database (or cache if we're talking about optimizing things)
    * send it to a client together with current server time
    * and now the client does the math! Keep in mind, that such solution gives hackers a possibility to see when spied user was last active (on this planet at least); of course a hacker will never know if last\_calc timestamp was updated by the planet owner or by another user sending spy drones, but if main planet of a user wasn't refreshed for 5 days, one can be pretty sure the user didn't login for at least as long.

# Answer
> 1 votes
First step: Time difference between hosts

It assumes that it takes same time for packet to go from server to client and back. server sends packet with current time to client and client responses back with current time. After that server has total time. Divide that time on two and you know when packet was on client.

```
// Server code
int64 dtime = time2 - time1;
int64 dtime2 = dtime / 2;
int64 clientTime = time1 + dtime2;

```

Second step: Keep track of time difference Keep track of time difference. You may calculate moving average for time difference.

```
float movingExpAvg(float value, float oldValue, float ftime, float time){
    float alpha = 1 - expf(-ftime/time);
    float r = alpha * value + (1.f - alpha) * oldValue;
    return r;
}

```

Every request from server to client that requires instant response may contain server time and response may contain client time.

---
Tags: timer, resource-management
---


title: Free AAA RTS engine SDK?

text:
# Question
Title: Free AAA RTS engine SDK?
I'm currently trying out the various free SDKs out there (Cryengine3, UDK, Source) however all of them are mainly designed for FPS games. I was wondering if there are other AAA 3D engine SDKs that are aimed towards RTS games?

# Answer
I believe what you are looking for is the Broodwar API (BWAPI). Although not an official SDK, it pretty much allows you to do anything in Starcraft: Brood War.

It even has a yearly competition supported by Blizzard.

PS If you decide to use it, don't forget to check out two very important extensions:
> 6 votes

# Answer
I myself have been researching for some short-cuts into RTS Game Programming and I found these:

I'm leaving these as a reference since I've not done any programming on them.
> 2 votes

# Answer
The simple fact is this: RTS games are not as popular as FPS games. And people, particularly people who make "free" stuff, tend to make what is popular (or what is easy, hence the thousands of Minecraft clones). That's what attracts multiple developers to a project, and multiple developers is pretty much the only way to make a "AAA" engine of any kind.

Because of that, you have to pretty much take what you can get with RTS game engines. The best are going to cost money, and you're not going to get anything even close to the quality of, say, the StarCraft II engine without paying for it.
> 1 votes

---
Tags: rts
---


# Question
Title: Where can I find a programmer/game developer to team up with?
I'm a pixel artist looking for an ametuer programmer/game developer to team up with, But I'm not sure where to start!

I'm not particularly worried about profit, I'm only interested in making the game as a hobby. Where can I find potential partners?

# Answer
> 7 votes
**Show What You Can Do**

When looking to start or join a team online, people are always interested in seeing what work you've produced beforehand. The work doesn't necessarily have to be done in a game, but it should showcase your ability to create game quality assets.

**Talk About What You Want To Do**

If you're looking to recruit people for a team, talk about the project you're wanting to work on. You don't have to have all the details fleshed out, but it is important that potential applicants understand the scale and scope of work you're wanting to accomplish. As an example, there is a big difference in the programming skill and amount of effort required to produce an Astroids clone and a Bullet Hell style game with online networking capabilities.

**Read and Follow The Rules**

A lot of communities that have job/recruitment boards have specific rules about posting in them. In many cases, they require you to fill out a template when posting, to help ensure you hit on all the major pitch points. Be sure to read the rules for each site before you post.

**Resources**

Here are links to a few communities you may find useful for recruiting game developer talent:

---
Tags: software-engineering, pixel
---


# Question
Title: Bullet Physics - Casting a ray straight down from a rigid body (first person camera)
I've implemented a first person camera using Bullet--it's a rigid body with a capsule shape. I've only been using Bullet for a few days and physics engines are new to me. I use `btRigidBody::setLinearVelocity()` to move it and it collides perfectly with the world. The only problem is the Y-value moves freely, which I temporarily solved by setting the Y-value of the translation vector to zero before the body is moved. This works for all cases except when falling from a height.

When the body drops off a tall object, you can still glide around since the translate vector's Y-value is being set to zero, until you stop moving and fall to the ground (the velocity is only set when moving). So to solve this I would like to try casting a ray down from the body to determine the Y-value of the world, and checking the difference between that value and the Y-value of the camera body, and disable or slow down movement if the difference is large enough.

I'm a bit stuck on simply casting a ray and determining the Y-value of the world where it struck. I've implemented this callback:

```
struct AllRayResultCallback : public btCollisionWorld::RayResultCallback{
    AllRayResultCallback(const btVector3& rayFromWorld, const btVector3& rayToWorld)
        : m_rayFromWorld(rayFromWorld), m_rayToWorld(rayToWorld), m_closestHitFraction(1.0){}

    btVector3   m_rayFromWorld;
    btVector3   m_rayToWorld;
    btVector3   m_hitNormalWorld;
    btVector3   m_hitPointWorld;
    float       m_closestHitFraction;

    virtual btScalar addSingleResult(btCollisionWorld::LocalRayResult& rayResult, bool normalInWorldSpace)
    {
        if(rayResult.m_hitFraction < m_closestHitFraction)
            m_closestHitFraction = rayResult.m_hitFraction;

        m_collisionObject = rayResult.m_collisionObject;
        if(normalInWorldSpace){
            m_hitNormalWorld = rayResult.m_hitNormalLocal;
        }
        else{
            m_hitNormalWorld = m_collisionObject->getWorldTransform().getBasis() * rayResult.m_hitNormalLocal;
        }

        m_hitPointWorld.setInterpolate3(m_rayFromWorld, m_rayToWorld, m_closestHitFraction);
        return 1.0f;
    }
};

```

And in the movement function, I have this code:

```
btVector3 from(pos.x, pos.y + 1000, pos.z); // pos is the camera's rigid body position
btVector3 to(pos.x, 0, pos.z); // not sure if 0 is correct for Y

AllRayResultCallback callback(from, to);
Base::getSingletonPtr()->m_btWorld->rayTest(from, to, callback);

```

So I have the `callback.m_hitPointWorld` vector, which seems to just show the position of the camera each frame. I've searched Google for examples of casting rays, as well as the Bullet documentation, and it's been hard to just find an example. An example is really all I need.

Or perhaps there is some method in Bullet to keep the rigid body on the ground?

I'm using Ogre3D as a rendering engine, and casting a ray down is quite straightforward with that, however I want to keep all the ray casting within Bullet for simplicity.

Could anyone point me in the right direction? Thanks.

# Answer
It turns out the solution is much simpler than the original attempt, and there's no need for subclassing if you're just testing one ray collision.

Here's all you must do to retrieve the collision vector:

```
btVector3 btFrom(camPos.x, camPos.y, camPos.z);
btVector3 btTo(camPos.x, -5000.0f, camPos.z);
btCollisionWorld::ClosestRayResultCallback res(btFrom, btTo);

Base::getSingletonPtr()->m_btWorld->rayTest(btFrom, btTo, res); // m_btWorld is btDiscreteDynamicsWorld

if(res.hasHit()){
    printf("Collision at: <%.2f, %.2f, %.2f>\n", res.m_hitPointWorld.getX(), res.m_hitPointWorld.getY(), res.m_hitPointWorld.getZ());
}

```
> 11 votes

---
Tags: c++, ogre, bullet-physics
---


# Question
Title: How do I apply skeletal animation from a .x (Direct X) file?
Using the .x format to export a model from Blender, I can load a mesh, armature and animation. I have no problems generating the mesh and viewing models in game. Additionally, I have animations and the armature properly loaded into appropriate data structures.

My problem is properly applying the animation to the models. I have the framework for applying the models and the code for selecting animations and stepping through frames.

From what I understand, the `AnimationKey`s inside the `AnimationSet` supplies the transformations to transform the bind pose to the pose in the animated frame. As small example:

```
Animation {
  {Armature_001_Bone}
  AnimationKey {
    2; //Position
    121; //number of frames
    0;3;     0.000000, 0.000000, 0.000000;;,
    1;3;     0.000000, 0.000000, 0.005524;;,
    2;3;     0.000000, 0.000000, 0.022217;;,
    ...
  }
  AnimationKey {
    0; //Quaternion Rotation
    121;
    0;4;   -0.707107, 0.707107, 0.000000, 0.000000;;,
    1;4;   -0.697332, 0.697332, 0.015710, 0.015710;;,
    2;4;   -0.684805, 0.684805, 0.035442, 0.035442;;,
    ...
  }
  AnimationKey {
    1; //Scale
    121;
    0;3;     1.000000, 1.000000, 1.000000;;,
    1;3;     1.000000, 1.000000, 1.000000;;,
    2;3;     1.000000, 1.000000, 1.000000;;,
    ...
  }
}

```

So, to apply frame 2, I would take the position, rotation and scale from frame 2, create a transformation matrix (call it `Transform_A`) from them and apply that matrix the vertices controlled by `Armature_001_Bone` at their weights. So I'd stuff `TransformA` into my shader and transform the vertex. Something like:

```
vertexPos = vertexPos * bones[ int(bfs_BoneIndices.x) ] * bfs_BoneWeights.x;

```

Where `bfs_BoneIndices` and `bfs_BoneWeights` are values specific to the current vertex.

When loading in the mesh vertices, I transform them by the `rootTransform` and the `meshTransform`. This ensures they're oriented and scaled correctly for viewing the bind pose.

The problem is when I create that transformation matrix (using the position, rotation and scale from the animation), it doesn't properly transform the vertex. There's likely more to it than just using the animation data. I also tried applying the bone transform hierarchies, still no dice. Basically I end up with some twisted models. It should also be noted that I'm working in openGL, so any matrix transposes that might need to be applied should be considered.

**What data do I need and how do I combine it for applying .x animations to models?**

I've made some mock ups of what this looks like, in case that's useful.

First I wanted to just test the translation, this is a bobbing head, what it looks like in Blender:

https://i.stack.imgur.com/NAc4B.gif

And what it looks like in game (don't mind the colors):

https://i.stack.imgur.com/nj2du.gif

Then for just rotation, the animation was the head rotating 360 degrees around the vertical axis. This is what that looks like in game:

https://i.stack.imgur.com/gVyUW.gif

Note, there should be no tilt, only rotation like a merry-go-round.

**Update**

I have the translation part of the animation working. But it feels kind of hacky and I don't see how to apply it to the rotation.

The translation works by taking these steps:

1. Take the position from the animation frame and swap the `y` and `z` values
2. Translate the transformation matrix by the altered position
3. Transpose the transformation matrix
4. Apply the transformation matrix to the vertices

So that's how it *can* work, but how is it supposed to work generally for position, scale and rotation?

# Answer
OK, I put some more time toward this and got it working for multiple bones, and considerably less hack-like (though still a little). The system I had in place originally was almost correct. However, the main problems were:

1. Blender saves Quaternions in **W, X, Y, Z** format. I was loading them *X, Y, Z, W*.
2. My code for converting a Quaternion to a matrix was incorrect. I'm actually still not sure why this is incorrect, but I know the following code works, as part of my Quaternion class:

```
public Matrix4f toMatrix() {
    Matrix4f tmpMatrix = new Matrix4f();
    if (this.length() > 0)
        this.normalise();

    float xx = this.x * this.x;
    float xy = this.x * this.y;
    float xz = this.x * this.z;
    float wx = this.x * this.w;

    float yy = this.y * this.y;
    float yz = this.y * this.z;
    float wy = this.y * this.w;

    float zz = this.z * this.z;
    float wz = this.z * this.w;
    //note the "* -1"s
    //I needed those to make the same matrices Blender was expecting
    tmpMatrix.m00 = (1.0f - 2.0f * (yy + zz)) * -1;
    tmpMatrix.m01 = (       2.0f * (xy - wz)) * -1;
    tmpMatrix.m02 =        2.0f * (xz + wy);
    tmpMatrix.m03 = 0;

    tmpMatrix.m10 =        2.0f * (xy + wz);
    tmpMatrix.m11 = 1.0f - 2.0f * (xx + zz);
    tmpMatrix.m12 = (       2.0f * (yz - wx)) * -1;
    tmpMatrix.m13 = 0;

    tmpMatrix.m20 =        2.0f * (xz - wy);
    tmpMatrix.m21 =        2.0f * (yz + wx);
    tmpMatrix.m22 = (1.0f - 2.0f * (xx + yy)) * -1;
    tmpMatrix.m23 = 0;
    return tmpMatrix;
}

```

Other than that, it's just:

`finalMatrix = boneMatrix * skinMatrix * invertedBindMatrix;`

Note that the `boneMatrix` should be using the animated matrices for each bone instead of the bind matrices. It should also get all it's parent matrices like so:

```
private Matrix4f getBoneMatrix() {
        if (parent == null) {
            return Matrix4f.mul(Matrix4f.mul(parentArmature.getBindMatrix(), parentArmature.getArmatureRootMatrix(), null), boneMatrix, null);
        } else {
            return Matrix4f.mul(parent.getBoneMatrix(), boneMatrix, null);
        }
    }

```

And it works. Leave a comment if you need clarification.
> 2 votes

# Answer
> It should also be noted that I'm working in openGL, so any matrix transposes that might need to be applied should be considered.

Maybe that's the key, have you tried negating some Z-coordinates around to convert from DirectX left-handed coordinates to OpenGL right-handed ones?

You could negate all Zs before applying your transformations, and re-negate when done, see if the output gets any better.

**EDIT**

Swapping the Y and Z-coordinates is another way to change handedness. So you do have to adapt your transformations, check this paper for details.

The fact that you have to transpose you matrix also means you going from row-major to column-major or the other way around. This should be less complicated to handle, you'll probably just have to find the right "place" to do it in your pipeline. I'm just guessing, but doing it on quaternions could simply means changing them to matrices, transpose, and go back quaternions, if your Math lib offers your this option.
> 3 votes

---
Tags: opengl, animation, blender, skeletal-animation
---


title: Unable to access jar. Why?

text:
# Question
Title: Unable to access jar. Why?
I was making a game in java and exported it as jar file. Then after that, I opeed jar splice. I added the libaries and exported jar. I added the natives then i made a main class. I created a fat jar and put it on my desktop. I'm using Mac OS X 10.8 Mountain Lion. When I put in the terminal, java -jar System Front.jar it says unable to access System Front.jar Even if i double click on the file, it doesen't show up! Help! I'm using slick.

I added slick and lwjgl as libraries for the jar splice at the jars.

# Answer
I'm afraid I don't know the specifics about "jar splice", but since its likely the problem is highly localized Ill give some general tips for how to troubleshoot this.

Jar files use Zip compression, try opening the file in a zip extractor, if that fails then its no longer in the correct format. If it works however, run a CRC check on the jar file, and look to see that the structure seems correct.

Most likely the jar file is now incorrect and you need to go back to your original jar file, and step by step redo the process, rereading the documentation for the steps to make sure you didn't misread something the first time around.

If the jar file is correct however, then make sure there isn't a simple misspelling issue, perhaps you altered the name from "System Front.jar" to "Systme Front.jar" and since you already know what its called your reading the name too fast and fail to spot the spelling mistake. But a command line would simply fail at this simple mistake.

Also check that your working directory is correct by opening a command prompt and listing the files to make sure your in the correct directory.

Bottom line is, if it should be working but isn't. Then its most likely something wrong that you think is correct. And the simpler it is to get it right, the less likely you are to actually look carefully at if it is right.
> 1 votes

# Answer
When using

```
java -jar

```

you need to give the full qualified name of the class you want to execute. That is, if you want to run class a.b.c.System you have to type:

```
java -jar a.b.c.System Front.jar

```

Also, you may have to specify the class path using the -cp parameter, a "-cp ." might help. If you want to make an executable jar, you need to include a Manifest file in said jar. It needs to have a property like "mainClass" or so. I can't remember it right now, as I always let my build system create a Manifest vor me ;)

Also I'm a bit confused with your build order: You create your game, export it, add external libraries to it and then you create your main class? Doesn't your game have a main class?
> 0 votes

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


# Question
Title: Bejeweled-like game, managing different gem/powerup behaviors?
In general, what I am asking is, given any game where a game element can look/behave/affect-other-elements one way under one set of conditions, and look/behave/affect-other-elements a different way under another, and there are many such conditions, what is the best approach to developing this flexibility into the core? (with one aim being to keep the game "fresh" by introducing variation on the game-play during the life of a game...)

Specifically, In a Match 3 game, a valid move involves swapping a pair of adjacent tiles so that three-identical-tiles in a row are formed. The identical tiles are removed from the grid and replaced by those above them. New spaces (on top) on the grid are now filled with new tiles. This is the standard behavior. Richer Match-3 games, such as Bejweled, offer modified behavior based on the same mechanic when a player matches 4 tiles-in-row resulting in retention of the one tile that was swapped, and triggering alternative animations, sounds, scoring, etc. And yet still, 5-in-a-row, and cross-patterns, "power-up" tiles behave in very different ways and affect neighboring tiles in alternative ways as well.

ANY pointers for good practices here would be highly appreciated.

# Answer
You could make a two-dimensional grid made of Array of IElement type. I imagine String or int would be enough for an element's name/id (e.g. "Diamond" or "Chest"), but your request for the game being easily upgradeable implies elements may have some state or even a functionality.

The IElement would be an interface with following methods:

```
1. canSwap ( swapWith:IElement ):Boolean
2. isHeavy ():Boolean
3. onActivate ():Array
3. onExplode ( power:int ):Array

```

**Ad 1.** Can a chest change places with a stone, or for some reason not? For example in some game type you could mark some elements as heavy (e.g. a heavy chest) and make a rule that two heavy items can't be swapped.

**Ad 3.** This method will be fired when a user selects the element as first. The method update's element's state (if needed) and returns an Array of actions to be done outside of the element, e.g. \[RemoveFromGridAction, ExplodeAction\] for a BombElement

**Ad 4.** As above, but here the method will be used when the element is a neighbour of an exploding bomb. A WoodenBoxElement would return \[RemoveFromGridAction\] Array, a BombElement would return \[RemoveFromGridAction, ExplodeAction\], and a MetalCubeElement would return \[\] (an empty Array).

All of this enforce on you, to make either various versions of Classes implementing IElement interface, or put there an additional method for every new game mechanic you add.

---

If you want to make a Bejeweled-like game with dozens or more of rule variations, then that would become a huge project and I suggest a MVC pattern:

**Model** \- the grid of dictionaries (or dynamic objects, or associative arrays). These dictionaries are simply value objects that store any data you want, e.g. {'type':'diamond', 'x':0, 'y':5, 'heavy':true, 'explode\_radius': 1, 'bonus':true, 'value': 115, 'lifetime\_in\_turns': '5' }

**View** \- components responsible for drawing the Elements, animating the process of swapping them, new elements falling down etc.

**Controller** \- Various commands responsible for almost everything:

* ChangeContextCommand - this command receives an event with a ruleset, unregisters current commands and registers commands responsible for a new ruleset chosen by a user.
* ActivateCommand - this command receives an event with X and Y coordinates, gets data from Model for these coordinates, and decides what to do next. Actionscript 3 + Robotlegs example

```
public class ActivateElementCommand extends Command {
private const MAX_HUMIDITY_TO_EXPLODE:int = 3;

[Inject]
public var e:ElementActionEvent;

[Inject]
public var grid:GridProxy;

override public function execute ():void
{
    var x:int = e.x;
    var y:int = e.y;
    var element:Object = grid.getElement ( x, y );
    if ( element.explode_radius ) {
        // it's gonna blow!
        var neighbours:Vector.<Object> = grid.getElementsSurrounding ( x, y );
        var humidity:int = 0;
        for ( var i:int = 0; i < neighbours.length; i++ ) {
            if ( neighbours[i].type == TypeConstants.WATER ) humidity += 1;
        }
        if ( humidy > MAX_HUMIDITY_TO_EXPLODE ) return; // can't fire up the match!

        grid.removeElement ( x, y );
        neighbours = grid.getElementsSurrounding ( x, y, element.explode_radius );
        for ( var i:int = 0; i < neighbours.length; i++ ) {
            el:Object = neighbours[i];
            dispatch ( new ExplodeEvent(el.x, el.y, x, y, element.explode_radius) );
        }
    }
}
}

```
* ExplodeCommand - receives an event with X and Y coordinates of element being currently processed, as well as X and Y coordinates of element that blew up and it's explosion\_range to be able to calculate the fire\_power on the element (if needed). The fire\_power could decrease humidity for example.

as You can see, you can easily create different ActionCommands for different rulesets. and then register the appropriate commands when game mode is changed. You could also not register an ActionCommand at all, if you don't want elements to do anything when clicked, in some particular ruleset.
> 1 votes

# Answer
This is likely to depend on the tools you are using (as well as your preferences in code design). A more procedural approach might organize calls to functions that describe the different power-up effects in a switch or set of nested if-else statements. A more object oriented approach might involve a base tile class with an empty virtual method called something like powerUp(). Then child classes for specific kinds of tiles can override this method to describe their specific ability. Finally, the option I tend to favor is a bit more functional in nature. Your tile class could contain a lambda, delegate, function pointer that describe how the tile behaves when cleared.

Hope these suggestions help stimulate some ideas for you. It really comes down to a matter of personal preference beyond any tool/engine architectural conventions or limitations.
> 0 votes

---
Tags: animation, component-based, behavior
---


# Question
Title: How to handle wildly varying rendering hardware / getting baseline
I've recently started with mobile programming (cross-platform, also with desktop) and am encountering wildly differing hardware performance, in particular with OpenGL and the GPU. I know I'll basically have to adjust my rendering code but I'm uncertain of how to detect performance and what reasonable default settings are.

I notice that certain shader functions are basically free in a desktop implemenation but can be unusable in a mobile device. The problem is I have no way of knowing what features will cause what performance issues on all the devices. So my first issue is that even if I allow configuring options I'm uncertain of which options I have to make configurable. I'm wondering also wheher one just writes one very configurable pipeline, or whether I should have 2 distinct options (high/low).

I'm also unsure of where to set the default. If I set to the poorest performer the graphics will be so minimal that any user with a modern device would dismiss the game. If I set them even at some moderate point, the low end devices will basically become a slide-show. I was thinking perhaps that I just run some benchmarks when the user first installs and randomly guess what works, but I've not see a game do this before.

# Answer
Depending on what you're aiming for, you have several options.

Best quality on every device? Make a separate version, optimized by hand for every single device separately.

Least amount of work? Find the crappiest device you want to support, develop for that, and port that around.

There's no magic way to detect the performance, but you can investigate the characteristics of various devices; how many pixel/texel pipes, how many shader cores, and so on. You'll find that while the desktop hardware has ludicrous amounts of shader cores and texel/pixel bandwidth, the mobile devices are genrally very, very constricted (some have as few as *one* shader core =)

EDIT: that said, there's some stuff you can do, like quality settings, and benchmarks, but don't expect desktop content to run on a phone (not yet, at least..)
> 6 votes

# Answer
I've done this professionally. For about a year, I was the guy responsible for managing rendering performance for a single "AAA" 3D game across almost the complete line of iOS devices.

I want to stress this: for the duration of the development of the game, this was exactly all of my job. I did this 8-10 hours per day, five days a week, for a year. I wasn't implementing the game (apart from some shaders); I was only maintaining and tuning rendering performance across a broad set of devices.

This is my way of saying: it's not easy. It takes a serious investment of time to really maintain compatibility across a wide range of devices.

The way that I did it was to build a series of in-game graphic testbeds. Things like level flythroughs, animation tests, and so on. These tests would run, and the devices would log out statistics about how long things took to render, how long they took to process, etc. I'd run these tests on about six different devices every day, as development continued. And then I'd graph these blobs of data, so I could compare how long something took to render on an iPhone3 vs. an iPhone 3GS vs. an iPhone4 vs. an iPhone4S, and I'd have to figure out how to make the iPhone4 run as fast as the 3GS, and how to boost the speed of the 3, and so on. I did research to figure out exactly what operations were slow on each device, so that I could make custom rendering changes for each model.

Often this meant using different shaders. Or disabling shaders entirely. Or tuning the far clip distance or being more or less aggressive in occlusion testing or anything else I could think of to boost performance on the slower devices. And after every change, I'd run the suite of tests again, to see if the change I'd made had actually had the effect I expected it to. It was a slow, laborious process, and required a lot of attention to avoid making mistakes and making things worse.

Incidentally, the other developers loved these graphs; they immediately showed on which days somebody had done something that hurt performance, which meant that we didn't have the usual last-minute crunching to find performance, since we (mostly) caught everything within a day or so of it going in.

In terms of pipeline, I used two separate pipelines; one which used shaders, and one which used the fixed-function pipeline. I'm not sure if I recommend that these days, but it's what I did. (The fixed-function pipeline, in my case, was legacy code which already existed. The shader pipeline was new. I don't think I'd bother writing a fixed-function pipeline from scratch, today, unless I really needed to support something that didn't have shader support.)

The device-specific changes were all placed in game code and in data files, not in the pipeline (so an iPhone4 would load a simpler shader than an iPhone4S would, for example, and an iPhone3 would move to lower LODs at a closer distance, etc), but they'd all be rendering through either the shader pipeline or the fixed-function pipeline, neither of which cared about the particular device they were running on.
> 3 votes

# Answer
You've pretty much identified the reason why - for most people in your position - aiming to support all hardware and all platforms is not a realistic objective. It's a noble objective, it's commendable, but - unless you have the time and resources and are willing to make sacrifices - not realistic.

If you've just started mobile development then I'd suggest that you have *way more important things* to be spending your time doing, and trying to get reasonable performance and good quality while dealing with all the quirks of each platform is just going to suck that precious time away from you.

So I'd advise to pick a single platform for the first project, focus on that, and learn mobile development on that platform. Much of what you learn will be easily transferrable to other platforms at a later date, but - crucially - you won't need to deal with the headache of supporting multiple platforms while you're learning.

Once you have that down you can look to adding support for other platforms if you want, but view it as a value-added bonus rather than a core requirement. At this stage. Future projects can be more ambitious, but for that first project your objective is to learn, not to be all things to all people.
> 1 votes

---
Tags: opengl, opengl-es
---


title: Resource not found?

text:
# Question
Title: Resource not found?
When I write in my terminal, `java -jar myJar.jar`, it gives me an error "Resource Not found res/playNow.png" When I run it in eclipse, it does not give me any errors about this image.

My folder in my eclipse is outside my package called res and inside it are images.

This is the full error

```
Exception in thread "main" java.lang.RuntimeException: Resource not found: res/playNow.png
    at org.newdawn.slick.util.ResourceLoader.getResourceAsStream(ResourceLoader.java:69)
    at org.newdawn.slick.opengl.InternalTextureLoader.getTexture(InternalTextureLoader.java:169)
    at org.newdawn.slick.Image.<init>(Image.java:196)
    at org.newdawn.slick.Image.<init>(Image.java:170)
    at org.newdawn.slick.Image.<init>(Image.java:158)
    at org.newdawn.slick.Image.<init>(Image.java:136)
    at javagame.Menu.init(Menu.java:31)
    at javagame.Game.initStatesList(Game.java:21)
    at org.newdawn.slick.state.StateBasedGame.init(StateBasedGame.java:164)
    at org.newdawn.slick.AppGameContainer.setup(AppGameContainer.java:390)
    at org.newdawn.slick.AppGameContainer.start(AppGameContainer.java:314)
    at javagame.Game.main(Game.java:32)

```

I'm using a terminal in my mac. How do I fix the error Resource Not Found? I'm using slick2d!

# Answer
Your resource folder has to be in the classpath. Just copy this folder in the folder holding the jar file and it should work. When you run your project in eclispe, the IDE already has settings that make it works. If you run the plain command `java -jar myjar.jar` java does not know where to look for your resources so it will look into the default classpath ("." e.g the current directory, that's why putting your resources on the same directory as your jar file would work). You can add parameters to the command line to change behaviors, change classpath etc. see the manual.

Also you can read this: http://docs.oracle.com/javase/tutorial/essential/environment/paths.html
> 1 votes

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


title: Isometric Screen View to World View

text:
# Question
Title: Isometric Screen View to World View
I am having trouble working out the math to transform the screen coordinates to the Grid coordinates.

The code below is how far I have got but it is totally wrong any help or resources to fix this issue would be great, had a complete mind block with this for some reason.

```
    private Point ScreenToIso(int mouseX, int mouseY)
    {
        int offsetX = WorldBuilder.STARTX;
        int offsetY = WorldBuilder.STARTY;

        Vector2 startV = new Vector2(offsetX, offsetY);

        int mapX = offsetX - mouseX;
        int mapY = offsetY - mouseY + (WorldBuilder.tileHeight / 2);

        mapY = -1 * (mapY / WorldBuilder.tileHeight);
        mapX = (mapX / WorldBuilder.tileHeight) + mapY;

        return new Point(mapX, mapY);
    }

```

# Answer
> 5 votes
As a side-note, these coordinates make more sense if you interpret them as (Y, X).

You can define a 'vertical line' (from bottom to right) as y = -0.5x + a And you can define a 'horizontal line' (from top to right) as y = 0.5x + b What you need is an algorithm to calculate A. You can obtain it from a grid drawing function - if you draw a line every 50 pixels, the a is 0 for first (border) line, 50 for second line, 100 for third line and so on. Now when you get a mouse coordinates, all you need is to find such a that the equation is true.

```
y = -0.5x + a
mouse coordinates: 403, -12
-12 = -0.5*403 + a
-12 = -201.5 + a
a = -12+201.5
a = 189.5

y = 0.5x + b
-12 = 0.5*403 + b
b = -12 - 201.5
b = -213.5

```

a is a value added to 'vertical lines', that is it's an equivalent of X on the tile. b is equivalent for Y.

by using modulo operator %, we can calculate cursor at this position is above tile (4, -5), though I could make a mistake somewhere. if You make a screenshot and show the grid drawing code I'll be able to post an accurate code.

---
Tags: isometric, coordinates, tilemap
---


title: Xna model parts are overlying others

text:
# Question
Title: Xna model parts are overlying others
I am trying to import in XNA an .fbx model exported with blender.

Here is my drawing code

```
public void Draw()
{
    Matrix[] modelTransforms = new Matrix[Model.Bones.Count];
    Model.CopyAbsoluteBoneTransformsTo(modelTransforms);

    foreach (ModelMesh mesh in Model.Meshes)
    {
        foreach (BasicEffect be in mesh.Effects)
        {
            be.EnableDefaultLighting();
            be.World = modelTransforms[mesh.ParentBone.Index] * GameCamera.World * Translation;
            be.View = GameCamera.View;
            be.Projection = GameCamera.Projection;
        }
        mesh.Draw();
    }
}

```

The problem is that when I start the game some model parts are overlying others instead of being behind. I've tried to download other models from internet but they have the same problem.

# Answer
Your device states are probably wrong. This often happens when mixing 2D and 3D (for example the overload for SpriteBatch.Begin() which takes no arguments sets some device states that are incompatible with 3D rendering. No worries though, all you have to do is to make sure that the following device states are set the way you want them:

```
BlendState, SamplerState, DepthStencilState, RasterizerState

```

The default values, which should be fine for just rendering a model are:

```
GraphicsDevice.BlendState = BlendState.Opaque;
GraphicsDevice.DepthStencilState = DepthStencilState.Default;
GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
GraphicsDevice.SamplerStates[0] = SamplerState.LinearWrap;

```

Especially take a look at DepthStencilState it should be set to DepthStencilState.Default and at the moment is probably set to DepthStencilState.None.

To learn more about graphics device states take a look at this series of "What is" articles on MSDN. To learn more about why this is managed in such a way you should read this article by Shawn Hargreaves (used to be on the XNA team and his blog posts are all brilliant)
> 3 votes

---
Tags: c#, xna-4.0, blender, fbx
---