# Question
Title: OpenGL ES create stencil effect using texture
## Environment

This is the environment I am working in:

* OpenGL ES 2.0
* iPhone Simulator & iPhone 4
* iMac 27" using NVIDIA GeForce GTX 680MX 2048 MB

Hope that helps.

## The Problem

Been searching high and low from multiple sources and multiple sites including Stackoverflow but haven't got a working stencil effect going.

What I have is this:

The black 'S' thing is **not a polygon** but a texture drawn onto a rectangle quad that is the same width and height as the background image.

I am trying to do a stencil effect where the background and the little yellow guy should only be visible if it's within that black 'S' texture.

In my fragment shader, I have this:

```
varying lowp vec4 destinationColor;

varying lowp vec2 TexCoordOut;
uniform sampler2D Texture;
uniform highp float TexScale;

void main()
{
    highp vec4 color = texture2D(Texture, TexCoordOut);

    if(color.a == 0.0)
    {
        discard;
    }

    gl_FragColor = color;
}

```

For my setup Depth Stencil Buffer, I have set it up like this:

```
-(void)setupDepthStencilBuffer
{
    GLint width;
    GLint height;

    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &width);
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &height);

    glGenBuffers(1, &depthStencilBuffer);
    glBindRenderbuffer(GL_RENDERBUFFER, depthStencilBuffer);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, width, height);
    //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_COMPONENT24_OES, width, height);

    NSLog(@"depthStencilBuffer = %d", depthStencilBuffer);
}

```

According to Apple's documentation (which I think is outdated):

http://developer.apple.com/library/ios/#documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/WorkingwithEAGLContexts/WorkingwithEAGLContexts.html#//apple\_ref/doc/uid/TP40008793-CH103-SW1

Note some of the things like GL\_RGBA enum doesn't exist when I tried to type it in Xcode (I think Apple must have removed it and made it obsolete).

I have also tried Apple's way of defining the so called "depth/stencil" buffer in the above link but it gave the same error below.

The code I have above is how you would create a stencil buffer.

In my setupFrameBuffer() method, I attach it like so:

```
-(void)setupFrameBuffer
{
    GLuint frameBuffer;

    glGenBuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilBuffer);

    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

    if(status != GL_FRAMEBUFFER_COMPLETE)
    {
        NSLog(@"failed to make complete framebuffer object %x", status);
    }
}

```

The error I got when I attach it like shown above is:

> failed to make complete framebuffer object 8cd6

For my render method, I have this:

```
-(void)render:(CADisplayLink *)displayLink
{
    glClearColor(0.5f, 0.5f, 0.5f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

    glClearStencil(0);
    glEnable(GL_STENCIL_TEST);

    // ----------------------------------------
    // Don't write to color or depth buffer
    // ----------------------------------------
    glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
    glDepthMask(GL_FALSE);

    glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

    // ----------------------------------------
    // First set the alpha test so that
    // fragments greather than threshold
    // will pass thus will set nonzero
    // bits masked by 1 in stencil
    // ----------------------------------------
    glStencilFunc(GL_ALWAYS, 1, 1);

    // ----------------------------------------------------------------
    // Drawing our stencil
    // ----------------------------------------------------------------

    glBindBuffer(GL_ARRAY_BUFFER, bgVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bgIBO);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, stencilTexture);
    glUniform1i(textureUniform, 0);

    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 3));
    glVertexAttribPointer(texCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 7));

    glDrawElements(GL_TRIANGLE_FAN, sizeof(bgIndices)/sizeof(bgIndices[0]), GL_UNSIGNED_BYTE, 0);

    /*
    // -----------------------------------------
    // Second pass of the fragments less
    // or equal than the threshold will pass
    // thus will set zero bits masked by 1
    // in stencil
    // -----------------------------------------
    glStencilFunc(GL_ALWAYS, 0, 1);

    glBindBuffer(GL_ARRAY_BUFFER, bgVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bgIBO);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, stencilTexture);
    glUniform1i(textureUniform, 0);

    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 3));
    glVertexAttribPointer(texCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 7));

    glDrawElements(GL_TRIANGLE_STRIP, sizeof(bgIndices)/sizeof(bgIndices[0]), GL_UNSIGNED_BYTE, 0);
    */

    // ---------------------------------------------------
    // RE-ENABLING THE COLOR AND DEPTH MASK AGAIN
    // TO DRAW REST OF THE SCENE AFTER STENCIL
    // ---------------------------------------------------
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
    glDepthMask(GL_TRUE);

    Mat4 frustrumMatrix = [CameraMatrix createOrthographicMatrixUsingLeft:-(self.bounds.size.width / 2.0)
                                                                       Right:(self.bounds.size.width / 2.0)
                                                                      Bottom:-(self.bounds.size.height / 2.0)
                                                                         Top:(self.bounds.size.height / 2.0)
                                                                        Near:-1.0f
                                                                         Far:1.0f];

    glUniformMatrix4fv(projectionUniform, 1, 0, frustrumMatrix.matrix);

    glViewport(0, 0, self.bounds.size.width * self.contentScaleFactor, self.bounds.size.height * self.contentScaleFactor);

    // ----------------------------------------------------------------
    // Drawing our background first
    // ----------------------------------------------------------------

    glBindBuffer(GL_ARRAY_BUFFER, bgVBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bgIBO);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, bgTexture);
    glUniform1i(textureUniform, 0);

    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 3));
    glVertexAttribPointer(texCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 7));

    glDrawElements(GL_TRIANGLE_FAN, sizeof(bgIndices)/sizeof(bgIndices[0]), GL_UNSIGNED_BYTE, 0);

    glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer);

    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, floorTexture);
    glUniform1i(textureUniform, 0);

    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
    glVertexAttribPointer(colorSlot, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 3));

    glVertexAttribPointer(texCoordSlot, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const void *)(sizeof(GLfloat) * 7));

    glDrawElements(GL_TRIANGLE_FAN, sizeof(Indices)/sizeof(Indices[0]), GL_UNSIGNED_BYTE, 0);

    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    [context presentRenderbuffer:GL_RENDERBUFFER];
}

```

The result of this is obviously a pink screen that means my setup is wrong:

Anyone able to shed some light please ?

# Answer
## The Solution

Hell yeah!!!

I'm one happy chap now! :D

OK, I finally manage to get Stencil working with texture :)

(also learned a number of things along the way, e.g. we can check color.alpha and use discard as a way to remove transparent pixel and the glBlend(GL\_SRC\_ALPHA, GL\_ONE\_MINUS\_SRC\_ALPHA) trick becomes obsolete)

So the first thing I noticed I did wrong was incorrectly generating the names for my stencil buffer.

In the above source code in my question, I had typed:

```
glGenBuffers(1, &depthStencilBuffer);

```

This should really be:

```
glGenRenderbuffers(1, &depthStencilBuffer);

```

d'oh!

Second of all, I commented out the important second glStencilFunc() that needed to be called:

```
glStencilFunc(GL_ALWAYS, 1, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);

// draw black 'S' textured quad here

. . .

// -----------------------------------
// I WAS MISSING THIS IMPORTANT LINE
// -----------------------------------
glStencilFunc(GL_ALWAYS, 0, 1);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

/* draw the rest of the scene here (the background and yellow guy) */

```

The final result:

Hope that helps everyone else who is trying this cool stencil with a texture feature :D

I also modified a number of other source code but those two were the main changes that got it working.

Some helpful changes helped me debug the problem too:

* I have found that I don't need to attach depth buffer to my framebuffer to get it to work
* I also don't need to clear GL\_DEPTH\_BUFFER\_BIT
* I changed the setupFrameBuffer() method to this with the extra if-else conditions to clearly point to me the possible errors.

The new setupFrameBuffer() method:

```
-(void)setupFrameBuffer
{
    GLuint frameBuffer;

    glGenBuffers(1, &frameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorRenderBuffer);
    //glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthStencilBuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthStencilBuffer);

    GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

    if(status == GL_FRAMEBUFFER_COMPLETE)
    {
        NSLog(@"framebuffer complete");
        //NSLog(@"failed to make complete framebuffer object %x", status);
    }
    else if(status == GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT)
    {
        NSLog(@"incomplete framebuffer attachments");
    }
    else if(status == GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT)
    {
        NSLog(@"incomplete missing framebuffer attachments");
    }
    else if(status == GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS)
    {
        NSLog(@"incomplete framebuffer attachments dimensions");
    }
    else if(status == GL_FRAMEBUFFER_UNSUPPORTED)
    {
        NSLog(@"combination of internal formats used by attachments in thef ramebuffer results in a nonrednerable target");
    }
}

```
> 7 votes

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


# Question
Title: How to handle sprite speed when objects move using Box2d?
I have a basic platformer using Box2d that works great. However, I now want to stop using my default square, and implement some running and jumping animations.

How can I ensure that:

* When running, the speed of the running sprite is correct with the current player speed, as to prevent the sprite from 'moonwalking'.
* When jumping, play the correct frames at the right moments? I imagine I need to check the vertical velocity and if this is zero again while jumping I'm at the highest point, but how do I track where to initiate the landing animation?

