title: LWJGL Adding Textures with VBOs

text:
# Question
Title: LWJGL Adding Textures with VBOs
I'm currently trying to texture a cube, but I am having no luck determining what the next step should be. I can load an .obj model from Blender into my LWJGL program just fine, and I can even make a an image appear from the information. However, I don't know how to use the extra data for textures (or even the normal information). Any help would be greatly appreciated.

This is my OBJLoader:

```
//Loads .obj files (created from Blender)
public static Model2 loadOBJModel(String name){
    Model2 m = new Model2();
    Material material = null;

    String [] lines = Utilities.readAllLines(name);
    String[] values;
    for(String line : lines){
        values = line.split(" ");
        if(values[0].equals("v")){
            //Adds a new vertex position
            m.getVertices().add(new Vector3f(Float.parseFloat(values[1]),
                                             Float.parseFloat(values[2]),
                                             Float.parseFloat(values[3])));
        }
        else if(values[0].equals("vn")){
            //Adds a new normal Vector
            m.getNormals().add(new Vector3f(Float.parseFloat(values[1]),
                                            Float.parseFloat(values[2]),
                                            Float.parseFloat(values[3])));
        }
        else if(values[0].equals("vt")){
            //Adds a new Texture Coordinate
            m.getTexCoords().add(new Vector2f(Float.parseFloat(values[1]),
                                              Float.parseFloat(values[2])));
            m.setIsTextured(true);
        }
        else if(values[0].equals("f")){
            //Adds the Index of the vertex
            int[] vertexIndice = new int[]{Integer.parseInt(values[1].split("/")[0]) - 1,
                                           Integer.parseInt(values[2].split("/")[0]) - 1,
                                           Integer.parseInt(values[3].split("/")[0]) - 1};
            //Adds the Index of the normal
            int[] normalIndice = new int[]{Integer.parseInt(values[1].split("/")[2]) - 1,
                                           Integer.parseInt(values[2].split("/")[2]) - 1,
                                           Integer.parseInt(values[3].split("/")[2]) - 1};
            if(m.getIsTextured()){
                //Adds the Index of the Texture Coordinates
                int[] texIndice = new int[]{Integer.parseInt(values[1].split("/")[1]) - 1,
                                            Integer.parseInt(values[2].split("/")[1]) - 1,
                                            Integer.parseInt(values[3].split("/")[1]) - 1};
                m.getIndices().add(new Face(vertexIndice, normalIndice, texIndice, material));
            }
            else{
                m.getIndices().add(new Face(vertexIndice, normalIndice, null, material));
            }
        }
        else if(values[0].equals("mtllib")){
            //Loads the material
            parseMaterial(m, Utilities.getFileInSameLevelOf(name, line.replaceAll("mtllib ",  "").trim()));
        }
        else if(values[0].equals("usemtl")){
            //Sets the material
            material = m.getMaterials().get(line.replaceAll("usemtl ", "").trim());
        }
    }

    m.prepareVBO();

    return m;
}

```

This is where I get lost... the prepareVBO method

```
private void prepareVBO(){
    //vertices holds the locations of all the vertices for the object
    Vector3f[] vertexData = new Vector3f[vertices.size()];
    vertices.toArray(vertexData);

    //normals holds the values of all the normal vectors at each vertex
    Vector3f[] normalData = new Vector3f[normals.size()];
    normals.toArray(normalData);

    //texCoords holds the values of all the texture Coordinates
    Vector2f[] texData = new Vector2f[texCoords.size()];
    texCoords.toArray(texData);

    //this section loads each vertex's/normal's/texCoord's index location
    int[] indexVertexData = new int[indices.size() * 3];
    int[] indexNormalData = new int[indices.size() * 3];
    int[] indexTexData = new int[indices.size() * 3];

    int count = 0;
    for (Face face : indices) {
        indexVertexData[count++] = face.getVertexIndice()[0];
        indexVertexData[count++] = face.getVertexIndice()[1];
        indexVertexData[count++] = face.getVertexIndice()[2];
        count -= 3;
        indexNormalData[count++] = face.getNormalIndice()[0];
        indexNormalData[count++] = face.getNormalIndice()[1];
        indexNormalData[count++] = face.getNormalIndice()[2];
        if(isTextured){
            count -= 3;
            indexTexData[count++] = face.getTexIndice()[0];
            indexTexData[count++] = face.getTexIndice()[1];
            indexTexData[count++] = face.getTexIndice()[2];
        }
    }

    //This is what I do for not using textures nor the normals... I don't know how to utilize the new data
    vboHandler = glGenBuffers();
    iboHandler = glGenBuffers();
    glBindBuffer(GL_ARRAY_BUFFER, vboHandler);
    glBufferData(GL_ARRAY_BUFFER, Utilities.createFlippedBuffer(vertexData), GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboHandler);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, Utilities.createFlippedBuffer(indexVertexData), GL_STATIC_DRAW);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

}

```

Finally, I draw with this:

```
public void draw(){
    glPushMatrix();
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, vboHandler);
    glVertexAttribPointer(0, 3, GL_FLOAT, false, 3*4, 0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iboHandler);
    glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_INT, 0);

    glDisableVertexAttribArray(0);
    glPopMatrix();
}

```

# Answer
> 0 votes
You are on the right track, but there is one problem in the provided code. You have separate indices for positions, normals and texture coordinates. In OpenGL there are only one list of indices, which are used for all vertex attributes. That means that when you are reading the normal and texture coordinate indices, you just need to ignore them or assert that they match the position indices. If they don't match, the vertex data is not compatible with OpenGL and would need reconstruction.

Then how to use these attributes:

> ```
> vboHandler = glGenBuffers();
> glBindBuffer(GL_ARRAY_BUFFER, vboHandler);
> glBufferData(GL_ARRAY_BUFFER, Utilities.createFlippedBuffer(vertexData), GL_STATIC_DRAW);
> glBindBuffer(GL_ARRAY_BUFFER, 0);
>
> ```

The code above specifies the position vertex attributes. I recommend to rename vertexData to positionData and vboHandler to vboPositions. Then just duplicate this code for normals and texture coordinates.

> ```
> glEnableVertexAttribArray(0);
>
> glBindBuffer(GL_ARRAY_BUFFER, vboHandler);
> glVertexAttribPointer(0, 3, GL_FLOAT, false, 3*4, 0);
>
> ```

This code sets up the rendering using vertex positions a the attribute with index 0. You can also duplicate that for the normals and texture coordinates, e.g.

> ```
> glEnableVertexAttribArray(1); // Index 1
>
> glBindBuffer(GL_ARRAY_BUFFER, vboNormals);
> glVertexAttribPointer(1, 3, GL_FLOAT, false, 3*4, 0); // Here also index 1
>
> ```

Finally you need to map the vertex attribute indices to the names in the shader code. There are multiple ways for doing that. You can specify them with glBindAttribLocation from the code, use Layout Qualifiers in the vertex shader or let OpenGL allocate them and use glGetAttribLocation to query the indices.

---
Tags: opengl, textures, lwjgl, vbo
---


# Question
Title: Why translation uses multiplication and not addition?
To translate an object from `(x, y, z)` to `(a + x, b + y, c + z)` it's done using:

OK, that's cool, but why would we multiply in the first place when we can add the two matrices directly as:

addition is faster and more effective, plus it's straightforward?

# Answer
> 6 votes
because it allows to combine rotation and translation into a single matrix. Multiplying those matrices together gives use the concatenated operation. We can rotation around an arbitrary point `P` by first translating to -P then rotating and then translating by P.

multiplying these matrices together gives us a single matrix we can apply blindly without having to worry about knowing when to add a vector and when to multiply with a matrix

# Answer
> 4 votes
You can store ALL transformations in one matrix, rather than a matrix and a vector. Also, matrices are associative. This means a translation, then a rotation, is not the same as a rotation and then a translation. The translation could be affected by the previous rotations, or scales. This could be useful.

Also, when multiplying a 4\*4 matrix with a 4 component vector, we could make the forth component of the vector 0, meaning it'll ignore the translation. A vector with a forth component of 0 means it's normalised. We don't want a normalised vector to me translated.

Yes, you could do all of this without matrices. It's just simpler and faster this way. You especially wouldn't want to manipulate a game with half matrices and half vectors.

---
Tags: matrix, transformation
---


# Question
Title: How can I detect mouse events on sprites in a canvas?
I'm making an HTML 5 game. I want mouse clicks on sprites drawn in a canvas element cause events that my code can react to. At the moment, I'm doing it by checking through all of my sprites in a for-loop on each click.

Is there a way to do that by adding an event listener to a sprite so it would respond just like that?

Are Javascript's custom events useful in this situation? I know it's possible with KinectJS, but I don't have any experience with it and really I'd like to learn how to do this myself without the help of a library.

# Answer
> 4 votes
The computer graphics term for what you're trying to do is **picking**.

The issue with picking from an HTML `canvas` is that the `canvas` doesn't understand anything about sprites -- all it knows about is pixels. In more general terms, `canvas` is a purely graphical representation -- it stores no semantic information. It has no idea what you wanted those pixels to represent.

The *sprites* you're talking about (which you're `for`-looping over and which KineticJS has triggering events and such) are not defined at the `canvas` level, but at your application's level. You could be rendering them with WebGL or SVG or anything else, but their semantics (what they *mean*) would stay the same. *That*'s where you should be asking *what did we click on?*

All of this is just a long way of saying **you're doing it totally right**. :) Looping over objects to see which one of them was clicked is totally reasonable. (The `canvas` could only have told you is what colour the clicked pixel was.)

---

Some stuff you might want to consider:

* If you want pixel-perfect picking from a `canvas`, there's a very good discussion of that here.
* If you're worried about picking performance as the number of objects increases, you could speed it up by storing your objects in a quadtree. I've had great success using D3's quadtree implementation.
* If you want to make your own `EventEmitter`s, consider using Node.js' event API, which has been ported to also run on browser JS engines.

---
Tags: javascript, html-canvas, events, mouse
---


# Question
Title: How can I compute the movement of an object along a parabola?
I am working on a simple 2D game. In the game, I have a 'robot' that throws a ball towards another robot, in the shape of a parabola. Both 'robots' have the same Y coordinate.

The program knows the positions of the two robots, and it knows the position of the parabola's apex ('vertex') as shown here:

I need the ball to travel along the parabola. This means (correct me if I'm wrong), that at any given time, I need to be able to calculate the Y position of the ball, since I know it's X position.

If so, how can I calculate that Y position at any given time, knowing the information above. Please try to make your answers as clear as possible, since my math knowledge is very basic.

# Answer
So you're looking for a parabolic function *y(x)* that equals zero at two known points. Let's call those points *r1* and *r2*, after robots 1 and 2. One solution is easily found:

*y(x) = ( x - r1 )( x - r2 )*

On top of the robots, one of the terms in parentheses becomes zero, which, multiplied by something else, remains zero. For that reason, we can multiply the entire thing by a factor *a*. This stretches the parabola vertically (or flips it upside down for negative values) without changing the location of the zeroes. We manipulate *a* to make sure the curve passes through the vertex, defined by coordinates *(xv, yv)*. We solve the following equation for *a*:

*y(xv) = yv*

*a ( xv \- r1 )( xv \- r2 ) = yv*

This yields:

*a = yv / (( xv \- r1 )( xv \- r2 ))*

We get the function *y(x)* we want by multiplying our original function with the scaling factor *a* we just obtained:

*y(x) = ( x - r1 )( x - r2 ) yv / (( xv \- r1 )( xv \- r2 ))*
> 2 votes

# Answer
If we are talking about projectiles here, and you know the X position, though it can simply be calculated:

Where *d* is the horizontal distance from the launch point.

You can simply calculate the y at distance x this equation:

Where:

* x is the x position.
* theta is the angle with the ground.
* g is the gravity constant.
* v is the velocity .
> 1 votes

---
Tags: 2d, physics, geometry
---


# Question
Title: How can I cut a graph representing 2D positions into two sub-graphs?
I have a graph where each node is associated with a 2D position. I would like to use a finite line to "cut" this graph into two halves, as shown below:

Note that the cutting line does have a direction. All vertices in that direction remain and aren't cut away.

How can I implement this?

# Answer
Here's the algorithm I see happening in your question: (I use "inside" meaning specifically not ON the cut line but only inside it)

```
P = Plane To Cut Across.
For every edge in the graph as Line A->B {
    A_inside = Is point A inside plane P?
    if (point B is on line P && !A_inside) return nothing;

    B_inside = Is point B inside plane P?
    if (point A is on line P && !B_inside) return nothing;

    if (A_inside == B_inside) {
        return Line A->B
    }
    Q = Intersection of line P and line A->B
    if (A_inside) {
        return Line A->Q
    } else {
        return Line Q->B
    }
}

```
> 1 votes

---
Tags: algorithm, procedural-generation, graph
---


# Question
Title: Why are entities in a component system composed at run time?
Why are entity component systems the way they are? For example as far as I have seen it may look like this

```
class Entity
    list of components
    add component
    remove component
    update comentent
    ....

```

So you are building your entities at runtime. I assume it will look like this

```
 Entity ork;
 ork.add(AI).add(movement).add(physics).add(renderer)

```

The problem I see with this approach is that errors appear at run time instead of compile time. It also seems to add a lot of potential errors for example the AI system only makes sense if the entity also has a movement component.

What is the advantage of building your objects that way instead of doing it like this?

```
class Ork: IEntity
     movementComp
     AiComp
     physicsComp
     rendererComp
     ....
     //wire everything together

```

One possible advantage that I can see is that object creation takes less code because you don't really need to wire up your objects, you just add your components and your done.

Would you please enlighten me?

# Answer
> 7 votes
Partly to allow data-driven operations, and partly because an ECS is a specific subset of all possible component-based designs.

A main point of component-based approach to aggregation (be it ECS or another use of components) is to allow you to reconfigure game objects *without* needing a recompile. You have an editor that your designers and game scripters can use to build up game objects without needing to bug a programmer and then wait for a new build (often requiring hours or even a full day to get rolled out to the content team).

There *are* perfectly valid component architectures that use static (compile-time) aggregation for components. This kind of class is just fine and is used in shipping games:

```
class Monster {
  TransformComponent m_Transform;
  MeshComponent m_Mesh;
  AnimationComponent m_Animation;

public:
  // accessors and forwarders

  // long repetetive methods like the following are common in this approach
  void handleMessage(const Message& msg) {
    m_Transform.handleMessage(msg);
    m_Mesh.handleMessage(msg);
    m_Animation.handleMessage(msg);
};

```

It's not an ECS but it is still a valid component architecture.

With an ECS specifically each component is intended to be external to the core game object. This is because one of the motivations for ECS is data-oriented design (*not* the same data-driven design!).

Data-oriented techniques focus on how the CPU uses data and this in turn shows that it's better to process data in small chunks that are allocated contiguously in memory. Putting a component object directly into a game object is antithetical to data-oriented design.

Grokking data-oriented design is essential to performance but it's *very* debatable whether your components are the right place to apply it. ECS assumes that your components are the main data being processed which may or may not be true for your particular engine/game. Performance-sensitive data in many engines tends to be external to the game objects/components.

# Answer
> 3 votes
If you know what an entity would require to wrap it up in an object, ECS doesn't stop you from doing the same in an iterative way. In a system, if an entity has the required components, the target components will be updated. If an AI component requires other components, it will only be updated if the entities has them. If it does not, a different behaviour can be chosen (typically, just moves on to the next entity).

This can be used to do interesting things. If your entity has an AI component that required a movement component, and the entity does not have it, it can choose to add a different AI, and return to the previous behaviour when such Movement component was added.

An example could be a freeze spell, that just removes the Movement component, and adds it back after it finishes it's effect. A frozen AI unit could switch it's behaviour to AIRanged (using shield, spells, try to remove the freeze), based on an AI state machine.

I am not too experienced with ECS, but I believe this could explain a bit.

---
Tags: entity-system, component-based, entity-component
---


# Question
Title: Should the Oj lobe of a Lafortune shader cause the light to be displaced?
I implemented the Lafortune shader in WebGL, and my biggest concern is about this formula:

**Explanation**

Kd/Ks is the material diffuse/specular color, ρd/ρs is the light diffuse/specular component, m is the number of lobes (in my shader I always use a single lobe), o is the viewer direction (from the surface point), i is the light direction, Oj is the lobe and ej is the shininess factor.
Full reference is here: A survey of shading models for real-time rendering, at page 28.

**Question**

The problem comes with the Oj lobe. I realized that as I change the value of Oj, the light gets displaced from it's original position, for example that's what I get with Oj= (-1,-1,1):

And that's what I get with Oj=(0,0,1):

Is that behavior normal? Should the light get displaced according to the value of Oj?

# Answer
> 10 votes
Yes, absolutely, **it is expected** that somehow the light appears to be at a different place if you change the main lobe’s properties without considering what it means physically.

The lobes describe, for a given incident light direction, in which directions light is going to be re-emitted. Here are a few examples of possible lobes: a perfect specular reflection lobe (for the Phong model), an off-specular lobe, and a retroreflection lobe (as is the case for catadioptric surfaces).

You are probably familiar with the specular highlight. When the surface is very shiny, it is the area around which the most re-emitted light reaches the viewer’s eye. This happens where the light direction and the viewer direction are exactly reflected (*i.e.* the view vector is close to the **R** vector above).

In the case of retroreflection there is a highlight, too, but that highlight is located where the light and viewer direction are close to each other (*i.e.* the view vector is close to the **L** vector).

Here is an example of highlighted areas in those two different cases:

As you can see, depending on the lobe, and even if the light does not move, the highlights can be at very different locations.

In your specific case, you chose `Oj = [0,0,1]`. It means that whatever the direction of the incident light, the most light will always be re-emitted along the surface’s normal. In other words, the highlight will be located **where the view vector is facing the surface normal**. And this is precisely what your second screenshot shows.

---
Tags: shaders, webgl
---


# Question
Title: What Should the Limits On the Camera's Pitch Be?
What should I be using as the limit to how much a camera can pitch in a first person video game? I'm assuming most video games use around the same value - so if I can use that value in my game, it will feel more natural to the user, since they are already used to such limits.

For example, let's say straight up is +90 degrees, straight down -90 degrees, and straight is 0 degrees. What's the min/max angle most first person games would impose?

Edit: Since this question is put on hold as opinion based, let me try to re-word it so it's more appropriate:

Is there a standard limit on the pitch? If so, what is it? If not, what should I keep in mind when deciding the limit for this?

# Answer
> 2 votes
For FPS cameras, there is no technical reason why the pitch needs to be smaller than +/- 90 degrees; the reasons for limiting it are purely gameplay-related, and it's obvious if you've encountered it.

When you are looking straight up or down, attempting to look left or right will not move your reticle with respect to the game world, instead you simply rotate on the spot. This makes it difficult to track moving targets that are directly above or below you, amongst other issues. Some games impose a pitch limit to address this issue, but most games avoid this issue altogether using smarter level design, and I think you should do this too.

Try to avoid situations that would require your player to look far up or down, such as:

* Avoid large vertical spaces, such as high towers, atriums etc. Prefer stairs, ramps and enclosed lifts to ladders or holes.
* If you cannot avoid a large vertical space, try to limit the vertical size of fields of view. For example, design watchtowers with shorter windows such that defenders can only see so far up or down. Consider this sketch of a watchtower that can only view so far down:

* Failing that, try to provide plenty of visual cues that help the player orient, to subtly remind them that they are looking up or down and to expect different results when looking left/right. Perfectly vertical or horizontal lines are great. For example, the skyscrapers in this picture lets you know that you are looking directly up, at an otherwise reference-free sky:

# Answer
> 1 votes
I don't think there's a standard value. Some games let you go all the way to 90 degrees; some cut you off at somewhere around 85 degrees, I'd guess. I don't think the precise value is a big deal.

Regarding the point about Euler angles, gimbal lock, etc. - there's actually no particular reason to limit the pitch to strictly less than 90 degrees, aside from the fact that it's disorienting to turn the camera upside down. In a first-person game you typically only control pitch and yaw, not roll, so you actually don't have any gimbal lock issue with the first-person camera itself.

If you want to animate in and out of the first-person camera then that should be done with quaternions, as usual when animating. In other words, convert the current first-person camera orientation to a quat and then animate/blend from there. However I think this is pretty unusual. Most first-person games don't attempt to blend smoothly between the first-person perspective and cutscene cameras.

---
Tags: camera, angles
---


title: Switching screens in a game

text:
# Question
Title: Switching screens in a game
I am working on a simple 2D game in Java.

I want the game to have an opening screen, instructions screen, and the screen with the game itself.

From the opening screen the user presses buttons to get to the instructions screen or to the game screen. From the instructions the user should be able to get back to the opening screen. When a game is finished, the user is automatically sent back to the opening screen.

I want all of this to happen in the same `JFrame`. Each screen should be a class that extends `JPanel`.

What would be the best way to do that? I thought of making a method inside the Main class (the one with the `main()` method), the switches screens and can be called from anywhere in the program.

But how will this method switch screens? What would be the best way to replace the JPanels?

Thanks a lot

# Answer
> 5 votes
The way I do it, not in java but in some sort of c#/c++ hybrid, is I have an engine class (similar to your main class), which holds a Screen object. The screen object is an abstract class with two main functions, update and draw. The engine has one screen which it just calls the Update and the Draw functions.

While I have no experience with it, I imagine the combination of your Main class and your JFrame would be similar to my Engine class and just handle calling the current screens functions.

Switching screens would be easy, just call Main.changeScreen, or something similar. Each screen would be its own class, you could have the base Screen class extend off JPanel if you needed. Having something like a pause screen would just pass a reference to the last screen, change the current screen to the pause screen and call the last screens draw function, then draw an overlay on top of that.

You could also have a stack of screens, where you only update/draw the top one, and going to the previous screen would simply be a Main.popScreen call. This might be more suitable to your exact scenario.

---
Tags: java, screen-management
---


# Question
Title: translating canvas for rotating sprites that shoot
I am trying to align bullets to my different sprites guns (top down 2D for android). Right now Im using this method to draw my bullets:

```
public void draw(Canvas canvas){
    update();
    canvas.save();
    canvas.rotate(angle, x + width / 2, y + height / 2);
    canvas.translate(translaterX, translaterY);
    canvas.drawBitmap(bitmap, x, y, null);
    canvas.restore();
}

```

The problem here is the translater, Im always having to add or substract from it to make the bullets spawn from my gun when my sprites rotate and I cant figure it out, is there any standard value for this, like `translaterX = bitmap.getwidth()/2`? I dont really understand how the translater works and I feel like Ive tried everything, what am I missing? For the examples sake lets say that my gun is always in the middle of the bitmap.

Or is there even another way to do this that is simpler?

# Answer
you'll need to calculate the rotation of the gun from the center of the player sprite

```
x = (float)Math.cos(playerAngle) * radius;
y = (float)Math.sin(playerAngle) * radius;

```

radius should be the distance that is from the player center to the position of the gun
> 1 votes

# Answer
You have different point locations for each gun, relative to the location of your sprite. Correct?

When you rotate your sprite, you need to rotate these points around the same center of rotation that you used for your sprite.
> 0 votes

---
Tags: java, 2d, android, html-canvas
---


# Question
Title: Centering three rectangles of different size
If I have 3 different sprites, that each belongs to the same sprite but with different animations type. Each has a different width, height, in the sprite sheet.

How do I adjust the 3 using math, to let them be centered, and overlapped on each other, so that when I can change their animation, and all animations are overlapped on each other. I would like to get the x,y for each sprite then, that result all of them have the same position.

# Answer
> 1 votes
Pick a reference point for the sprite images. For example, if it's a human character, choose the point he's standing in.

Then, make sure the position of this point is consistent in all the frames. It doesn't mean all the frames have to be the same size - it could mean this point is always horizontally centered in the image, and vertically at the bottom. This may mean you have to add transparent pixels around the actual image.

Now if the character is standing at (X,Y), you just need to draw the sprite at (X - W/2, Y - H).

---
Tags: mathematics, game-mechanics
---


title: Drawing UI using density pixels

text:
# Question
Title: Drawing UI using density pixels
I have a question about proper ways to draw UI, since I've learned what I know from the internet and by experimenting I often dont code the "proper" way, instead I do it my own way, not knowing if it will have consequenses that Im unaware of. So, Is it "wrong" to draw your UI using density pixels?

For Example:

```
canvas.drawText(bullets, this.getWidth() - 134 * dp, 32 * dp, paint);

```

I try to use `getWidth()` and `getHeight()` as much as possible but sometimes I just need to use constants in my code to place stuff where I want it, is this ok as long as I use dp? or will this effect the layout on screens with different resolutions/performance? (Don't have anything except my own to run the game on)

# Answer
I am assuming that you perhaps mean the scale? This is a perfectly valid solution!

All of my android projects run with a "target resolution" and an "actual resolution", and all of my UI elements scale appropriately.

Let's say my target resolution is at 960x540 and my actual resolution is 1920x1080 (aka my Galaxy S3). That means my scale is 2. I draw an object at 50,50 and my handler will scale that from the target resolution to the actual resolution, putting it at 100,100 on the screen.
> 2 votes

---
Tags: java, android, pixel, ui-design
---


# Question
Title: pygame - avoiding sprite 'jitters' on rotating the image
Is there a common trick for getting around sprites that are changing directions 'too quickly' and causing their sprite to display erratically?

In this project, the player moves in 8 directions by determining the `abs()` distance between the mouse's X and Y coordinates and its own `obj.rect.center`. If the absolute value is less than `obj.speed`, it simply moves to that point. If it is greater, it moves the distance its speed allows it to move in that direction. When it's time to draw the sprite, PyGame rotates it in accordance to `obj.direction` by using a dict called `SPINNER` with stored default values to pass to `pygame.transform.rotate`.

```
def draw(obj):
    drawImg = pygame.rotate.transform(obj.img, SPINNER[obj.direction])
    drawCtr = drawImg.get_rect(center=obj.rect.center)
    DISPLAYSURF.blit(drawImg, drawCtr)

```

This is fine for the foolish AI characters which typically make very few course corrections - however, small movements of the mouse can cause the player's `obj.direction` to update very quickly, which looks chaotic.

Is there a simple way to curb this behavior? My first guess is to bog down the player object with values that retain its previous state and then determine the amount of rotation to apply, but I have a feeling the better solution is to assign that responsibility to the 'view' and not the 'model'. I'm not sticking to any hard and fast rules regarding MVC, but I am trying to engage in enough separation of concerns that 'view-like methods' don't make 'controller-like' changes to 'model-like' objects, if that makes sense.

# Answer
I think you want a certain amount of "hysteresis" in your system here; this is commonly used in many kinds of systems to prevent rapid back-and-forth switching.

For example, you might add a 2.5 degree buffer, so when moving from top-right to right, an angle above 70 degrees is needed, but to move from right to top-right, and angle below 65 degrees is needed. This will stop the rapid flicking between the two.

As this is a concern of the display, I would say this probably belongs in View. You only need one additional attribute, to hold which of the 8 directions the object is currently pointing, and one argument, the new angle from the Model. The View layer then decides whether the new angle means a *displayed* change of direction.
> 1 votes

---
Tags: sprites, rotation, pygame
---


# Question
Title: DirectX9 thread lock problem with "present" and background loading new textures
**Given:** Selfmade 3D engine based on DirectX9 written in C++

**Task:** While render loop runs load additional textures in a background thread

**Current Implementation:** \- Create device with D3DCREATE\_MULTITHREADED \- Ensure that loaded content is used by render thread only after loading finished

**Problem:** Loading performance is very poor because DirectX calls block most of the time

**More specific:** Seems that all DirectX calls are blocked for the whole duration the "Present" call waits for the vsync. That is in my case 99% of the time -\> Loading thread has very few opportunities to run its DirectX calls.

**Absurd observation (on first sight):** Loading performance gets much better when I deactivate vsync and the render tread runs full speed. That is because the relative portion of time the render thread is inside a DirectX function is lower.

**Possible but problematic solution:** Do not let "Present" wait for the vsync, instead do a "while" loop with a non waiting "Present" and as long as it returns "D3DERR\_WASSTILLDRAWING" do a short "Sleep".

But I do not like that solution: First I am afraid it degrades maximum performance of the render loop as the resolution of "Sleep" time is limited. Second problem is that I am using multihead rendering with several monitors and I am afraid taking away full control about vsyncing from DirectX might introduce effects like tearing on some monitors or something like that.

**First question: Why?** I would bet my life that blocking whole DirectX while waiting for vsync is not neccessary especially while I am only using separated resources in the loading thread. But, well, it is like Microsoft implemented it and I am afraid I have to deal with it.

**Second question: Better ideas, anyone?** Does anybody have a better solution for this, or enough experience to tell me that my possible solution is not problematic at all or can think of a better way.

I know that Microsoft worked on these things with DirectX11 but porting the whole thing now is not an option, it would take too much time.

Thanks for your time, Ole

# Answer
> 0 votes
Came up with a solution on my own. Its not beautiful, but its simple and works.

Just do a "Sleep(8)" after each "Present" in the rendering thread.

Sounds weird at first sight and as far as 8 miliseconds is about half a frame you might think that I am limiting the maximum performance of my engine to 50%. But in fact only the GPU feeding rendering CPU thread sleeps, not the GPU itself. Testing shows no degradation in maximum performance, even If I set the maximimum buffered frames to only one to achieve better responsiveness to input in terms of delay. There is always at least one buffer left - the backbuffer.

Of course I have to outsource processor intensive calculations to other threads now because the rendering thread itself should not load the CPU, but that is good practice anyway and was already done.

But there is some uncertainty left:

1. You depend on a buffering and asychronous execution model you do not really know anything about, and which may work completely different under other circumstances.
2. The resolution of "Sleep" is somewhat undefined, so if you say 8 miliseconds you never know how long that "Sleep" will really be.

But both points haven proven to be negligible after extensive testing.

So as long as I do not port to a higher DirectX version I will go with that because:

1. Its very simple - all my current code can stay as it is.
2. I may use DirectX calls across my loading code now as I like. And the "Sleep" ensures they are not blocked for too long.
3. It still uses a perfectly "normal" Present call so I do not have to be afraid of tearing effects or some other unwanted behaviour in cases of complicated monitor configurations.

Only thing I am not sure about: Place the "Sleep" before or after The "Present"? Or a totally different place? While testing I could not notice a difference.

# Answer
> 4 votes
Preventing present waiting for a vsync is basically all you can do if you want to do other things with that thread or D3D9 in general.

However what you could do is load your file from disk on another thread (or asynchronously with say overlapped IO) then create your texture from that on the main thread. If your using a compressed image format that will need to be decompressed (e.g. PNG) you could also do the decoding on another thread.

If your not letting D3D9 block and just doing D3D calls on the main thread I believe that is about as good as you can get. I have never found the CPU thread to be completely limiting at that point, but rather the GPU or data transfers cant keep up.

# Answer
> -1 votes
Placing sleep after the Present call is usually the best solution, so you get least ammount of delay between all your D3D calls in the frame that you are about to present.

Sleep at start or end of the render thread. Doesnt matter where, for obvious reasons.

---
Tags: multithreading, directx9, vsync
---


# Question
Title: Use both AddForceAtPoint and change velocity property?
I'm using Rigidbody2D for some game objects. It seems that when I `AddForce()` or `AddForceAtPoint()`, the game objects are mostly affected on the Y axis and hardly at all on the x axis. I don't understand why. To really get any effect on the x axis, I need to have a very strong force like \*10 000. But the effect on the y axis is then extremely strong and shoots the object out of screen, yet only nudges the game object on the x scale.

I believe that the problem with the y axis is because I use `.velocity` to move the character. But I don't know how to change the velocity directly without doing that. What should I do to use both forces and set velocity on the same object?

# Answer
You're using the AddForceAtPosition, which will apply a force to a particular position on the rigid body. You are entering the direction vector on the zombie rigidbody as a position. You should just use the following:

```
rigidbody2D.AddForce (direction.normalized * force);

```
> 0 votes

# Answer
AddForceAtPosition is the function of RigidBody, right? It would appear that you're calling it incorrectly; it should be force first, then position.

For more information, See the API reference for Rigidbody.AddForceAtPosition.
> -1 votes

---
Tags: unity, physics
---


# Question
Title: How to move a Entity without moving its children in AndEngine?
I have a Entity in AndEngine and when I move it, all child move together with it. Which is great. But, sometimes, I need to move it without moving its children. Is it even possible? And, if it is, how can I do so?

# Answer
its not possible as you have it set up now. Children inherit the transform of their parents. You will have to do some extra work. Here are two suggestions:

Make it appear that they move separately, but applying an opposite transform to each child. For example if the parent translates 10 x, move each child -10 x. It will appear not to move.

Another approach, would be to construct your Entity groups differently, so that the current parent entity and its children were all siblings within a common EntityContainer parent. That way when you want to move them all, you move the parent, and when you want to move the one part, you move the one part.
> 1 votes

---
Tags: android, andengine
---


title: NPC Dialogue directing the player

text:
# Question
Title: NPC Dialogue directing the player
I recently gave a build of my game to some people and asked for any thoughts. One of the ones I keep getting is, 'I didn't know where to go first, but I guessed.'

The problem is, I'm still getting this *after having revised NPC text to be clearer and more helpful to the player.* The build in question is here, if you're curious to see what exactly I'm up to.

How can I make sure my NPC dialog is effective at guiding players to the next objective?

# Answer
> 3 votes
One thing I have seen often is **highlighting** key words like places, a macguffin to collect and key characters to talk to next. this allows a player who is just skimming to stop and reread the context

consider having a fortuneteller character who gives more direct hints, just someone who will be always available to talk to maybe in the home town maybe duplicated all over the place, depends on the world really.

if the players are lost in the sense that they don't know where places are then add signs and a world map

---
Tags: level-design, text, npc
---


# Question
Title: Order of render with transparency opengl
I tried to render using different render configurations (GL\_BLEND\_FUNC()) but I couldn't get the back object to render in certain angles. The first screenshot here shows one angle where the back object is not visible through the front one. In th second screenshot, I looked at the blocks from 180 degrees.

Is there a way I could render them through? Or would I have to implement a sorting algorithm?

# Answer
> 1 votes
You need to render them back to front relative to the camera in order for transparency to correctly work, check painters algorithm, and depth buffering.

The rational behind this, is that because how depth tests work. The "usual" case for OpenGL is to test fragments for depth, once a fragment passes the depth test it will be written to the frame buffer overwriting any fragment that was written in the same frame buffer position, in other words when your scene have only opaque objects the depth buffer is enough to sort your rendered objects because it only keeps fragments that are near the camera.

When transparency comes into play, this is no more the case, and you need more info than the only nearest fragment. The depth test will still make near fragments overwrite far ones in the frame buffer, even though transparency says otherwise.

`GL_BLEND_FUNC()` (deprecated btw you should switch to shaders) can only blend fragments using a certain fixed equation, has nothing to do with the order pixels are written and have no control over the depth buffer. So it will apply the blending equation regardless of how the depth buffer sorted them. So the only practical option is to draw far then near objects.

Order-independent transparency on the other hand exist but they are particularly hard to implement.

As a side note opaque only objects (unlike transparent) should be draw front to back to avoid over-draw.

# Answer
> 1 votes
There are techniques for order-indepdendent transparency, but they all require a ***lot*** of work. The two techniques I am most familiar with are depth peeling and stencil routed A buffering and they both have a lot of overhead. There are also some new techniques made possible with compute shaders by building a linked-list of fragments, but I have not fooled around with them.

In an engine that only draws cubes like this, sorting your geometry is probably your best bet - you only need to depth sort the centroids for each cube and assuming you cannot rotate the cubes you do not have to worry about objects that intersect throwing off the sort validity. Remember to transform your centroids using the modelview matrix before sorting by Z, you generally want to sort in view-space such that Z represents depth.

# Answer
> 1 votes
I actually wrote an article on a simple algorithm I designed a little while ago to handle this.

http://evergreen-game.tumblr.com/post/72616811569/transparent-object-sorting\]

Basically it's a quicksort (or mergesort) that uses a collision detection as its comparison function. If a convex object **A**'s volume created by sweeping it away from the camera plane intersects another convex object **B**, **A** is in front of **B** (and thus the comparison function returns that **A** is greater than **B**). In terms of implementation, I'd use a GJK raycast test.

---
Tags: opengl, rendering, transparency
---


# Question
Title: Is it possible to compile both VS and PS in a single file in VS2012?
`VS2012` has a built-in option for compiling `*.hlsl` files at compile time (e.g. to check for errors). But from what I've seen it requires me to provide the entry point (function) name for each file. What if I have both `Vertex Shader` and `Pixel Shader` in 1 file? Is it possible to make `VS2012` still compile that file (both shaders) to check for errors?

I know it's possible with `Custom Build Tool` option and using `fxc` in the `Command Line` (I just tell it to compile the file without specifying the entry point). But since by default `VS2012` is using `fxc` as well I thought it should be possible to compile 2 shaders in a single file when choosing `HLSL Compiler` option, too.

# Answer
It's not meant to work that way. The HLSL compiler options in VS2012 aren't there to just check your files for errors; they're designed to actually *compile* the shaders to HLSL bytecode, which you can then load and pass directly to `CreatePixelShader` etc. in your program.

While you can put both vertex and pixel shader code in the same file, the trouble is it takes two `fxc` calls to generate the bytecode for both, and the bytecodes need to be output to separate files. Visual Studio doesn't have any easy way to configure this situation, since normally a single source file generates a single output file, not two. (In a makefile, on the other hand, it would be trivial to do this.)

Compiling as an "effect" is something totally different. It allows multiple shaders in the same file, but you must use the technique/pass syntax to specify the entry points, and then you must use the Effects11 library at runtime to work with the shader. You cannot pass effect bytecode directly to `CreatePixelShader` and friends.
> 3 votes

---
Tags: hlsl, visual-studio
---


title: Run OpenGL shader on part of a texture

text:
# Question
Title: Run OpenGL shader on part of a texture
How do I run an OpenGL shader on just a portion of an off screen texture and leave the rest of the texture unmodified? Are there any calls that restrict the sampled pixels to just a rectangle or do I have to filter out the rectangle in the shader code?

# Answer
Yes, you can restrict rendering to just a rectangle by using either the viewport rect or the scissor rect. These can be set by the `glViewport` and `glScissor` calls, respectively.

The distinction is that setting the viewport will pretend that the viewport is the entire render target. Any geometry you render will be scaled down to the viewport; the viewport will always extend from -1 to 1 in NDC (post-projective) coordinates. The scissor rect, on the other hand, doesn't rescale any geometry or alter any coordinates - it simply suppresses rendering to any pixels outside the rect.
> 2 votes

---
Tags: opengl, opengl-es2
---


# Question
Title: How do I make a natural-looking map from some Voronoi regions?
I'm using Voronoi regions to create a map for my game, much like this. However, the lines are too straight and perfect. How do I make the borders more natural looking? As in, less like US state borders and more like international borders in Europe or Asia.

# Answer
Simply add smooth noise in the form of waves of different amplitudes and frequencies. You would need to add more vertices and split these edges. You could use a noise map to compute nice looking points based on the original edges at random.

Here is some working code:

```
/*****************************************************************************
 * Artur Wulf White - 18/1/14
 *****************************************************************************/

<languageVersion: 1.0;>

kernel Pres3D
<   namespace : "AWW37";
    vendor : "Arthur";
    version : 1;
    description : "Add noise to map"; >
{
    input image4 src;
    input image4 src2; // some smooth random colorful noise
    output float4 dst;

    parameter float4 coeffx;
    parameter float4 coeffy;

    void
    evaluatePixel()
    {
        const float2 imgSize = float2(512.0, 512.0);

        float2 c2D = (outCoord() / imgSize) - float2(0.5, 0.5);

        float4 tmp = sampleLinear(src2, outCoord());
        c2D.x += tmp.x * coeffx.x + tmp.y * coeffx.y + tmp.z * coeffx.z + tmp.w * coeffx.w;
        c2D.y += tmp.x * coeffy.x + tmp.y * coeffy.y + tmp.z * coeffy.z + tmp.w * coeffy.w;
        if(outCoord().x < imgSize.x && outCoord().y < imgSize.y){
            dst = sampleLinear(src, (c2D + float2(0.5, 0.5)) * imgSize);
        } else{
            dst = float4(0.0, 0.0, 0.0, 0.0);
        }

    }
}

```

And the result:

I used Pixel Bender for prototyping quickly. Can be re-written in another language.
> 1 votes

---
Tags: procedural-generation, maps
---


# Question
Title: MMORPG design question: Storing a tile map on the client computer, security concerns
in my game the client logs in and receives a map made of tiles (they differ in height and terrain type) from the server. I'm storing these tiles in a SQLite database on the client. The next time the client logs in, it communicates to the server that it already has the map. This saves network load and cpu on the server and decreases loading time.

Now I wonder if I'm doing the right thing. Because it would be very easy for the player to modify the tiles in his local SQLite database, turn a mountain into flat land client-side and walk right through it.

I will of course implement a system on the server that picks one or a few players at a time and checks if their reported positions are valid (as in, they aren't hacking), but I can't constantly run these checks on everyone for performance reasons.

This brings up the following questions:

1. Can I encrypt the SQLite database locally?
2. Would I hide the key in the code?
3. Is that safe? Could the client find the key?
4. Can the map be altered on the client even if I don't store it in a database?

Thanks everyone

# Answer
> 1 votes
I think the answer is that 90% or more of the clients would not find a way to use all these exploits but it is enough that one person will and it's on the net and the damage is done.

Often times it is sufficient to cheat a small amount of times at certain critical points to gain unfair advantage. You may not be able to detect cheaters if you randomly check once in awhile.

Short answer: Send the client the tile/height map once and check the result for every action the client performs. If you care about security, never let the client tell you the result.

Long rant: If you let the client-side make decisions about anything that has to do with game logic, such as your height map in this case that affects mobility, it is an invitation welcoming hacks. I wouldn't modify the tile-map, I would use a pkt sniffer and simply send the server pkts that contain the decisions I would like. I would do it for fun and challenge.

This strategy to optimize server performance is much like a bank, saying, well, you tell me how much money you have in your account and I'll check if I feel like it. Basically offering no form of security at all. It is not even exploitable, cause you are leaving the gate wide open. It is more like a feature.

# Answer
> 0 votes
Anything stored in the client can be found, read, and modified. Never store something in the client without adequate server-side enforcement. If someone has the time and desire to change those files, then I can assure you that they will.

For example, there's plenty of hacks and tools for the popular MMORPG World of Warcraft. If I wanted to, I'm sure I could find a tool or script that works with the current version of the game that would let me fly through the world. There are also certain programs that play the game for you, and they read the navigation meshes stored on the client.

---
Tags: mmo, security, encryption
---


title: Tessellation cracks

text:
# Question
Title: Tessellation cracks
i'm trying to a mesh tessellate with dx11 with the tessellation factor calculated by the size of the triangle and the distance to the screen.

I do the same operation on the 3 edges of the triangle, so i would expect i get the same level of tesselation on the other triangle that shares the edge, but it seems like it doesn't. Does anyone have an idea why this doesn't work like expected?

I need the same amount of tessellation on the other side of the edge to do displacement mapping without any cracks.

There are 5 triangles in this image, the red "circle" is around 2 edges shared by 4 of the triangles in pairs.

```
float calcLod(float3 a, float3 b)
{
    float dist = distance(a,b) ;

    float3 center = (b+a)/2;

    float camDist = distance(CameraPosition, center);

    return dist * tesselationStrength / camDist;
}

hullShaderConstantOutput hullShaderConstant( InputPatch<vertexShaderOutput, 3> ip, uint pid : SV_PrimitiveID )
{
    hullShaderConstantOutput output;
// get worldspace positions
    float3 v0 = ip[0].position;
    float3 v1 = ip[1].position;
    float3 v2 = ip[2].position;

    output.edges[0] = calcLod(v0, v1);
    output.edges[1] = calcLod(v1, v2);
    output.edges[2] = calcLod(v2, v0);

    output.inside = (output.edges[0] + output.edges[1] + output.edges[2])/3;

    return output;
}

[domain("tri")]
[partitioning("integer")]
[outputtopology("triangle_cw")]
[outputcontrolpoints(3)]
[patchconstantfunc("hullShaderConstant")]
hullShaderOutput hullShader( InputPatch<vertexShaderOutput, 3> input, uint pointId : SV_OutputControlPointID, uint pid : SV_PrimitiveID )
{
    hullShaderOutput output;
    output.position = input[pointId].position;
    output.uv = input[pointId].uv;
    output.tangentToWorld = input[pointId].tangentToWorld;
    return output;
}

```

# Answer
I also tried to create my own algorithm for tessellation, but it produced micro-cracking, then found this (on AMD's site if I recall correctly), which works like a charm:

```
cbuffer tessBuf:register(b0)
{
    float4 g_f4Eye; //camera position in world space
    float4 g_f4TessFactors; //constant tessfactors (from a material for example)
};

struct ConstantOutputType
{
    float fTessFactor[3] : SV_TessFactor;
    float fInsideTessFactor : SV_InsideTessFactor;
 //other outputs beside tessfactors
}

ConstantOutputType PatchConstantFunction(InputPatch<HullInputType, 3> I)
{
    ConstantOutputType O = (ConstantOutputType)0;

static const float MODIFIER = 0.6f;

    float fDistance;
    float3 f3MidPoint;
    // Edge 0
    f3MidPoint = ( I[2].f3Position + I[0].f3Position ) / 2.0f;
    fDistance = distance( f3MidPoint, g_f4Eye.xyz )*MODIFIER - g_f4TessFactors.z;
    O.fTessFactor[0] = g_f4TessFactors.x * ( 1.0f - clamp( ( fDistance / g_f4TessFactors.w ), 0.0f, 1.0f - ( 1.0f / g_f4TessFactors.x ) ) );
    // Edge 1
    f3MidPoint = ( I[0].f3Position + I[1].f3Position ) / 2.0f;
    fDistance = distance( f3MidPoint, g_f4Eye.xyz )*MODIFIER - g_f4TessFactors.z;
    O.fTessFactor[1] = g_f4TessFactors.x * ( 1.0f - clamp( ( fDistance / g_f4TessFactors.w ), 0.0f, 1.0f - ( 1.0f / g_f4TessFactors.x ) ) );
    // Edge 2
    f3MidPoint = ( I[1].f3Position + I[2].f3Position ) / 2.0f;
    fDistance = distance( f3MidPoint, g_f4Eye.xyz )*MODIFIER - g_f4TessFactors.z;
    O.fTessFactor[2] = g_f4TessFactors.x * ( 1.0f - clamp( ( fDistance / g_f4TessFactors.w ), 0.0f, 1.0f - ( 1.0f / g_f4TessFactors.x ) ) );
    // Inside
    O.fInsideTessFactor = ( O.fTessFactor[0] + O.fTessFactor[1] + O.fTessFactor[2] ) / 3.0f;

//Then pass the other members of the outputtype
}

```

Hope it helps!
> 1 votes

---
Tags: directx11, level-of-detail, tessellation, displacement-mapping
---


# Question
Title: Move the location of the XYZ pivot point on a mesh in UDK
When working with any mesh, you get an XYZ point somewhere on it. If you just want to move the mesh in any direction, it doesn't matter where this point is located.

However, I want to rotate a door. This requires the point of rotation to be very specific. I can't find anywhere how to change the location of the point. Can anyone help?

EDIT: solved, to change the pivot point, right click on the mesh, go to "Pivot" and move it. Then right click again and this time select "Save PrePivot to Pivot"

# Answer
As far as I know that is in the model itself. You have to open that model on whatever editing package you used to make the door in the first place and move the pivot there.
> 2 votes

# Answer
It seems to be that the pivot is set based on where the model is from the origin in world space not model space.
> 1 votes

# Answer
Double click the statick mesh you wish to alter the pivot point In the properties box that apears click the display tab click on pre pivot and you can then alter the pivot point using X Y Z coordinates
> 0 votes

# Answer
right click on the model. from the context menu select Pivot \> Move Here (Snapped)
> -1 votes

---
Tags: 3d-meshes, udk, unreal
---


# Question
Title: Unity Get corners of camera in world space
I'm making a 2D game and i need to get the corners of the camera in world cordinates. Is this possible in unity?

# Answer
> 6 votes
Yes, Unity allows you to get the corners of the camera in world coordinates.

```
Camera camera;
// gets top-right coord
camera.ViewportToWorldPoint(new Vector3(1,1,camera.nearClipPlane);

```

Please see the Documentation.

---
Tags: c#, 2d, unity
---


title: How to use FrameBuffer objects (OpenGL)

text:
# Question
Title: How to use FrameBuffer objects (OpenGL)
I want to draw a 2D scene and after the scene i want to draw some light effects.

When i draw some light, i create a FBO, draw in it and when finished with drawing, i want to create a texture where i draw the content of the FBO.

My current code:

```
//////////
//Init_

//Create Texture
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, out _texfbo);
glBindTexture(GL_TEXTURE_2D, _texfbo);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, _screenWidth, _screenHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, null);
glBindTexture(GL_TEXTURE_2D, 0);

//Create Renderbuffer
glGenRenderbuffers(1, out _rb);
glBindRenderbuffer(GL_RENDERBUFFER, _rb);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, _screenWidth, _screenHeight);
glBindRenderbuffer(GL_RENDERBUFFER, 0);

//Create Framebuffer
glGenFramebuffers(1, out _fbo);
glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, _texfbo, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, _rb);
glBindFramebuffer(GL_FRAMEBUFFER, 0);

//////////
//Loop:

glBindFramebuffer(GL_FRAMEBUFFER, _fbo);

//Draw Scene

glBindFramebuffer(GL_FRAMEBUFFER, 0);

glBindTexture(GL_TEXTURE_2D, _texfbo);

//Draw Rectangle with texture from Framebuffer

```

The Scene is not drawn on the screen, i think that means it's drawn in the right buffer. But i can't get someting on the screen. What is wrong?

# Answer
You are missing a `glDrawBuffers (...)` call. You need to establish that color attachment **0** is the first buffer your fragment shader is going to output.

### This should fix your problem:

```
glBindFramebuffer(GL_FRAMEBUFFER, _fbo);

const GLenum draw_buffer = GL_COLOR_ATTACHMENT0;
glDrawBuffers (1, &draw_buffer);

//Draw Scene

glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

You do not have to do this in the loop, you could do it once when you initialize your FBO. But you ***do*** have to do it somewhere while your FBO is bound.
> 1 votes

---
Tags: opengl, 2d, post-processing, frame-buffer
---


# Question
Title: How can I represent rooms and associated actions and inventory in a text-based adventure game?
I am just getting started learning to make games. I have created a simple text-based game where the user can walk around between rooms and interact with the objects in each room. However, I feel like my approach has led to a pile of bad spaghetti code. I'm not sure what a good way to structure a game like this would be.

My approach was to have one class with a method for each room and all the objects and interactions that could be done in that room. For example, this is the method for the study:

```
public static void Study()
{
    bool studyexited = false;

    while (!studyexited) {
        string usercommand = Console.ReadLine ();
        usercommand.ToLower ();

        switch (usercommand) {
        case "turn left":
            GameEventText.StudyLeft ();
            break;
        case "turn right":
            GameEventText.StudyRight ();
            break;
        case "go forward":
            Notes firstsetofclues = new Notes ("First Note");
            GameEventText.StudyFront ();
            string firststudycommand = Console.ReadLine ();
            firststudycommand.ToLower ();

            if (firststudycommand == "read note") {
                firstsetofclues.Firstnotereading ();
            }

            Console.WriteLine ("Picking up this note would prove valuable");
            string secondstudycommand = Console.ReadLine ();
            secondstudycommand.ToLower ();

            if (secondstudycommand == "pick up note") {
                if (MainClass.PlayerInventory.AddItem (firstsetofclues))
                {
                    Console.WriteLine ("The note has been added to your inventory");
                } else {
                    Console.WriteLine ("Your inventory is full");
                }

                MainClass.PlayerInventory.Inventorydisplay ();
            }
        }
    }
}

```

I don't feel like this is an approach that will scale; that is, I can't really write functions like this for *every* room. I believe that using files in some way would be a good strategy to avoid the "hard coding" that I'm currently doing. But I am not sure how I can achieve that?

# Answer
You are on the right track with your notion of using files to help alleviate the amount of hard-coded behavior you have. You want to make your game *data driven* as much as possible: it isn't a complicated concept, it is exactly what it sounds like. Drive the game behavior via data rather than directly via code.

A good mindset to take when determing how to drive some system via data is to look for the generalities. What things are in common between all instances of these systems? The commonalities become properties of the system, and the values of those properties are the data. Rooms, for example, usually all have a description and a list of exits. They may also have an "inventory," a list of items that are in the room.

One option you can persue is to use plain text or XML files (both of which are fairly straightforward to parse in C#) to store room data and contents.

Consider an XML structured file like this:

```
<room name="Study">
  <description>
  You enter a well-furnished study. A heavy wooden desk sits in one corner, an ugly lamp illuminating its surface.
  </description>
  <exits>
    <exit command="north">Hallway</exit>
  </exits>
  <items>
    <item name="Pen">
  </items>
</room>

```

This simple structure defines exactly what I listed above. A cooresponding `Room` class would have properties for the `Description`, a `List<T>` of exits (which are references to other rooms and the "go" command used to get there, in the above example going north would take the player to the hallway). There's also a `List<T>` of items.

Rather than put a `while` loop in a function for each room (which you can't do now since you only have a single `Room` class anyhow), you make a more generalized main loop:

```
while(!done) {
  Console.WriteLine(currentRoom.Description);
  var command = Command.Parse(Console.ReadLine());
  switch(command.Verb) {
    case "go":
      nextRoom = allRooms[currentRoom.GetExitForDirection(command.Object)];
      if (nextRoom == null) {
        Console.WriteLine("You cannot go that way.");
      }
      else {
        currentRoom = nextRoom;
      }
      break;
    ...
  }
}

```

Note that the `Command.Parse` function is left as an excersize for you, but should basically parse user input and return some kind of "verb/object" pair or similar (see this question for a kickstart on doing so, it's a bit beyond the scope of your question). In the above example, the verb would be "go" and the object may be "north" or "south" or whatever.

But beyond that, what this loop is doing is presenting the rooms in a generalized fashion; every time through, you print the room description, wait for user input. If the user input is "go to some other room," you find the exit of the current room coresponding to the direction the user entered. If there is no exit in that direction, say so, otherwise set the current room to that new room. Then repeat.

You can continue to refine this approach (for example, the above prints the room description after *every* command; can you see how to make it print the description only the first time you enter the room? How about that plus when you type a "look" command?). You can also scale it out to include handling of items in a similar fashion.
> 10 votes

# Answer
If you know html, you can think of the rooms as webpages, the exits as links, the actions perhaps as anchors and the game itself as a browser. The only additional thing the game needs to manage is an inventory and NPCs, which is basically a static class or two with the state of each item and character in the game, has it been taken, was it used/ talked to already, has it been destroyed/ defeated.

If you use html instead of pure xml in a similar way to what Josh described, you could debug in the browser, at least as far as navigation goes.
> 1 votes

---
Tags: c#
---


# Question
Title: What would be best practice of client comunication in a multiplayer game
Assume that we have a multiplayer game and the users are moving their characters (might be a circle) on the game area. At every game loop some changes can be happened. Should clients send their changes at every game loop to the server ? What would be best practice to comunicate clients each others by avoding overloading server?

Note: I'm asking this question for mostly HTML5 multiplayer games and will be using Box2D.

# Answer
> 3 votes
I'm far from an expert but I've been working on an HTML5 version of Pong that uses Websockets for multiplayer so I can share what's been working for me. The general maxim I've been living by is:

```
"Send the minimal amount of information necessary as infrequently as possible."

```

In my case I maintain the state of the keyboard by listening for the `keyup` and `keydown` events in the client. When one of these events is fired the client sends a message to the server and then updates its own state. This allows the client to employ client-side prediction (see this article for more details) and gives the server the minimal amount of information it needs to execute the move.

When the server receives one of these events it updates its own internal state and then rebroadcasts the event to all other clients so they can handle it as well.

To keep everything in sync the server will periodically (every 10 ticks of the engine in my case) send a "sync state" message to all of the clients giving them the exact positions of all players. You never want to sync the state of a client to the server as that opens up all sorts of cheating opportunities.

**EDIT**

To be clear, state syncing should only ever go *from* the server *to* the client, never the other way around.

**END EDIT**

I found Maple.js to be quite useful as a reference for a concrete implementation in Javascript.

# Answer
> 1 votes
There is usually no good reason for the clients to send their positions at every game loop, because in most situations their positions will either not change at all or change in a very predictable way (because they are moving with a constant speed in a constant direction).

To avoid a storm of lots of redundant network packages, you should just report changes in movement.

Also keep in mind that all game mechanics should happen on the server. When a client says that it moves towards point x:y, the server should treat this as a request to do so, and only relay it to the other clients when its actually able to do it according to the game mechanics. When you don't do this, players will be easily able to cheat.

# Answer
> 1 votes
What happens generally is that clients send their timestamped inputs to the server, then the server uses them to compute a new "world state", and sends it back to the clients.

That's it in a nutshell, but the devil is in the details. And there are tons of details :) I've written extensively about the topic, details and all, here: http://gabrielgambetta.com/fast\_paced\_multiplayer.html

# Answer
> 0 votes
I'm not an expert but i thought that the best practice is send the player input from the client side only when change (for example if the player is moving to left, not send infinite packages with 'left', only when starts or stop moving), and do all the game mechanics in the servers-side.

---
Tags: multiplayer, client-server, websocket
---


title: 2d grappling hook for platformer?

text:
# Question
Title: 2d grappling hook for platformer?
What are the options and mechanics for creating a grappling hook in a 2D game?

In the prototype for this feature, the person runs around in a platformer world and can throw the hook at any wall, where it sticks and shows a line to the player sprite. So that part (the easy part) is solved. But what options are available now for getting a rather good looking (not necessarily "correct") Tarzan-style grappling hook going, e.g. one allowing some kind of neat-looking swings?

(I understand several different approaches of how the mechanics could work are available; I'm looking for a simple one that may make some compromises and not be entirely physical, e.g. perhaps something which attracts the player to the hook center for a while or so while keeping to a certain rope min distance or such.)

I'm using JavaScript/ ImpactJS, by the way. Thanks!

# Answer
I have had some success with this problem, and my solution was certainly a "compromise" on the exact physics. That is almost always desirable, anyway.

My method was to maintain a fixed radius from the grapple point, and only update a speed scalar. I did *not* store a velocity vector; I will explain. Then each frame:

1. Determine player direction as a normal vector perpendicular to the direction from center of rotation to position.
2. Calculate total acceleration, (gravity, player input, etc.) in the direction of motion, and reduce that to a scalar value.
3. Modify speed scalar by the acceleration scalar.
4. Move the player in the direction of motion from step 1, with distance according to the speed scalar.
5. Modify position such that the stored radius is maintained. (Find the new direction to the center, and reduce the distance to that point to what it should be.)
6. Determine the new direction of motion and reduce speed by its dot product with the old direction (aka the cosine of the angle between them).

That last step will be a very high fraction of unity for small angle changes. It will slow the player down, but the deceleration will be almost imperceptible for slow speeds, and far more noticeable for higher speeds. It will appear as though you planned it that way, almost as if you were calculating a drag force. :)

It is conceivable to allow the swing radius to change, but I would recommend making that a separate system with completely independent, more arcade-like motion. In any case, it would also yield weird effects. For example, it would introduce physics abuses like those the ninja rope races in the recent versions of worms:

You will need to mitigate these problems as you see fit. But then again, they made for fun gameplay, so try it and see what happens.
> 4 votes

---
Tags: javascript, geometry
---


# Question
Title: Orthographic Zooming with 0,0 at top/left
I'm trying to implement zooming on my 2D game. Since it's using orthographic projection, I thought it would be easy to implement zooming. After looking around the internet, I found a bunch of explanations and samples on how to do this if (0,0) is the center of the screen with the orthographic projection. The problem is, my ortho projection has (0,0) at the top-left (similar to XNA/Monogame, and a couple others). I could not find any examples about how to implement zooming to the center of the screen when the center is not (0,0).

And help/links/code examples would be greatly appreciated.

# Answer
> 2 votes
there are two solutions:

# first:

translate your coordinate system into a coordinate system with it's origin at the center of the screen, scale it, translate it back again. If you modes this with matrices, you can combine all steps into a single matrix multiplication

# second:

change your setup into so coordinate system that has it's origin at the center. scale it.

no matter what you choose, knowing linear algebra and matricas will help you alot to make this kind of problems much easier.

# Answer
> 0 votes
As Byte56 pointed out in his comment, it would be the easiest to create a function where you just enter in-game-coordinates and get out the screen-coordinates. That would be the most flexible. But as you asked how to achieve this with (0|0) being the upper left, I'll give you the answer although it isn't intelligent to implement it like this (sorry I can't give you code but I think this won't be too difficult to achieve). So let's just say your *zoom* var stores the number of screen pixels per in-game unit. To make things easier, let's say, it's initial value is 100 and the screen measures 1000|1000. Not that complicated, is it? So, to keep things easy, let's say you want to zoom in to let *zoom* be 200. So what you know have to do is to tell the var that stores where the (0|0) point of the screen is on the map (let's call it \*upper\_left\*) to increase so you zoom to the center of the map and not to the upper-left (which would look just silly). So what you have to do is to calculate the amount of game units the screen was width *before* you did the zooming (that's quite easy: 1000 / 100 = 10) and the amount after the zooming (not that complicated: 1000 / 200 = 5). So to get the new x-value for \*upper\_left\*, just subtract the second value from the first (10 - 5 = 5) and divide it by two (5 / 2 = 2.5). Now, you're almost done. Just simply add that value to the X-coordinate of \*upper\_left\* and you're done. repeat that procedure for the y-coordinate and you've done everything.

---
Tags: c++, opengl, projection, screen, viewport
---


title: Rotate around the centre of the screen

text:
# Question
Title: Rotate around the centre of the screen
I want my camera to rotate around the centre of screen and I'm not sure how to achieve that. I have a rotation in the camera but I'm not sure what its rotating around. (I think it might be rotating around the position.X of camera, not sure) If you look at these two images: https://i.stack.imgur.com/wQNeN.png

https://i.stack.imgur.com/IOfBo.png

The first one shows how the camera is normally, and the second shows how I want the level to look when I would rotate the camera 90 degrees left or right. My camera:

```
public class Camera
{
    private Matrix transform;
    public Matrix Transform
    {
        get { return transform; }
    }

    private Vector2 position;
    public Vector2 Position
    {
        get { return position; }
        set { position = value; }
    }

    private float rotation;
    public float Rotation
    {
        get { return rotation; }
        set { rotation = value; }
    }

    private Viewport viewPort;

    public Camera(Viewport newView)
    {
        viewPort = newView;
    }

    public void Update(Player player)
    {

        position.X = player.PlayerPos.X + (player.PlayerRect.Width / 2) - viewPort.Width / 4;

        if (position.X < 0)
            position.X = 0;

        transform = Matrix.CreateTranslation(new Vector3(-position, 0)) *
            Matrix.CreateRotationZ(Rotation);

        if (Keyboard.GetState().IsKeyDown(Keys.D))
        {
            rotation += 0.01f;
        }
        if (Keyboard.GetState().IsKeyDown(Keys.A))
        {
            rotation -= 0.01f;
        }
    }
}

```

(I'm assuming you would need to rotate around the centre of the screen to achieve this)

# Answer
Here's some code I use to generate a matrix for my camera's transormation:

```
Matrix mTranslation, mRotate, mOriginAfterScale, mScale;

mTranslation = Matrix.CreateTranslation(-_position.X, -_position.Y, 0);
mRotate = Matrix.CreateRotationZ(_rotation);
mOriginAfterScale = Matrix.CreateTranslation(_origin.X, _origin.Y, 0);
mScale = Matrix.CreateScale(_zoom);

_transform = Matrix.Identity * mTranslation * mRotate * mOriginAfterScale * mScale;

```

`_origin` is a Vector2 which is half the values of the width and then height. Then you need to divide it by the zoom, i.e:

```
Vector2 _origin = new Vector2(screenWidth, screenHeight) / (2 * _zoom);

```

`_position` is the position you want your camera to be centered on.
> 1 votes

# Answer
I Build a class to return a vector that moves between to points by rotating around a point

```
    class Movement
        {
            Vector2 Postion;
            static float slices = (float)(2 * Math.PI) / 16; // circle split into 16 bits
            float Rotation;
            bool goLeft;
            public Movement()
            {
                Rotation = slices;
            }
            /// <summary>
            /// it outputs Vector2, it needs  Vector2 centerPoint and GameTime gameTime
            /// </summary>
            public Vector2 Update(Vector2 centerPoint, GameTime gameTime)
            {
                float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds; // movement based on cpu chip
                float min = slices * 2; // min point
                float max = slices * 6; // max point
                float distance  = 260; // distance away from point
                if (goLeft)
                {
                    Rotation -= 0.7f * elapsed;
                    if (Rotation < min) { goLeft = false; }
                }
                else
                {
                    Rotation += 0.7f * elapsed;
                    if (Rotation > max) { goLeft = true; }
                }

                this.Postion.X = ((float)-Math.Cos((double)Rotation) * (distance)) + centerPoint.X;
                this.Postion.Y = ((float)-Math.Sin((double)Rotation) * (distance)) + centerPoint.Y;

                return Postion;
            }
        }

```

hope this helps
> 0 votes

---
Tags: xna, c#, mathematics, camera
---


title: Minimal Projection Matrix

text:
# Question
Title: Minimal Projection Matrix
i hope you can help me. I'm currently stuck at the creation process for projection matrices used by shadow maps.

The problem is the following: I got the spot/directional light projectionmatrix/boundingfrustum and additionally the bounding frustum of the camera projection matrix.

What i need is the minimal bounding box of these two frustums. How do i get that? Or is there a better way to create projection matrices for shadow maps?

# Answer
everything that is visible is within \[-1;-1;-1;1\] \[1;1;1;1\] in ndc from your camera. invert the projection matrix to bring the box to world space coordinates and then make them relative to your light source by multiplying with your projection matrix of your light source. Now all you need to do is make a Bounding box of a convex shape with 8 vertices. Shouldn't be that hard.
> 1 votes

---
Tags: xna, matrix, projection, shadows
---


# Question
Title: Replace glTranslatef and glRotatef with matrixes
I'm not an opengl expert, and, as a novice, I prefer to practice a little bit with the old opengl just to be sure to understand correctly the basic concept of computer graphics before deal with shaders and modern opengl (3.x). I don't want to start a flame with this so I'll go through my question. I just know that what I'm using is deprecated.

What I wanto to render is this:

and I'm drawing it using this piece of code:

```
// draw grid
drawGrid(10, 1);

// draw a teapot
glPushMatrix();
glTranslatef(modelPosition[0], modelPosition[1], modelPosition[2]);
glRotatef(modelAngle[0], 1, 0, 0);
glRotatef(modelAngle[1], 0, 1, 0);
glRotatef(modelAngle[2], 0, 0, 1);
drawAxis(4);
drawTeapot();
glPopMatrix();

```

Now, I'd like to replace the last `glTranslatef` and `glRotatef` with matrixes, and I'm doing in this way:

```
Matrix4 _matrixModel;
_matrixModel.identity();
_matrixModel.translate(modelPosition[0], modelPosition[1], modelPosition[2]);
_matrixModel.rotateX(modelAngle[0]);
_matrixModel.rotateY(modelAngle[1]);
_matrixModel.rotateZ(modelAngle[2]);

glLoadMatrixf(_matrixModel.getTranspose());

```

And I don't see anymore the teapot. So I thought that this \_matrixModel is not complete because it is only the model matrix and I need a modelview so I have to multiply it with the projection matrix but.. this is what I get:

where am I wrong?

# Answer
> 2 votes
> So I thought that this \_matrixModel is not complete because it is only the model matrix and I need a modelview so I have to multiply it with the projection matrix but.

Not quite. You also have to multiply it with the view matrix. The model matrix transforms coordinates from model (or object) space to world space. The view matrix then transforms them from world space to camera (or eye) space. Then the projection matrix is used to transform coordinates in camera space to projection space.

See also this question on stackoverflow. And also the article linked therein.

The view matrix is what for example `gluLookAt` produces. See here for documentation about that function and what the matrix looks like.

If you have a camera object, that has a model matrix like other objects, the view matrix would be just the inverse of that model matrix.

# Answer
> 2 votes
Translate after rotation. If you rotate while the object is still in object-space, it will rotate the object around its center.

If you rotate after it's been translated into world-space you're in for a real nasty surprise. More often than not, the object will rotate its way off-screen. In short, if you want to rotate an object around the object's center, then the object has to be centered at the origin.

This is a very common problem, I would suggest you lookup rotation around an arbitrary point for a more thorough understanding.

Also, why are you loading the transpose matrix? Is your matrix math library row-major for some reason? I'd suggest you use `glm` at that point...

# Answer
> 1 votes
don't omit the pushMatrix and popMatrix and use glMultMatrix instead of glLoadMatrix. Otherwise you throw away all your camera information that was used to draw the grid.

http://www.opengl.org/sdk/docs/man2/xhtml/glMultMatrix.xml

---
Tags: opengl, matrix
---


# Question
Title: DirectX11 pixel shader in pipeline is missing
I'm writing a program which displays a MS3D model using DirectX, and unfortunately, the result shows nothing on the screen. When I use the Graphics Debugger from Visual Studio 13, I notice that the pixel shader is missing from the pipeline, as it is shown in the below picture

This is my pixel shader source code:

```
 cbuffer SkinningTransforms
 {
    matrix WorldMatrix;
    matrix ViewProjMatrix;
 };
//--------------------------------------------------------------------------------
// Inter-stage structures
//--------------------------------------------------------------------------------
struct VS_INPUT
{
    float3  position        : POSITION;
    int4    bone            : BONEID;
    float4  weights         : BONEWEIGHT;
    float3  normal          : NORMAL;
    float3  tangent         : TANGENT;
    float2  tex             : TEXCOORD;
};
//--------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 position         : SV_Position;
    float3 normal           : NORMAL;
    float3 light            : LIGHT;
    float2 tex              : TEXCOORDS;
};

Texture2D       ColorTexture : register( t0 );
SamplerState    LinearSampler : register( s0 );

//--------------------------------------------------------------------------------
VS_OUTPUT VSMAIN( in VS_INPUT input )
{
    VS_OUTPUT output;
    //Transform vertex and pass them to the pixel shader
    return output;
}

//--------------------------------------------------------------------------------
float4 PSMAIN( in VS_OUTPUT input ) : SV_Target
{
    // Calculate the lighting
    float3 n = normalize( input.normal );
    float3 l = normalize( input.light );

    float4 texColor = ColorTexture.Sample( LinearSampler, input.tex );

    float4 color = texColor * (max(dot(n,l),0) + 0.05f );
    return( color );
}

```

As I was known from Graphics Debugger, all of the graphics event are right. I listed in below important events, which might be relating to Pixel Shader:

```
106:(obj:4) ID3D11Device::CreateDepthStencilView(obj:24,NULL,obj:25)*
108:(obj:5) ID3D11DeviceContext::OMSetRenderTargets(8,{obj:1,NULL,NULL,NULL,NULL,NULL,NULL,NULL},obj:25)*
109:(obj:5) ID3D11DeviceContext::ClearRenderTargetView(obj:1,addr:21)*
111:(obj:5) ID3D11DeviceContext::ClearDepthStencilView(obj:25,1,1.000f,0)*
119:(obj:4) ID3D11Device::CreateSamplerState(addr:24,obj:27)*
134:(obj:4) ID3D11Device::CreatePixelShader(addr:27,21056,NULL,obj:30)*
135:CreateObject(D3D11 Pixel Shader,obj:30)
136:(obj:5) ID3D11DeviceContext::PSSetShader(obj:30,NULL,0)*
137:(obj:5) ID3D11DeviceContext::PSSetSamplers(0,1,{obj:27})*
139:(obj:4) ID3D11Device::CreateTexture2D(addr:28,addr:5,obj:31)*
140:CreateObject(D3D11 Texture2D,obj:31)
142:(obj:4) ID3D11Device::CreateShaderResourceView(obj:31,NULL,obj:32)*
143:CreateObject(D3D11 Shader Resource View,obj:32)
144:(obj:5) ID3D11DeviceContext::PSSetShaderResources(0,1,{obj:32})*
146:(obj:4) ID3D11Device::CreateRasterizerState(addr:29,obj:33)*
147:CreateObject(D3D11 Rasterizer State,obj:33)
152:(obj:5) ID3D11DeviceContext::RSSetState(obj:33)*
154:(obj:5) ID3D11DeviceContext::RSSetViewports(1,addr:30)*
156:(obj:4) ID3D11Device::CreateBlendState(addr:11,obj:34)*
157:CreateObject(D3D11 Blend State,obj:34)
159:(obj:5) ID3D11DeviceContext::OMSetBlendState(obj:34,addr:31,-1)*
162:(obj:4) ID3D11Device::CreateDepthStencilState(addr:32,obj:35)*
163:CreateObject(D3D11 Depth-Stencil State,obj:35)
165:(obj:5) ID3D11DeviceContext::OMSetDepthStencilState(obj:35,0)*

```

I debugged all of the function in the above list, and all of them return OK. Nothing wrong. My question is what is the reason the pixex shader is missing from pipleline, which in turn may result in the empty screen.

# Answer
I just spotted something, which doesn't look right. The alpha value returned from your pixel shader could easily end up as zero, which will make everything transparent. Try forcing it to be 1.0 like this:

```
float4 color = texColor * (max(dot(n,l),0) + 0.05f );

// At this point color.a could be zero which will make things transparent
color.a = 1.0; // Could also use texColor.a

return( color );

```

Of course the colour will most likely be black after the fix if that was what's wrong, so make sure the background color isn't black.
> 1 votes

---
Tags: c++, directx11, fragment-shader, rasterization
---


# Question
Title: Why are radians preferred over degrees in game development?
I've been looking up the definition of radians and found out that mathematicians prefer them because they are derived from pi instead of being completely arbitrary like degrees.

However, I have not found a compelling reason to use them in game development, possibly due to my complete lack of related mathematical understanding. I know that most sin/cos/tan functions in languages what radians, but someone could just as well create library functions in degrees (and avoid the inherent rounding errors when using pi).

I don't want this to be an opinionated poll, I would just like to hear from people that have done game development (and the associated math research) where radians offer a superior experience over degrees, as opposed to "We're using radians because we always used them", just for the sake of helping me (and possibly others) to understand what they are good for.

# Answer
> 53 votes
Radians are used in math because

1. They measure arc-length on the circle, i.e. an arc of angle theta on a circle of radius r is just r * theta (as opposed to pi/180 * r * theta).
2. When trig functions are defined in terms of radians, they obey simpler relationships between each other, such as cosine being the derivative of sine, or sin(x) ~= x for small x. If defined in terms of degrees, the derivative of sine would be pi/180 * cosine, and we'd have sin(x) ~= pi/180 * x for small x.

It's not that mathematicians just like pi. Radians are actually a more *natural* choice of angle measure than degrees, for the above reasons. They are the angle measure in which factors like pi/180 disappear.

So IMO, the question is not "why use radians", but "why *not* use radians". In other words, one doesn't need a reason to use radians; they are the *default* choice of angle measure. One needs a reason to use degrees. For example one might choose to show angles in degrees in the user interface of an app, because they're more familiar to many people (especially artists). However, personally I've gotten quite used to thinking about angles in terms of radians rather than degrees.

I don't have any specific gamedev examples to give you because this isn't really a gamedev issue, but a mathematical one, and would be the same in any field that uses math.

(By the way, there are no more "inherent rounding errors when using pi" than when using degrees...angles should always be real numbers, not integers, else how are you going to represent an angle of half a degree? :))

# Answer
> 5 votes
Nathan's answer is very concrete. I'd like to supply a more general view:

The most complex mathematical concept that is natively implemented in most processing units are floating point numbers as models for the field of real numbers ℝ. Visual geometriy is based on the three dimensional real vector space ℝ³. Coordinates are real numbers. Geometric quantities are based on the *length*, which is a real multiple of a unit.

Because of this base in real numbers and lengths, it is practical to also model angles by real numbers resp. lengths. Radians is the length of the arc of a unit circle with the given angle. Thus it is the model of an angle most compatible with all these other units based on real numbers resp. lengths. For example, the approximation sin x ~ x for small values of x is an approximation of the y-coordinate of a point on the unit circle by the arc from the x-axis to that point.

One should not forget, that an angle *is **not*** a length. It is one of the 4 parts of a plane created by two intersecting straight lines. It's quantity is bounded by the symmetriy of planes in ℝ³ and the euclidean metric.

It is more natural to model an angle by the semiopen interval \[0,1) (or (0,1\] ) glued together at its end points, given the value of an angle as part of a full turn. Degrees are just 1/360 of a full turn. (BTW: Number theoretically, this is a better choice than the decimal system used for real numbers.)

# Answer
> 1 votes
While I use radians too, for all the reasons specified, there's at least one good reason why degrees are preferred: Precision and accumulation of errors. Rotating through a full circle 1 degree at a time is exact. Rotating through a full circle 2PI/360 radians at a time is not. Performing a 90 degree rotation 4 times on a pixel grid gets you back to exactly where you started. Performing a 2PI/4 radian rotation on a pixel grid 4 times does not.

# Answer
> -3 votes
Let's agree, that it is better to choose any and stick to it than using two definitions und a little guessing which one of them is necessary for the current function. Then using arc length is more natural for the implementation of sin and cos which might be a reason for cmath to implement it that way. Since games are often written in C++ or C and there is already sin and cos implemented it makes sense to stick to that definition.

\[Screw you legacy opengl\]

---
Tags: mathematics, angles
---


# Question
Title: Pathfinding Search for Path of Specific Length
I am creating a roguelike. This question applies to random map generation.

First, I generate areas using a BSP algorithm, where I randomly divide the map into areas. Then, I generate a graph of the areas so that I can use search algorithms to generate paths through the map. It is easy to find the shortest path between two areas, but I would like to find a path with a specific number of steps(or path cost).

So, my question is: What is an algorithm that I can use to find a path that has a specific cost or cost range?

An Example of why I think this is useful: Say that I randomly choose two areas(start and end for example). These area might be next to each other, they might be on the opposite sides of the map. I want to force the player to travel through a minimum number of areas before reaching the end, let's say 5. I should be able to be like:

```
path = startArea.findPathMinimumCost(endArea,5);

```

And it will return a path of cost 5, or the shortest path, whichever has the greater cost.

Thank you.

# Answer
Try this on for size: Always choose a specific corner of the generated map as the origin, then perform a Dijkstra's path-finding and randomly select a destination from those areas which meet the minimum distance criteria. Finally, rotate the map according to some algorithm to imply random start location to the user.
> 2 votes

# Answer
I would suggest to incrementally make your shortest path worse. Start with the shortest path and incrementally block some random edges within your path, and search again. If no path is available anymore, choose a different edge.
> 0 votes

# Answer
In graph theory terms, you want to find a simple path (path with no repeated vertices) from A to B with a certain length. One approach is to find all simple paths from A to B, then choose the right one from among that list.

This SO question covers the first part (finding all paths from A to B). In summary, you can do this:

* Use a modified BFS to find all paths starting from A, keeping the ones that get to B and discarding the ones that don't.
* You need to modify BFS so that instead of updating a node's predecessor if you find a shorter path to it, you keep a list of possible predecessors (as well as lists of visited nodes to keep the paths simple)
* Finally, backtrack from B through all the possible predecessors to build the list of paths; select the best path using some criterion (e.g. closest length to target).
> 0 votes

---
Tags: algorithm, path-finding, random, roguelikes, content-generation
---


# Question
Title: Bounding volume hierarchy for outdoor scenes
I started with a very simple graphics engine a few weeks ago and I have finished a simple scene-graph and I am now at a point where I need to create a bounding volume hierarchy.

I never really thought about it that much and now I am stuck. Basically my current goal is to achieve view frustum culling and I know how to do this but I have no idea of how to generate a bounding volume hierarchy.

The problem that I have is that I don't know how to create bounding boxes spatially.

My scene-graph allows me to group objects together and at the moment I am doing this

```
[object_group1,object_group2,....object_groupN]

```

And now I just check if the object\_group is inside my view frustum, but this is only a naive solution.

Which algorithm/data structure would you recommend for an outdoor scene?

# Answer
> 1 votes
First, of all I *smell* that you are going to use your scene graph for frustum culling and other operations not meant to be a scene graph operations. ***Please Don't***.

Using scene graph for things other than propagating data like transformations and some other properties, is counter intuitive. If frustum culling needs info derived *from* the scene graph Doesn't mean the scene graph should be used to make frustum culling. And that's might big reason why you are stuck.

Regarding your outdoor scene, it's hard to select one spatial partitioning that will fit (rule:-) them all.. If your engine contains a lot of terrains then you might use an Octree data structure, especially if there are a lot of static objects. Bounding Volume Hierarchy can be used with more dynamic scenes. And you probably will end up using multiple spatial partitioning techniques.

My advice is to implement basic frustum culling testing the whole scene without BVH or Octrees, this will be your starting point. Don't overwhelm yourself ( because I did that I ended up less productive). After successfully implementing frustum culling you can *optimize* more using other techniques, which highly depend on the scene.

And again **Please Don't** use your scene graph for things it was not meant to be.

---
Tags: rendering, scene-graph, bounding-boxes
---