# Answer
> 3 votes
You'll just have to adjust your frame time based on your speed (or use a different animation based on your sprite's velocity). As for jumping, you'd either have to play the animation after landing or make sure you know you're landing soon, e.g. by having an invisible physics object below your character that gets notified of collisions in advance (but which won't cause anything else to bounce or anything similar).

---
Tags: animation, sprites, box2d, platformer
---


title: ray polygon intersection

text:
# Question
Title: ray polygon intersection
I am looking for an elegant way to do ray and polygon intersections in 2d. I don't care about languages.

Now what I'm doing is taking a line that lies on the ray (with a screen length) and testing line-to-line intersections between this derived-ray and all lines formed by each consecutive vertices in the polygon.

This, for now, is good even if I don't know which parts of the ray are inside or outside the polygon (in cases it is concave one). But for now I don't need this information, even if a general approach could maybe give it.

I don't care about self-intersection polygons.

Any advice? Maybe triangulating the polygons could be an idea?

# Answer
For 2D, I don't think you can do much better than just intersecting the boundary edges. If you triangulate your polygon, you will end up with more edges to test against, making your test slower.
> 2 votes

# Answer
The simplest algorithm is to test ray intersection with each edge. It has linear complexity. You can skip edges, e.g. when ray goes right and both edge points are on the left side from ray origin.

Here is my implementation in JavaScript: http://polyk.ivank.net/?p=demos&d=raycast

There are algorithms with logarithmic complexity for this, but you will have to make some data structure upon your polygon (BVH, KD-tree, octree...).
> 1 votes

---
Tags: geometry, intersection
---


title: Basic plane kinematics

text:
# Question
Title: Basic plane kinematics
I never did physics in my life and this is really hard for me. I am currently trying to implement movement in the X and Y axis of a plane, in a video game I am making.

What I want to do is, given a starting angle and a velocity, and the value of gravity, calculate in different points of time the current angle and the displacement in X and Y.

So, lets say, my current velocity is `4 units / second` and my current angle is `30 degrees` and my gravity is `9.8 u/s`, I want to pass an argument in seconds and calculate the final angle, velocity, and the amount of X and Y the body moved.

# Answer
If the acceleration is constant, e.g. the only force acting on the body is gravitational, we can use a trivial expression for the displacement at any time. It is ***a*** integrated twice with respect to *t*. In vector form: ***x****(t) = **x**(0) + **v**(0) t + ½ **a***.

The starting velocity can be derived from *θ* using: ***v*** *= v (cos θ, sin θ)* or a variant, depending on how the angle is defined.

With the example values of:

* ***x**(0) = (0, 0)*
* *v(0) = 4*
* *θ = 30°*
* ***a** = (0, -9.8)*

the displacement can be calculated as: ***x****(t) = (2√3, 2) t + (0,-4.9) t²*.
> 0 votes

# Answer
Just do your math step by step (as long as you're not looking for complex simulation of this):

To move the plane based on its acceleration (`plane.a`; can be constant or `0`) you should first calculate its velocity along the axes:

```
plane.vx += plane.a * cos(plane.angle) * delta_time / 2.0;
plane.vy += plane.a * sin(plane.angle) * delta_time / 2.0;

```

This should get you some basic movement. Based on your coordinate system (e.g. in which direction the y coordinate becomes bigger) you might have to negate one or more parameters.

Once this is done, just apply the gravity as well:

```
plane.vy += gravity * delta_time / 2.0;

```

Then you can just update your coordinates:

```
plane.x += plane.vx * delta_time;
plane.y += plane.vy * delta_time;

```

If you're using fixed time steps in your logic, you can just assume `delta_time` being `1`, which makes the whole calculation even easier to be done. The velocities become simple deltas and your acceleration essentially becomes a constant velocity:

```
plane.x += plane.v * cos(plane.angle);
plane.y += plane.v * sin(plane.angle) + gravity;

```
> 1 votes

---
Tags: 2d, physics, movement
---


# Question
Title: Multithreading for a mixed-genre game in Python?
So here's the situation. I'm making a game that mixes two genres; arcade shooter and puzzler. They don't intertwine TOO much; all the interaction that really goes on is that every time an enemy is destroyed, a block is created. The blocks aren't even a part of the main collision detection system; they have their own more suited to their needs. What I want to ask is this; **might it be a good idea to have the arcade shooter portion run on one thread, and the puzzle game portion run on another?**

# Answer
> 3 votes
Probably not, unless you want to create extra work for yourself.

Threading is an optimization, which adds significant complexity to the program, and if you don't move the right thing on to another thread it won't even add much performance. The only way to know what the right thing to optimize is, is to use a profiler.

If you do want to use threads to improve performance a task based approach is what I'd recommend.

For example, let's say that for example once you've finished writing the game you find that the arcade game code takes 20ms / frame, and the puzzle game code takes 2ms / frame. That gives a total frame time of 22ms. In that case at best moving the puzzle game to another thread saves you 10% of the frame time. However if you could split the arcade game across two threads that could gain you up to 10ms.

The task based approach has the potential for even better performance, because it can easily scale to more than two threads.

It's also worth noting that games are generally not easy to split across multiple threads, and there's much better ways to optimize Python code than using threads - for example rewriting the expensive parts of the code in a lower level language like C/C++ can give huge gains.

# Answer
> 2 votes
In addition to what Adam has already said in his answer (and especially the second paragraph), it's worth noting that Python does not scale well with threads at all, because there is a global lock shared across all Python threads so that only one can run at a time, except under certain conditions. So the answer to any question like "Multithreading for *XYZ* in Python?" is almost always 'No'.

I'll add one thing - multithreading can indeed be used as a way to improve code organisation. But this is almost exclusively to allow a linear process to run in parallel with other processes that don't share many resources. Your situation doesn't seem to resemble this in that neither process is linear, and that you are likely to have many shared resources (eg. screen, input devices, sound system). As such it is probably better to go with the usual time-sliced approach.

# Answer
> 1 votes
First: Threads and processes are different on different platforms, and there is an advantage to using processes on Linux and a disadvantage on Windows. So your intended platform may drive which one you should use.

The general rule of thumb is that if you are hardware-bound, you should split blocking tasks off into their own thread. If you are computation-bound, you should split high computation tasks off into their own process.

Second: Adding concurrent processes of any sort adds complexity because you are inherently creating an asynchronous condition that requires synchronization. In other words, you must share data and time across the various tasks. Unfortunately, the programmer must explicitly identify and create a design for these tasks to communicate with each other.

Third: Testing and especially debugging becomes much harder because the tasks run independently of each other and obtaining state information for each task and the system itself is much more complex. This often means that you must increase your verbosity for logging and traces.

The general consensus is that you should not optimize your code too early. In other words, design your code as modular as possible, but do not add the extra complexity of threading until you realize that you must.

---
Tags: python, optimization, multithreading, pygame
---


title: Rotating a 2D Skeleton

text:
# Question
Title: Rotating a 2D Skeleton
I am currently implementing a 2D skeleton system in C# with XNA, but got stuck in how I would rotate the bones around a skeleton's axis.

A basic algorithm that I have figured out already would involve, one part or another, manipulating the coordenates of the bone around the axis. I just cannot find the equation that would return these coordenates once provided an angle.

For example, if the bone's axis.X originally is -1 and its axis.Y -2 units away from the skeleton's axis' X and Y, then when the skeleton is rotated 90 degrees the X difference would become 2 and the Y, -1 (illustrated).

I'm certain the function I'm looking for would end something like this:

```
    void rotateVector (Vector2 vectorToAnalyze, Vector2 axis, float currentAngle, float newAngle, out Vector2 result);

```

If there are already functions that do the job, then I wouldn't mind using them - I'm certain there's something in the Matrix class related to this, but I'm a bit overwhelmed by it. As much it really would be nice to learn how this whole deal rolls, the most important thing to me, simply, is to find a solution that works this way I intend.

# Answer
You might be overcomplicating this a bit - plus this is something the different matrixes have been introduced for.

This is how I'd do this (don't calculate the rotation and stuff in software; it might be nice for a training exercise, but in the end let the graphics hardware do the math):

* Set your bone's local coordinates (i.e. the vertex coordinates) in a way that its origin is in the center (i.e. the point where you'd like to rotate it). You only have to do this once.
* Reset the bone's projection matrix to the identity matrix. Now the bone won't be rotated or translated at all.
* Apply the rotation you're looking for (the correct angle).
* Now apply the proper transformation (i.e. move the bone where you want it to be on screen).

Once this is done, the bone should be rotated and where you want it to be.

What you're experiencing here is doing this in the wrong order (translating the bone first, then rotating), which just overcomplicates things a lot.
> 1 votes

# Answer
Assuming that your bone has Parent bone, Length and Rotation (not transformed), then:

```
BeginPosition = Parent.EndPosition;
TransformedRotation = Rotation + Parent.TransformedRotation;
var v = new Vector2f(Length, 0);
v = v.Rotate(TransformedRotation);
EndPosition = bone.BeginPosition + v;

```

Rotate is my extension method:

```
public static Vector2 Rotate(this Vector2 v, float angle)
{
    var sin = (float)Math.Sin(angle);
    var cos = (float)Math.Cos(angle);
    return new Vector2(v.X * cos - v.Y * sin, v.X * sin + v.Y * cos);
}

```

Note that you have to update parent before it's children.
> 0 votes

---
Tags: xna, c#, rotation, skeletal-animation
---


# Question
Title: In an Entity-Component System, how to represent the world/level/gameboard?
I am trying to learn more about Entity-Component Systems, and something that kinda stuck out at me was the question of how to represent the world in such a system? More specifically, I'm trying to do a version of Tetris with such a system, and I was wondering how I would put the board, and the fallen pieces in place?

I was thinking of having each piece be an Entity, and it would store a number of Block Components, which would represent the individual blocks that make up the pieces, and it's relative position to the center of the piece. Would it be a good idea to simply transfer this component to some Board Entity, which would hold many of these components in the board?

# Answer
> 5 votes
## The Piece

Rather than having several BlockComponents that represent blocks, consider having a single ShapeComponent that has a 2D array of blocks - these can be a simple binary matrix ('true' where block present, 'false' where not). You will find rotation around a point much easier to implement mathematically this way, and collision is a breeze. Your ShapeComponent can then expose methods to manipulate it (ShapeComponent.RotateClockwise(), for example).

A Piece entity would be defined as:

* PositionComponent (integer X,Y co-ordinates)
* ShapeComponent (as described above)
* RenderComponent (marks the entity as renderable, probably defines a colour)
* MoveableComponent (marks the entity as moveable each game tick)

## The Board

The 'board' doesn't really exist...! All you need to do is implement two constraints on your active piece:

* it may not move below 0 on the Y axis
* it may not move outside of 0-10 on the X axis

This logic should be performed by the system in charge of updating piece position. If the piece violates #1 it should be stopped as if it had rested on top of another block. If it violates #2 the movement should simply be ignored.

Bear in mind that you need not completely eschew the OO paradigm when implementing an Entity-Component-System architecture. Rather, the ECS approach is based on one of the basic principles of good OO design, *Prefer composition over inheritance*.

# Answer
> 2 votes
> I was thinking of having each piece be an Entity, and it would store a number of Block Components, which would represent the individual blocks that make up the pieces, and it's relative position to the center of the piece.

Sounds like it would be far too complex. The aim of using components is not to see how many different components you can have! It's to improve modularity by packaging units of functionality together which can be combined to change the functionality. Each of your proposed Block Components would have pretty much no functionality and you'd need a separate component to manage the whole lot when it comes to rotations etc.

Far better would be to have *one* component that represents the arrangement of blocks. It would contain data that specifies the exact arrangement, current rotation, etc. Each Piece would have one Blocks component to manage all that.

> Would it be a good idea to simply transfer this component to some Board Entity, which would hold many of these components in the board?

There is certainly an argument for having a Board entity, which has some sort of Board component to manage the game environment, and which also contains all the Piece entities.

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


title: mat3x4 in webGL shaders

text:
# Question
Title: mat3x4 in webGL shaders
I am porting the IQM bone animation format to Javascript and have run into a problem...

The vertex shader is failing to compile and the only error message I get out is `'mat3x4' : syntax error` on the first occurance of `mat3x4` in the file. Its the very data-type name itself that is unsupported, it seems.

This happens on all machines I have access to for testing, which have a variety of Intel and ATI cards and run Linux with Firefox. (Chrome is not available.)

If I change all `mat3x4` to, say, `mat3` then my shader compiles fine.

1. does webGL support `mat3x4`? (I can find nothing via Google)
2. how can I work around this? How can I package the bones into `mat4`, for example, and keep the code working correctly?

# Answer
> 6 votes
1- Unfortunately no, the WebGL standard references the GLSL ES 1.0 standard, which only has square matrices (section 4.1.6).

2- A `mat3x4` holds 12 floats, so you may need to pass the information as a `mat4` to the shader anyway (`mat3` only holds 9). In that case you will need to use 4×4 matrices in the client code, too, and fill the last column with the values `[0 0 0 1]`.

This will use 30% more uniform space, unfortunately, but then some parts of the shader can be simplified:

```
 vec4 mpos = vec4(gl_Vertex * m, gl_Vertex.w);

```

simply becomes:

```
vec4 mpos = gl_Vertex * m;

```

2bis- One other solution is to send the array of `Matrix3x4` as an array of `Vec4` and rebuild the matrix in the shader:

```
uniform vec4 bonemats[240];

[...]

vec4 c1 = bonemats[3*int(vbones.x)]   * vweights.x;
vec4 c2 = bonemats[3*int(vbones.x)+1] * vweights.x;
vec4 c3 = bonemats[3*int(vbones.x)+2] * vweights.x;
c1 += bonemats[3*int(vbones.y)]   * vweights.y;
c2 += bonemats[3*int(vbones.y)+1] * vweights.y;
c3 += bonemats[3*int(vbones.y)+2] * vweights.y;

[...]

m = mat4(c1, c2, c3, vec4(0.0, 0.0, 0.0, 1.0));

[...]

vec4 mpos = gl_Vertex * m;

```

If you do that, the client code needs not be modified if your `Matrix3x4` array is stored column-major.

---
Tags: javascript, html5, glsl, webgl
---


title: Component-based Rendering

text:
# Question
Title: Component-based Rendering
I have component `Renderer`, that `Draws` `Texture2D` (or sprite) Then I have method `OnUpdate`, and there should be my rendering code, something like

```
spriteBatch.Draw(Texture, Vector2.Zero, Color.White)

```

But first I need to do `spriteBatch.Begin();`. Where should i call it? And how can I make sure it's called before any Renderer components `OnUpdate` method?

(i need to do more stuff then just `Begin()` i also need to set right rendertarget for camera etc.)

# Answer
> 1 votes
How I like to go about this is, instead of calling `spriteBatch.Draw(...)` right in your component's `OnUpdate` method, I submit it to a rendering system and draw every object that has been submitted after they have all been updated.

So inside your component you could have something like this:

```
if( inViewOfCamera() ) {
    submitToRenderSystem(spriteBatch);
}

```

Inside your render system you will build up an array of spriteBatch objects that you need to draw. Then, after all of your objects have been updated, you can call the draw method on your render system, which could look something like this:

```
SpriteBatch.Begin();
for( int i = 0; i < renderObjects.size(); i++ ) {
    renderObjects.get(i).Draw(...);
}
SpriteBatch.End();

```

# Answer
> 0 votes
It sounds like you have every component type potentially in a single list.

I would suggest that you split the lists up so that like components are in their own list and potentially within their own management system. This would then allow your manager to do any sort of global prep work, like call .Begin() before then processing (OnUpdate()) all of its components.

Also, remember that just because everything is a component it does not mean every component has Only the component interface to its data and/or logic. The Update call to a Rendering component for example might just simply update animations if need be before the draw calls are done.

# Answer
> 0 votes
When you're using a component based model, you have two real options when it comes to the individual components.

* Keep track of all components in one massive "Components" list (or array, or dictionary, etc.), calling OnUpdate() on each one sequentially, in turn.
* Group the components by type or usage, and call the groups you need, in turn.

I'm oversimplifying, clearly, but I hope it's obvious that the latter is much more useful than the former.

Either way, you need to both keep track of all of the components, and update each of the components. It sounds like you're already using a "Subsystem" kind of class that handles your individual render components. Great! You're well on your way to the second bullet point. As long as your Render Subsystem knows how to access the render components you need, you can start the spritebatch, update your components en masse, and then end it.

I wrote a component-based render system myself, and this was all the code within my Draw() call (in my case, my GraphicsSubsystem extended XNA's DrawableGameComponent class, which means it has both an "Update" and a "Draw" method):

```
 public override void Draw(GameTime gametime)
        {
            sprites.Begin();

                foreach (var pair in graphicsDict)
                {
                    //only draw them if they're set to visible
                    if (pair.Value.visible)
                    {
                        pair.Value.draw(sprites);
                    }
                }
            sprites.End();

            base.Draw(gametime);
        }

```

Where GraphicsDict is a GUID,RenderComponent Dictionary that holds all of the components, and I pass in sprites, the SpriteBatch as a parameter. This way you can do all of your rendering that requires certain batch settings at once, and you don't have to worry about switching between settings between the drawing of the individual components.

---
Tags: sprites, rendering, component-based
---


# Question
Title: What is a suitable input method to use for a 2D platformer on a touch device?
I am creating a 2d platformer game like Super Meat Boy in which precision of movement of my lead character matters. I am using libgdx. The keyboard controls on the PC work precisely, but when it comes to accelerometer handling, it's really hard to handle the character precisely. This worsens in stages with congested safe paths to escape. I thought of implementing an on-screen analog ball for handling input, but read a lot of bad consequences of that on the internet.

What is an intuitive but *precise* input method to use for platformer games on touch devices?

# Answer
> 7 votes
In a word: **Swiping.**

I played Pac-Man championship edition on my Android phone and what I thought really worked for it is that while there was an on screen joystick, you didn't actually have to touch it to move Pac-Man in the proper direction. If your finger fell off the joystick it didn't matter. All that mattered is in what direction you moved your finger.

To move up, swipe up. To move down, swipe down. To move left, swipe left. To move right, swipe right.

You could just as easily make swiping context sensitive to screen regions and actions currently happening within the game. Imagine your phone is in landscape mode and you are holding it like a video game controller. The left half of the screen could be reserved for movement using the swiping I describe above. The right half of the screen could be used for actions such as jumping, shooting, shielding, whatever game play abilities you want to give your player using swiping in a very similar fashion. Or if you only have one ability (like jumping in Super Meat Boy) - just treat the right half of the screen as a button.

**Update**

We were discussing this in chat and it appeared that my solution, the way its described above is a lot like a virtual stick that moves when you lift up and place down your finger. I want to elaborate that this is not the case and is actually much more flexible than that.

The image above shows the swiping pattern one could take to move Pacman around on the board. Note that the action that is taken is not at all based on where you place your finger down the first time. If you accidentally move your finger too far when swiping right or not enough when swiping down, its ok. With this implementation as long as you swiped far enough for it to register properly with the software it will take it and use where your finger ended up as the next starting point, or if you lift your finger off, it will use the next place you put your finger down.

As I said before, you could apply this to a platformer just by splitting controls into separate regions so that that your swipes and taps do different things depending on where on the screen you performed the action. The obvious route is make the left side handle movement just using swiping. Then the right side would be used to handle actions and abilities of the player using any combination of swipes and taps.

# Answer
> 4 votes
What if you treated a half of the screen like a virtual track ball where the position/speed of your character is directly tied to that of the ball? Swiping and releasing would set your character into constant motion (and cause the trackball to spin). Holding your finger on the screen would be like holding the trackball so that you could make small adjustments to your character's position, or stop your character from moving. I think this could work quite well for those frantic moments in Super Meat Boy where you're trying to run, jump, then stop on a dime. This would be an experimental approach because I haven't seen it done before, but anything is better than a virtual stick.

Edit: The Steam Controller handles their trackpad like a simulated trackball, but I haven't experimented enough to find a game that treats it like one.

# Answer
> 2 votes
I found side-of-screen **touch and hold** controls to be the most responsive.

If the person touches the left side, run left (until he lets go). If the person touches the right side, run right.

RunRunRiot! is an example of this.

As for jumping, you could go for a mid-screen tap (using either hand).

Examples (landscaped iPad) Running right

```
______________
|            |
|            |
|            |
|___________R|

```

Jumping right

```
______________
|            |
|L*          |
|            |
|___________R|

```

(L\* = left tap)

Jumping left

```
______________
|            |
|          R*|
|            |
|L___________|

```

# Answer
> 1 votes
The best input for a touch screen game I have found is on those really simple platform games when all you have to do is touch the screen to jump! Any game that uses the accelerometer for movement input to me is very disorienting!

This is a common dilemma when developing on a touch screen, if only there was a D-pad attachment that was popular. I think you will have to try your on screen ball idea.

Maybe you could have the left and right input on the far left and far right of the screen and have the up and down using the the higher or lower part of the left or right input. I think that makes sense?

# Answer
> 1 votes
You could consider having more precise controls for only when the player character is airborne.

For instance, if the right side of the screen controlled lateral direction, you could have the entirety of the left side be for the jump. Once airborne, the bottom left half of the screen could be 'descend' and the top half could be double jump.

Another option would be to adopt a jumping scheme like Jetpack Joyride or those "Cave" type games, where the longer you hold "up" the higher you go. It has the potential to be fairly precise and I think would work well with a Super Meat Boy type platformer, assuming the levels are designed appropriately.

---
Tags: 2d, input, touch, multitouch
---


# Question
Title: Should the world transformation matrix be stored in a constant buffer when rendering?
Generally when rendering objects you would:

1. Apply world transformation to go from object space to world space
2. Apply view transformation to go from world space to camera space
3. Apply perspective projection transform to go from camera space to canonical view volume

In a normal situation, you only have a single camera and screen to work with so you only have one each of view transform matrix and projection transform matrix to render a frame. So, before the rendering begins, you need to put all this info in a constant buffer. So that the vertex shader can transform the vertices per objects into a world matrix.

Considering you need a (probably unique) world transform matrix for each object, *how is this process actually done in practical situations*?

The easiest and obvious solution I can think of is to put world matrices in a constant buffer but if I am not mistaken from the architecture of video card memory, you are not able to dynamically allocate constant buffers. I can think of this being a big problem because in real situations, the number of objects to be rendered would vary each frame.

A tutorial I came across handles this situation in a rather concerning way. If object `A, B, C` exists, instead of passing all objects to the vertex shader, it would go through the following process:

* Add world matrix of object A into a constant buffer then draw the object A
* Add world matrix of object B into a constant buffer then draw the object B.
* Add world matrix of object C into a constant buffer then draw the object C.

This works, but this seems really counter-intuitive from a performance perspective as you have to do a lot of synchronization for a simple rendering process. Not to mention drawing operation becomes O(n) for the number of objects. It also doesn't fit too well with the philosophy of shader process where parallel processing is heavily favored.

So I had a random thought for a potential solution: you would first dynamically allocate memory size of `(XMMatrix) * (Object Count)` on the GPU, and when transforming from vertex from vertex shader, you would select which matrix to use from list of world matrices. This seems very doable in CUDA but not too sure about HLSL . Is this idea even legit to begin with?

I guess you could also somehow send the vertices of the object located in world space directly to the vertex shader.

# Answer
> 6 votes
Your understanding of the general rendering process seems mostly correct, except that you frequently refer to "passing the object to the vertex shader," which isn't what happens. Instead you set an active vertex shader, along with several other active state objects (textures, uniform parameters to your shader, constant buffers, and so on), and then you submit the object geometry to be rendered to the GPU. It does the job of processing those vertices and passes those vertices to the vertex shader.

In terms of answering your question (how to deal with the fact that most objects will generally have unique world transforms), the first approach you described is generally what's done. Each object is gets a corresponding draw call, and prior to that draw call the appropriate world matrix is set. The world matrix can be set as a shader uniform, but D3D10 introduced constant buffers which can also be used (as you've noted) for this purpose.

One of the benefits of constant buffers is that you can construct several, each with unique intended update scopes, so you can create a constant buffer dedicated entirely to containing the values that will changed in each frame.

You're correct that this approach involves a number of draw calls that scales with the number of objects to be rendered, and that one solution to this is to pre-pack a large vertex buffer with all the pre-transformed world coordinates of all the geometry and render it in one go. This kind of batching can be useful for static geometry.

Another approach for dealing with varying world transforms while reducing the number of draw calls is instancing. This involves multiple vertex buffers, one containing the baseline geometry data and another containing the per-instance data for each object to be drawn. There's a D3D9-specific article here, but the 10+ API still retains support for it via calls like DrawInstancedIndexed.

Basically, you were pretty close to the more viable solutions with your guesses and speculation. The biggest place you missed it was talking about directly allocating `(matrix * object count)` on the GPU, because you can't really *directly* do that (and `XMMatrix` is not a GPU type, it's a CPU-side matrix type), but it's effectively what you're doing when you supply per-instance data via a vertex buffer.

# Answer
> 2 votes
For one-off objects like the world geometry, you shouldn't have issues using a matrix in the constant buffer.

A technique for dealing with lots of small objects is to place the positions and other per-object data into their own buffers (texture samplers were used heavily some years back). This is used frequently with Instancing.

---
Tags: 3d, rendering, directx11
---


# Question
Title: How to handle materials in an Entity/Component system
My E/C implementation is the basic one where Entities are just ID's, Components are data and Systems act on the Data. Right now I'm having trouble with object materials and rendering in general. For simple objetcs I have a `ModelComponent`, tied to a `RenderSystem`, `ModelComponent` has the vertex buffer ids that the render system uses. A simple `MaterialComponent` would probably have color or specular strenght, etc, but I wanted it to be flexible enough to allow for more than one render pass and general "effects" that are not as easy as a simple variable in the `MaterialComponent`.

Trying to solve these problems I came up with two solutions:

**1 - Super-generic Material Component**

Something like this:

```
struct Material : public Component
{
    ShaderData* shader;
    std::vector<std::pair<std::string, boost::any>> uniforms;
    [...]
};

```

and in the render system I would loop and pass the uniforms to the shader. I suppose this would be slow, but fast enough for my purposes.

**2 - Another layer of abstraction, MaterialData**

Having a class to wrap specific materials, that could be inherited by whatever specialized material, the base class would have something like `void set_shader_constants(ShaderData* d)` but the implementation is up to each class, and the `MaterialComponent` would have a pointer to a MaterialData object.

I'm not sure which approach I would prefer, but neither of these touch the subject of multiple passes, or other complex rendering techniques.

Any idea on how to accomplish this?

# Answer
Materials are a graphics concept, and belong in your renderer. A renderer is too low-level a piece of architecture to be built on top of an entity system. Entity systems should be for higher-level game objects. *Not everything needs to be a component,* and in fact, it's generally a bad idea to try to force everything into a single paradigm like that. It creates a least-common-denominator solution.

Consequently I would advise that you take a different approach:

* A material is just another type in your renderer.
* Your renderer has a type that represents "a thing to be drawn to the screen." Frequently these are called "render instances" or "renderables" or even "models." This type has a reference to the material it will use when drawing and provides a public API to allow a consumer of the renderer to set that material to whatever is desired.

This is essentially asking you to take your `ModelComponent` and rename it `Model`, removing the dependency on the entity/component layer and thus moving it to a lower layer of abstraction, alongside the rest of your renderer.

Then, you do this:

* In the same layer of abstraction as your other components, you have some kind of "aspect component" which represents the visual presentation of an entity. This component just contains a reference to some renderable (as described above), which in turn contains the reference to a material. The component may provide an API to expose the renderable (thus allowing clients to manipulate it) or it may wrap the renderable's API to control exposure. That's up to you.

This addresses the component interdependence issue you're running into by having models and materials both be components; an entity should either have an aspect or not, and that aspect should be able to encode everything about the presentation of the entity, including the material.

This also affords you the flexibility to take other approaches with the material object that would be harder to do with that object as a component because of the lack of parity with the rest of the render system abstraction.

Your issue of allowing for more complex effects and multiple passes is one that could be solved primarily in the material, by exposing functions to query and set named shader constants exposed by the material's shader file. This is especially true if you use effect files (in D3D) which support multiple passes and the like. Even if you aren't using effect files, you can expose the idea of multiple passes from the material, each with distinct shaders, and allow the material API to provide manipulators for that. It would be easier and cleaner to integrate into the rendering API most likely, since material is now at the same level of abstraction.
> 26 votes

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


# Question
Title: How can I cleanly and elegantly handle data and dependancies between classes
I'm working on 2d topdown game in SFML 2, and need to find an elegant way in which everything will work and fit together.

Allow me to explain. I have a number of classes that inherit from an abstract base that provides a draw method and an update method to all the classes.

In the game loop, I call update and then draw on each class, I imagine this is a pretty common approach. I have classes for tiles, collisions, the player and a resource manager that contains all the tiles/images/textures. Due to the way input works in SFML I decided to have each class handle input (if required) in its update call.

Up until now I have been passing in dependencies as needed, for example, in the player class when a movement key is pressed, I call a method on the collision class to check if the position the player wants to move to will be a collision, and only move the player if there is no collision.

This works fine for the most part, but I believe it can be done better, I'm just not sure how.

I now have more complex things I need to implement, eg: a player is able to walk up to an object on the ground, press a key to pick it up/loot it and it will then show up in inventory. This means that a few things need to happen:

* Check if the player is in range of a lootable item on keypress, else do not proceed.
* Find the item.
* Update the sprite texture on the item from its default texture to a "looted" texture.
* Update the collision for the item: it might have changed shape or been removed completely.
* Inventory needs to be updated with the added item.

How do I make everything communicate? With my current system I will end up with my classes going out of scope, and method calls to each other all over the place. I could tie up all the classes in one big manager and give each one a reference to the parent manager class, but this seems only slightly better.

Any help/advice would be greatly appreciated! If anything is unclear, I'm happy to expand on things.

# Answer
> 5 votes
Not sure if composition will solve all the problems. Maybe can partially help. But if what you want is to decouple classes I would look into more events driven logic. This way e.g. you'll have **OnLoot** function which needs to have player position and info about loots available to find the closest. Then function sends event to the looted item. Looted item in its event process cycle handles this event so item only needs to know how to update itself. **OnLoot** function can also update player inventory or item itself may send **updateInventory**/\**OnLootSucess** event and player/inventory will handle it in its own process events cycle.

Pros: you've decoupled some of your classes

Cons: added events classes, maybe unneeded code overhead.

Here is **one** of the possible ways of how it may look:

```
case LOOT_KEY:
   OnLoot(PLayer->getPos(), &inventoryItems);
....

// note onLoot do not needs to know anything about InvItem class (forward decl in enough)
int onLoot(vec3 pos, InvItems& pitems)
{
    InvItem* pitem = findInRange(pos, pitems, LOOT_RANGE);
    if(pitem)
     EventManager::Instance->post( Event::makeLootEvent(pitem));
}
....

// knows only about EventManager
InvItem::processEvents()
{
    while(!events.empty())
    {
        Event* pev = events.pop();
        ...
        case LOOT_EVENT:
            // in case you broadcasted it, but better is to sort all posted/sent events and add them only if they addressed to particular item
            if(pev->item == this && handleLoot((LootEvent)pev))
            {
                EventManager::Instance->post(Event::makeLootSuccessEvent(this));
            }
    }
}

int handleLoot(LootEvent* plootev)
{
    InvItem* pi = plootev->item;
    if(pi->canLoot())
    {
        updateTexture(pi->icon, LOOTED_ICON_RES);
        return true;
    }
    return false;
}

...
// knows only LootSuccessEvent and player
Inventory::processEvents()
{
    while(!events.empty())
    {
        Event* pev = events.pop();
        ...
        case LOOT_SUCCESS_EVENT:
             player->GetInventory()->add( ((LootSuccessEvent*)pev)->item );
        ...
}

```

This is just one of the possible ways. Probably you don't need so many events. And I am sure you can do better knowing your data, this is only one of many ways.

---
Tags: c++, 2d, architecture, sfml
---


# Question
Title: Circle Collision class not positioning itself correctly
Ok I am using unity3D and the Futile framework. I have everything drawing and working correctly with Futile, but I am trying to attach a circle collision class to the FSprite that I have. I must be missing something but I have tried everything I can think of.

Right now, it positions itself offset from the center of the texture. The picture below shows what I am talking about. (The blue circle filled circle is my round Planet and the red circle is the circle class)

Below is my Planet class constructor

```
public Planet(string texture, Vector2 position, Team team, Level level = Level.One)
    : base(texture)
{
    Debug.Log("Texture Rect width: " + this.textureRect.width.ToString());

    //this.anchorX = .5f;
    //this.anchorY = .5f;
    this.Position = position;
    collision = new Circle(this.textureRect.width / 2, this.Position);
    collision.Position = this.Position;

    FAtlasManager am = Futile.atlasManager;
    levelOneTexture = am.GetElementWithName("Circle.png");
    levelOneTexture = am.GetElementWithName("Planet_1.png");
    levelTwoTexture = am.GetElementWithName("Planet_2.png");
    levelThreeTexture = am.GetElementWithName("Planet_3.png");
    ChangePlanetTeam(team);
    ChangePlanetLevel(level);
    SetPlanetLevelTexture(level);

    float rot = RXRandom.Range(0, 2 * Mathf.PI);
    this.rotation = rot;
}

```

And here is my Circle class

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

public class Circle
{
    private float radius = 1f;
    private Vector2 position = Vector2.zero;
    private Vector2 origin = Vector2.zero;

    public float Radius
    {
        get { return radius; }
        set { radius = value; }
    }
    public Vector2 Position
    {
        get { return position; }
        set
        {
            float x = value.x + Radius;
            float y = value.y + Radius;
            position = new Vector2(x, y);
            //position = value;
        }
    }
    public float X { get { return Position.x; } }
    public float Y { get { return Position.y; } }

    public Circle(float radius, Vector2 position)
    {
        Debug.Log("Circle position: " + position.ToString());
        this.Position = position;
        this.radius = radius;
        Debug.Log("Radius: " + radius.ToString());
    }

    public void DrawRadius()
    {
        Debug.DrawLine(new Vector3(this.X, this.Y, 0), new Vector3(this.X + Radius, this.Y + radius,0));
    }

    /// <summary>
    /// Test if two circles are currently colliding.
    /// </summary>
    /// <param name="a">One of the circles to test</param>
    /// <param name="b">The other circle to test</param>
    /// <returns>True if collision is present</returns>
    public static bool CircleToCircleCollision(Circle a, Circle b)
    {
        return ((a.Radius + b.Radius) > Vector2.Distance(a.Position, b.Position));
    }

    /// <summary>
    /// Test if a certain circle contains a point
    /// </summary>
    /// <param name="a">The circle to test</param>
    /// <param name="point">The point to test</param>
    /// <returns>Returns true if circle contains the point</returns>
    public static bool CircleContainsPoint(Circle a, Vector2 point)
    {
        return a.Radius > Vector2.Distance(new Vector2(a.X, a.Y), point);
    }

    public bool CircleContainsPoint(Vector2 point)
    {
        return Circle.CircleContainsPoint(this, point);
    }
}

```

I guess my collision code could be wrong but I dont believe so. I am passing in a point to determine if the click was inside of the circle.

Perhaps my math is wrong, or i dont understand the Futile coordinate system like I should, but I am at a loss.

I have checked to ensure that the texture I use for the planet is square(128x128), and that the actual circle is perfectly centered.

I can get the circle close but not perfect. There is always a registered click where it shouldnt be.

Also I tried to tag this post with "Futile" but it would not let me due to reputation.

# Answer
Ok so I dont really program in c#. However, I've had this problem once before and realised that I had added the radius of the circle to the x and y position which offsets the collision circle from the circle sprite.

```
 public void DrawRadius()
{
    Debug.DrawLine(new Vector3(this.X, this.Y, 0), new Vector3(this.X + Radius, this.Y + radius,0));
}

```

In your DrawRadius() method you "this.X + Radius"...

If I am not mistaken, this should be "this.X - Radius"

Like this:

```
 public void DrawRadius()
{
    Debug.DrawLine(new Vector3(this.X, this.Y, 0), new Vector3(this.X - Radius, this.Y - radius,0));
}

```

Make sure you apply the "- Radius".

Be aware, I have little to no experience in C#. However, I'm just trying to help :)

Give that a go.
> 1 votes

# Answer
For some reason you are deliberately offsetting the collision circle’s centre:

```
       float x = value.x + Radius;
       float y = value.y + Radius;

```
> 0 votes

---
Tags: unity, physics
---


# Question
Title: How to make my characters turn smoothy while walking on a path(list of coordinates)?
I have a list with coordinates - output from A\* algorithm - and I would like to make my characters smoothly follow this path with rotations.

So I have something like **A** and I want to get **C**

How can I do this ?

**EDIT**

To make myself a little bit more clear:

I am more interested in **smooth turning** as I already know how to walk from one node to another.

**EDIT**

As many people find this useful (me too) I am posting link to Daniel Shiffman's "Nature of code" where he discusses a lot of game AI (and physics) problems e.g. steering behaviours http://natureofcode.com/book/chapter-6-autonomous-agents/#chapter06\_section8

# Answer
If you want smooth paths in a tile-based environment, there's no way around applying some *path-smoothing* on your A\* waypoints. In his book about programming game A.I., Matt Buckland describes a simple and fast algorithm to smooth a path (basically remove all edges that can be removed without causing an intersection with your obstacles).

Once you have remove unnecessary edges like this, your first case (**A -\> B**) is solved. Smoothing out the edges in your graph could be accomplished in several ways. Most likely, Hermite splines would work (depending a bit on your obstacle density and tile-size). Another option could be steering behaviors, where you start to steer towards the next waypoint, as soon as you're half a tile away from the current target (this really depends on how fast your "agent" moves/turns).
> 7 votes

# Answer
As others have mentioned, for the second case you will need to implement some sort of spline or (actually a better fit for your example) give the unit some sort of steering behavior.

However, for the first case, there is a solution that is both simpler and gives better results than path smoothing. It's called Theta\*, and is a simple *(and relatively new)* extension of A\* on grids that allows units to move in any direction between grid-points.

There is a nice article explaining Theta\* (from which I stole the above image) here
> 9 votes

# Answer
To a more human realistic movement, try integrating with SharpSteer, a C# version of the classic OpenSteer.

You get the output of A\* (A star) and let the steering behavior care about the movement; one of the samples show exactly how to do this, navigate following a path.
> 2 votes

# Answer
I've had good luck with Catmull-Rom splines (a type of cubic spline as also recommended by @bummzack). The good part about those is that the spline will always go through the control points, many others do not. Implement something like this:

```
t    = <time*>
t12  = t + 1.0
t23  = t
t34  = t - 1.0
t123 = (t + 1.0) / 2.0
t234 = t / 2

c1 = controlpoint[0];
c2 = controlpoint[1];
c3 = controlpoint[2];
c4 = controlpoint[3];

l12 = lerp(c1, c2, t12);
l23 = lerp(c2, c3, t23);
l34 = lerp(c3, c4, t34);
position = lerp(lerp(l12, l23, t123), lerp(l23, l34, t234), t);

```

***time** is a value \[0,1\] between the control points 1 and 2.
> 2 votes

# Answer
In case of navigation from point to point, I used the difference in angles (current player direction vs. direction from current point to next point) and then gradually changed the angle to final angle as the movement happens. Check this game here where the airplanes move from 1 point to another but the turn is not abrupt but on watching carefully one can identify the points of the path. (the game works only on mobile though preferably iPhone/iPad).
> 1 votes

# Answer
A-\>B can be solved by using navigation meshes instead of a grid. This implies a big change in pathfinding data generation.

Cases like C and D are just corner cutting: if character is moving in a path and inside a "corner" (cell where previous, current, next cells are not on a straight line), push it in direction of both previous and next cell. The only problem is to determine the distance from real position (the pushing distance). That would probably require the distance from current cell as input. Something like this:

```
push_dir = average( prevcell.pos, nextcell.pos ) - curcell.pos;
push_dist = cell_half_width - distance( char.pos, curcell.pos );
char.pos += push_dir * push_dist;

```
> 0 votes

---
Tags: c#, unity, path-finding
---


# Question
Title: Android ndk-build can't find glm headers
I am trying to port some boilerplate code of mine to work on android, using the android ndk & NativeActivity

So far I have just one file that defines the glue between android and my code and it works fine. It includes one GLIncludes file, that sorts out the includes based on platform

However, if I add glm headers to the GLIncludes file, becoming:

```
#ifdef __ANDROID_API__
    #include <EGL/egl.h>
    #include <GLES/gl.h>
    #include <GLES/glext.h>
#endif

#include "glm/glm.hpp"
#include "glm/gtc/matrix_transform.hpp"
#include "glm/gtc/type_ptr.hpp"

```

ndk-build then complains about not finding glm.hpp:

```
In file included from jni/src/GLIncludes.h:41:0,
                 from jni/androidLauncher.cpp:4:
jni/src/glm/glm.hpp:86:18: fatal error: limits: No such file or directory

```

I have verified that the file does indeed lie at **\< ANDROID\_PROJECT\_ROOT \>/jni/src/glm/glm.hpp** so what could be the problem?

Here is my **Android.mk** file that sits in the jni folder:

```
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE    := libglobes
LOCAL_CFLAGS    := -Werror
LOCAL_LDLIBS    := -llog -lGLESv1_CM -lEGL -lm -landroid
LOCAL_CPP_EXTENSION := .cpp
LOCAL_STATIC_LIBRARIES := android_native_app_glue

LOCAL_SRC_FILES := androidLauncher.cpp

include $(BUILD_SHARED_LIBRARY)

$(call import-module,android/native_app_glue)

```

My directory structure is:

```
< ROOT >
    src/ (dir with all sources in it)
        GLIncludes.h
        glm/
            glm.hpp
    android/ (base dir for android port)
        jni/
            androidLauncher.cpp
            Android.mk
            src/ (symbolic link to upper src folder with same contents)

```

So why is the ndk-build not seeing the glm.hpp files? Is it because it is too deep? or is it because of the symbolic link? Or is it something else completely?

Thanks

# Answer
You need to read the error message more carefully:

```
In file included from jni/src/GLIncludes.h:41:0,
                 from jni/androidLauncher.cpp:4:
jni/src/glm/glm.hpp:86:18: fatal error: limits: No such file or directory

```

As you can see, the `glm.hpp` header **is** found. It's `limits` that is not found, because by default the NDK uses a stripped-down C++ runtime library.

You will need to read `CPLUSPLUS-SUPPORT.html` to choose what kind of runtime is best for you. In the meantime, adding this to `Application.mk` will probably work:

```
APP_STL := gnustl_static

```
> 4 votes

---
Tags: android, ndk, glm
---


title: SDL2 focus lost = massive gain in FPS

text:
# Question
Title: SDL2 focus lost = massive gain in FPS
Whenever I lose focus from my game window, I go from ~60FPS to 6000+, then when the window gains focus again, I go back to around 60 frames per second. And yes, this happens every time I run my game, including Release mode.

Here is an example log output from my game:

```
[INFO] [10/01/2013 22:37:42.355] Window Gained Focus!
[INFO] [10/01/2013 22:37:45.365] Frames Per Second: 60.0439
[INFO] [10/01/2013 22:37:45.365] Frame Counter: 60
[INFO] [10/01/2013 22:37:46.365] Frames Per Second: 60.0324
[INFO] [10/01/2013 22:37:46.365] Frame Counter: 60
[INFO] [10/01/2013 22:37:47.381] Frames Per Second: 59.4341
[INFO] [10/01/2013 22:37:47.382] Frame Counter: 58
[INFO] [10/01/2013 22:37:49.669] Window Lost Focus!
[INFO] [10/01/2013 22:37:50.383] Frames Per Second: 1240.02
[INFO] [10/01/2013 22:37:50.383] Frame Counter: 9561
[INFO] [10/01/2013 22:37:51.384] Frames Per Second: 1839.02
[INFO] [10/01/2013 22:37:51.384] Frame Counter: 6662
[INFO] [10/01/2013 22:37:52.77] Window Gained Focus!
[INFO] [10/01/2013 22:37:52.400] Frames Per Second: 1656.77
[INFO] [10/01/2013 22:37:52.400] Frame Counter: 34
[INFO] [10/01/2013 22:37:53.400] Frames Per Second: 1512.46
[INFO] [10/01/2013 22:37:53.400] Frame Counter: 60
[INFO] [10/01/2013 22:37:54.401] Frames Per Second: 1391.89
[INFO] [10/01/2013 22:37:54.402] Frame Counter: 60
[INFO] [10/01/2013 22:37:55.402] Frames Per Second: 1289.78
[INFO] [10/01/2013 22:37:55.402] Frame Counter: 58
[INFO] [10/01/2013 22:37:55.876] Quitting with error code: 0

```

The frame counter is just a simple integer that I increment every loop in the game, and then reset (and print it out) every second. Here is the implementation of my game loop, (inside the run() function), based off of this article.

Is this a problem with my loop, or is this a problem with SDL? I'm not sure why my frame rate is rocketing up.

# Answer
60 fps in focus mode is very suspicious, it must be vsync.

Why vsync is turned off when the app loses focus is not a question I can answer though.
> 6 votes

---
Tags: c++, sdl, game-loop
---


# Question
Title: How to handle entity path-finding and movement in a large networked world?
Considering the image above with tiles split into 32x32 boxes, I have an entity which is marked to 'aggro' nearby players that come close to it. I'd like this monster to ideally chase the player (and continue to chase the player for a while). Currently, my only movement is done my a simple interpolator for remote entities and this works because the gaps between movement updates are rather small.

I can't successfully just tell the client that the monster wants to move to the position he/she is at, as that will cause the entity move much faster than it should (this can probably be solved with using some math for the interpolation co-efficent) but more importantly it does not look realistic and may clip walls! I don't want to simulate the entire movement on the server if it can be avoided... although I guess I could but that still wouldn't solve the clipping issue. I suspect the solution involves some path-finding and sending the client periodic node updates and letting them simulate the movement but I'm unsure.

Thanks!

# Answer
For a simple start you can implement steering behaviors. Specifically seek behaviors.

In addition to seeking the characters should use avoidance to steer away from obstacles.

Once you have those aspects working, you can implement some more intelligent following. That would include path finding. Now instead of steering towards their foes, enemies will steer towards each node on the path that leads them to their target.

Once the enemy gets "close enough" you can switch over to entirely steering behaviors. Since they're less expensive than path finding, and you'll get results that are good at close range.

Steering will also allow you to define maximum turn speeds and maximum speeds for enemies.

Steering can be managed on the client with periodic updates from the server to ensure they're still on track.
> 9 votes

# Answer
> I can't successfully just tell the client that the monster wants to move to the position he/she is at, as that will cause the entity move much faster than it should (this can probably be solved with using some math for the interpolation co-efficent)

Actually this is simple to do. The direction of movement will be the target position minus the current position. All you need to do is scale that vector down to the movement speed you actually want. Repeat every frame.

> but more importantly it does not look realistic and may clip walls! I don't want to simulate the entire movement on the server if it can be avoided...

You need to simulate the movement on the server. How else will you know that all players are seeing the same behaviour?

You will need some basic pathfinding. A\* is the standard. You can calculate a path to the target and then following that path is simply a case of setting movement vectors as above. (Or you can use steering behaviours as in Byte56's answer, which is essentially the same thing with some added extras.)
> 1 votes

---
Tags: ai, networking, path-finding, movement, entity
---


# Question
Title: Flow/design of steering behaviors implementation
I am implementing some simple steering behaviors like: follow the leader, separation, cohesion and flee(from the leader when he walks in our direction - aka spread the group for him).

I am having issues with design of this system. I know how each of this behavior works separately but I simply can't do it with "if ladder" (as I did up to know). Can someone lead me on how to concatenate/normalize/multiply the forces and how to join them in one resultant force ?

**EDIT**

What I am exactly talking about is: for now I have something like so :

```
if(leaderGoingAtMe)
    makeSpaceForhisMovement()
else if(followTheLeader)
    goto(positionBehindLeader)

if(separation)
    addSeparationForce()
if(cohesion)
    addCohesionForce()

if(velocity > maxSpeed)
    clamp(velocity, maxSpeed)

```

Which is EXTREMELY bad in my opinion but I have no idea how to improve it.

# Answer
> 3 votes
Add all the relevant forces together. Clamp them at the end to a maximum acceleration rate for that agent. Then you're done.

# Answer
> 2 votes
This comes up in AI fairly often. I think what you are looking for is a way to keep your State Machine organized.

Assuming you are using an object-oriented language, the general idea is to represent each of those actions that your *agent* can do as a state Object, with a defined entry and exit methods that leads into other states. You're most likely going to have a "parent" AI controller that they can ask to transition over into what state they want to be in next.

You can then update your vectors accordingly. Instead of doing those state-based if statements, it might be a better approach to store all of the vectors that your states *can* update, and then apply those during a regular update cycle.

With respect to Steering Behavior, any number of recent books will have them showcased as an example of using an object-oriented state machine, Mat Buckland's Programming Game AI by Example and Ian Millington's Artificial Intelligence for Games come to mind.

---
Tags: architecture, steering-behaviors
---


title: Graphics not being displayed on OUYA

text:
# Question
Title: Graphics not being displayed on OUYA
I hope its not too early to be asking OUYA dev questions, but I just got my dev kit and I want to get my game running ASAP! I am using LibGDX as my framework for my game and launching the Android backend on the OUYA. Everything seems fine except that none of my graphics are being displayed! I can only tell what's going on because of Box2D's DebugDraw showing my physics. I am using LibGdx's Spritebatch and OpenGL ES 2.0. Everything is working pefectly on my desktop and Android (phone) backends.

Am I doing something wrong with handling my resources for OUYA? What could be the problem? Could this be because I store my graphics in the assets folder instead of /res?

Edit: Here's a logcat output: http://pastebin.com/BbPyPCcR

# Answer
I don't know much about ouya but seeing the log,

```
01-02 07:09:21.490: W/PackageManager(305): java.lang.NullPointerException

01-02 07:09:21.490: W/PackageManager(305):      at android.app.ApplicationPackageManager.putCachedIcon(ApplicationPackageManager.java:782)

01-02 07:09:21.490: W/PackageManager(305):      at android.app.ApplicationPackageManager.getDrawable(ApplicationPackageManager.java:618)

01-02 07:09:21.490: W/PackageManager(305):      at android.content.pm.PackageItemInfo.loadIcon(PackageItemInfo.java:140)

```

Suggests a wrong location of images. Recheck that the url is not null.
> 4 votes

# Answer
are you sure the image is where it should be? maybe that's why the desktop project works and ouya's doesn't

also how come it gives you an exception but you can still see things on the box2d debug? what happens if you disable the drawing of box2d debug?

gl if your doing the jam and I hope you'll solve this fast
> 0 votes

---
Tags: java, android, libgdx, ouya
---


# Question
Title: How to implement rotating Earth effect in 2D?
I've modeled a photorealistic scene of the Earth rotating in 3DS Max and would like to use it as a backdrop of a menu screen in a 2D game. What would be the appropriate way to implement this effect in-game, a sprite sheet? That seems like it would require a whole mess of frames to appear convincing. Does that matter?

What if I then wanted to add the moon orbiting the Earth? A second sprite sheet for the moon's positions, with blank frames where it should be hidden behind the Earth?

Is there a better method?

# Answer
So long as your staying in 2d, tons of frames is pretty much the only reliable option, you could try to use a video codec in your program, but I've seen that's usually way more trouble than its worth if you want to do it for free.

Frankly the best way to avoid using the frames method is make your game in OpenGL or DirectX and simply import the planet models straight from 3ds Max and just have them sit in the background, but if you have no experience at all in 3D graphics API's then you're pretty much stuck with animating loads of frames.
> 5 votes

# Answer
Well, you could render the entire earth, and then draw it rotated to a clip rectangle if you wanted a smooth animation with more flexibility. And, you could do the same for a moon and then use sin/cos to make an arcing path around the earth. There's a few other things you could do like separating the land from the water on the earth and animate those separately. It depends on how you want it to look and how much memory you want your textures to take up.
> 2 votes

# Answer
You don't specify how precise you need this Earth visual to be. If you don't need a "perfect" Earth render, consider the implementation at 3D Illusion of a 2D Planet Texture
> 2 votes

# Answer
Save as video is another option, and play it in menu.
> 1 votes

# Answer
You didn't specify what 2d means exactly in your situation. If you're doing 2d in a 3d engine, you could just render the planet with an ortographic projection.

If you don't want to do that, but you can still render 2d shapes with custom texture coordinates and shaders, here's an idea (although a little complicated):

1. At asset build time create a 2d projection of your 3d earth
2. save it as a 2d shape, and (most important) save the texture coordinates
3. render your 2d shape in the background with a custom shader and use texture scrolling to move your texture on it, creating a rotation effect. Since you're using the results of a projection, the texture coordinates will guarantee the proper distortion.
> 0 votes

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


# Question
Title: DirectX9 fullscreen, render immediately?
Is it possible, somehow to avoid the single frame of black that appears before a DirectX9 window is displayed in fullscreen? My code looks like this.

````
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
WNDCLASSEX wc = { sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle( NULL ), NULL, NULL, NULL, NULL, L"D3D", NULL };
RegisterClassEx( &wc );
LPDIRECT3D9         pD3D = NULL;
LPDIRECT3DDEVICE9   pd3dDevice = NULL;
int                 windowWidth = 1280;
int                 windowHeight = 1024;
int                 adapter = 3;
bool                fullscreen = true;

if( NULL == ( pD3D = Direct3DCreate9( D3D_SDK_VERSION ) ) )
    return E_FAIL;

HWND hWnd = CreateWindow( L"D3D", L"D3D Test", WS_VISIBLE | WS_POPUP, 0, 0, windowWidth, windowHeight, NULL, NULL, wc.hInstance, NULL );

D3DDISPLAYMODE d3ddm;
pD3D->GetAdapterDisplayMode( adapter, &d3ddm );

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );

d3dpp.Windowed               = !fullscreen;
d3dpp.SwapEffect             = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat       = d3ddm.Format;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval   = D3DPRESENT_INTERVAL_ONE;
d3dpp.BackBufferCount        = 1;
d3dpp.BackBufferWidth        = windowWidth;
d3dpp.BackBufferHeight       = windowHeight;
d3dpp.hDeviceWindow          = hWnd;

if( FAILED( pD3D->CreateDevice( adapter, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &pd3dDevice ) ) )
{
    return E_FAIL;
}

MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
    pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB( 255, 255, 255 ), 1.0f, 0 );
    pd3dDevice->Present( NULL, NULL, NULL, NULL );

    if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }
}

if( pd3dDevice != NULL )
    pd3dDevice->Release();

if( pd3dDevice != NULL )
    pd3dDevice->Release();

UnregisterClass( L"D3D", wc.hInstance );
return 0;

````

`}`

# Answer
> 2 votes
If you're referring to the fact that the screen may go black for a second or two during a switch to fullscreen\[\*\] and before the scene is actually displayed following the switch, then you will very likely not be able to remove it. Changing to a fullscreen mode may involve a video mode change for your display device, and if this needs to happen then the black frame is just part of the normal video mode change process - you'll see the same if you e.g. change the screen resolution using your display control panel (which this is effectively identical to).

It's possible to sometimes avoid the need for this to happen if the fullscreen mode you're using is identical in all respects to the current display mode, but there's another catch - with Vista or higher a switch to fullscreen will also disable the DWM, which also causes a frame of black.

So this isn't a problem with your code and there's nothing you can do in code to avoid it - it's a property of your OS and display driver.

There is however one workaround, and that's to not use a fullscreen mode. Instead create a windowed mode at your desktop resolution, but use no title bar/borders/etc on the window. Of course that will run a little slower compared to a true fullscreen mode, but it may not matter if you're already running fast enough.

\[\*\] - when I say "switch to fullscreen" you may assume that I also mean "starting in a fullscreen mode" here.

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


# Question
Title: 2D destructable terrain with collisions in MMO
### Task

What I want is to create destructable terrain (like in Worms) and collisions with this terrain (with calculated normals) that will be fast enough to work on server machine.

Basically lets say that I want to make Worms Online (I don't really) using model CLIENT-SERVER, not peer2peer.

### Approaches I read about

* People in other threads were suggesting using bitmaps and perpixel collisions, but is it fast enough to handle i.e. 100 games simultaneously?
* Another approach is using vectors to track outline of terrain, but it seems also really CPU heavy and I didn't find any good example of that.

### So guys what is your proposal?

# Answer
> 5 votes
One good option is to use something larger than pixels and use marching squares to create smooth terrain. The server and client only talk to each other in grid terms, thus reducing bandwidth. The client is responsible for running marching squares and interpolating the grid into a smooth terrain. However, all the collisions and terrain interactions use that grid for their calculations, making them faster.

Additionally, this allows you to easily test the performance of one size square and easily scale the squares up or down depending on where you find your performance. For example, create a grid that's 5X pixel size. Test the performance, if it's good, scale the grid down to 3X pixel size for smoother terrain and more accurate collisions.

As an example, there's a Ludum Dare game from a while back that used marching squares for destructible terrain:

As you can see, the result is fairly smooth terrain. A change in textures could help if you wanted something more realistic looking without the dark outlines.

# Answer
> 2 votes
> People in other threads were suggesting using bitmaps and perpixel collisions, but is it fast enough to handle i.e. 100 games simultaneously?

I think there is a middle approach here where you can use Client-Server, but you let your clients do all the hard work, and keep them in sync using an arbitrating server.

The basic premise is that instead of doing all the work on the server, you capture client input and broadcast it to all the other clients. This is the premise behind most RTS games (and people frequently mistake them as being peer-to-peer, where in fact one of the players runs a server inside their game instance).

Since Worms is turn-based, there are no real-time requirements, which gives you plenty of CPU time between turns to ship some packets. You can have the clients transmit their last frame state to the arbitrating server. If any of the clients has mismatching data, the game is out of sync and you can drop it completely.

This gives you several benefits:

1. You can have a lot of games running off of a basic machine, because it isn't doing any heavy lifting.
2. You still have a client-server architecture.
3. Cheating in a synced game like this is near impossible.
4. You can go so far as to store *replays* if you want to.

In the end, the way you implement the terrain breakage doesn't really matter. You can use bitmaps and stencils, or vector fields. It's handled on the client-side.

The discussion is hidden in comments, so lets do a basic example here.

## Regular Example

We have a game with 3 players, *A*, *B* and *C*, and the Arbitrating Server, *AS*

1. Game Frame is started.
2. Player *A* selects their weapon, and their angle. They fire, and a "Fire" packet is sent with (WeaponId, Angle, Amount of Power) data.
3. *AS* receives this packet, sends it to all other players.
4. Players *B* and *C* simulate the game as well.
5. Player *B* is shot, so their worm is moved elsewhere, the position has changed.
6. All players send the state of the worms, what weapons they have, their position and their facing to the *AS*.
7. *AS* confirms that the data is the same from all the players, so players are in sync. This frame is concluded, and a new frame starts.

## Cheating Example

Now what would happen if *A* was cheating and modified the number of ammo they had?

1. Game Frame is started.
2. Player *A* changes the number of rockets they have from 0 to 10.
3. Player *A* selects the Rocket weapon, and their angle. They fire, and a "Fire" packet is sent with (WeaponId, Angle, Amount of Power) data.
4. *AS* receives this packet, sends it to all other players.
5. Players *B* and *C* try to simulate the game, but notice that *A* has no ammo. They send this discontinuity to the *AS*.
6. *AS* broadcasts an "Out of Sync" message, and the game is terminated.

Keep in mind that this is a simplified look at how it works, but the premise always remains the same.

---
Tags: collision-detection, mmo, python, terrain, client-server
---


# Question
Title: How to run Minecraft from a different folder
My problem is that I can run minecraft from a different folder, but when I run it, it is still using .minecraft folder. It saves the worlds there and so on. How can I run it like "everything get from and save to my folder"? I heard you can mod it to run from somewhere else, but I did not found it anywhere.

```
        public static string generateSession(string username, string password, int clientVer)
    {
        return httpGET("https://login.minecraft.net?user=" + username + "&password=" + password + "&version=" + clientVer);
    }

    private static string httpGET(string URI)
    {
        WebRequest req = WebRequest.Create(URI);
        WebResponse resp = req.GetResponse();
        StreamReader sr = new StreamReader(resp.GetResponseStream());
        return sr.ReadToEnd().Trim();
    }

    public static void startMinecraft(bool mode, int ramMin, int ramMax, string username, string sessionID, bool debug, int modpack)
    {
        string appPath = Path.GetDirectoryName(Application.ExecutablePath) + @"\";
        string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\";
        string mcFolder;
        //Launching a modpack
        if (modpack == 0)
            mcFolder = @".gslauncher\vanilla";
        else mcFolder = @".gslauncher\gstech";
        Process proc = new Process();
        if (debug == true)
            proc.StartInfo.FileName = "java";
        else
            proc.StartInfo.FileName = "javaw";
        //Online and offline modes
        if (mode == true)
            proc.StartInfo.Arguments = "-Xms" + ramMin + "m -Xmx" + ramMax + "m -Djava.library.path=" + appData + mcFolder + "/bin/natives -cp " + appData + mcFolder + "/bin/minecraft.jar;" + appData + mcFolder + "/bin/jinput.jar;" + appData + mcFolder + "/bin/lwjgl.jar;" + appData + mcFolder + "/bin/lwjgl_util.jar net.minecraft.client.Minecraft " + username + " " + sessionID;
        else
            proc.StartInfo.Arguments = "-Xms" + ramMin + "m -Xmx" + ramMax + "m -Djava.library.path=" + appData + mcFolder + "/bin/natives -cp " + appData + mcFolder + "/bin/minecraft.jar;" + appData + mcFolder + "/bin/jinput.jar;" + appData + mcFolder + "/bin/lwjgl.jar;" + appData + mcFolder + "/bin/lwjgl_util.jar net.minecraft.client.Minecraft " + username;
        proc.Start();
    }

```

# Answer
> 2 votes
The Minecraft modding forums is probably the best place to get answers like this. Searching there is your best bet and you can likely find the answer. I did a search there and found that someone had asked this question already. It looks like the best way is to use Magic Launcher. If you want to do it through code, I suggest you ask the question over there.

---
Tags: c#, minecraft-modding
---


# Question
Title: Should I use OpenGL, Direct3D, OpenGL ES, or WebGL?
Let's say I *don't* want to make a game. I specifically want to mess around with a low-level 3D graphics API, because I'm bored and I want to learn something new. I want to work on programming problems with a strong visual component (something like this), because I'm a visual thinker and I like visual problems.

So I spend a few hours on Google, and what the heck? What's all this nonsense about fixed-function and programmable pipelines? Why are there so many darned API choices? What if I have an integrated Intel card that only supports OpenGL 2.1, but for some reason supports Direct3D 10, which is apparently the better "programmable" version? I like the Linux command line, but should I switch over to Windows because of D3D10? You're saying that I can do OpenGL ES graphics programming on my smartphone?

What should I use, given my circumstances of wanting to learn low-level 3D graphics and having an integrated Intel card? There are too many choices, and I honestly don't know what to research.

# Answer
> What should I use, given my circumstances of wanting to learn low-level 3D graphics and having an integrated Intel card? There are too many choices, and I honestly don't know what to research.

This was mentioned before but the gist of the matter is - it doesn't matter which 3D API you use, the underlying operations are mostly the same and thus they conform to a similar interface, whether it be OpenGL or Direct3D.

If you would like to learn 3D graphics programming regardless of the API, there are plenty of books that pick either OpenGL or Direct3D, and go over the concept and show how to apply it to that API.
> 3 votes

---
Tags: 3d, graphics
---


# Question
Title: Passing information between states created at different times
I have two states, a configuration state and a gameplay (simulation) state.

After configuring the game details (gametype, scoring type, win condition, etc. etc.) As each state is isolated, what is a good way to pass this data to my simulation state which will be created later?

Currently I'm storing configuration details in static variables of the gameplay class. Then upon creation--the gameplay class is copying that into it's internal configuration. This seems sloppy. Could I be doing something better?

# Answer
> 2 votes
define a GameParameter class and send it from config to game class.

```
myNameSpace.GameParameter= function(score, level, gun, ...) {
    this.score=score;
    this.level=level;
    ...
 }

```

then you must implement in all your state class getGameParameter() and setGameParameter(params) OR have a startRunLoop(params) depending on how you manage the state change.

(tell me if i'm not clear).

# Answer
> 2 votes
Personally, I've got a game object which holds data I want to be persistent between states, like configuration variables (e.g. gravity, difficulty, e.t.c...), player data, camera data and a world object (which in turn holds terrain, characters and other stuff).

I pass this game object to the current game state object and query it for the data I need from within the state object, e.g.

```
foostate::on_update(game* g){
    //I'm totally interested in knowing the current gravity...
    print(g.gravity);
}

```

In my main method, I have a variable that holds the game object and in my game loop, I call the update function of the current state, passing the game object as a parameter.

This way, I can e.g. set my game to a pause state, but still draw the current view.

In addition to this, being able to save/load the current coniguration to/from a text file makes life easier, because you can just load the configuration instead of having to configure everything whenever you (re-)start the game.

# Answer
> 2 votes
If you're dealing with small games, this is somewhat inconsequential, as a finished game is better than a well-engineered game.

That said, if you're already finding yourself wishing that you could switch back and forth between screens, or set an option on one screen which propagates to another screen, afterwards, then I'd suggest looking into something like a `"Mediator" / "Moderator"` pattern.

The idea is that you have one system-wide object (or domain-wide object), which can be called by all members of that system/domain.

You can `subscribe/listen/"on" + <event>` to this object.
When that happens, you register a method or a function to use as a callback, to act on parameters passed in with the notification.

```
var system = Moderator(),

    player = Player(),
    scoreboard = Scoreboard();

system.listen("register-player", scoreboard.register);
system.listen("player-kill", scoreboard.add_point);

player.suicide(); // system.notify("player-kill",
                  //               /* dead-player */ player.id,
                  //               /* killed-by   */ player.id  );

```

Now, instead of finding ways of tying everything together, you're dealing with custom events, the names of which you name, followed by agreed-upon types and numbers of function parameters...

The disparate parts don't know anything about one another.
So when you make a multiplayer character, you might use a moderator as a way of registering to receive network updates.
If you kill that multiplayer character, it doesn't really need to update its network position any more, so you can unregister it from the moderator.

A player character who gets knocked-out or stunned for a short time might also be unregistered from receiving controller updates.
Once your components are this loosely coupled there are all kinds of things you can do.

You might also have, say, an achievement system and a goodie-unlock system which listen for your kills, and unlock after you reach X.
Now, instead of having to be hard-coded into the middle of your player class, they can just listen to the same moderator, to be notified of the same event.

You could also have multiple moderators...

For component-based stuff, this is usually the half-way between OOP and 100% entity-system.
For example, you might have every player have their own internal moderator.
That moderator might be the talking point between each of the components (like when a control tells the movement to jump, tells the skeleton to change animations, tells the IK-engine to blend the jump in with whatever you were doing, etc)...

...and then the player might be given access to a "global" moderator (or one which manages ALL players).

And that moderator would handle all communication from the player(as a whole) as it needed to be broadcast to the outside world.

---
Tags: architecture
---