title: How to implement a tractor beam?

text:
# Question
Title: How to implement a tractor beam?
I'm working on a game where the player can pick up objects using something like a tractor beam, and carry them around.

Attracting the object towards the center of the beam is not difficult. But once the object is close enough to the center, I need to keep it there while the player moves, which is what I'm having problems with. I can think of two ways to do it, and both have issues:

1. Update the object's position whenever the player position changes, keeping it centered on the beam.
2. Update the object's velocity to point directly towards the center of the beam, the further away, the more velocity.

Moving and rotating works just fine with both approaches, but the physics are wrong when the carried object collides with other objects:

With the first approach, physics are completely ignored. The carried object just pushes anything out of the way. That is because position changes are only supposed to be done as part of the world physics, based on velocity.

With the second approach, physics basically behave how they should, but overreact. The problem is: In order to keep the carried object at the center of the beam even when rotating and moving, I need to use high velocity values. So once the carried object touches another one, it gets way too much velocity from the collision.

How can I implement this properly? My best guess right now is to go with the second approach and add special handling for carried objects to the world physics, reducing the velocity to sane values for collisions or when the player stops carrying them. But that seems like a pretty inelegant workaround.

**Edit:** Adding some pseudo code to illustrate how it works right now (that'd be the second approach above)

```
void attract_object(object, ticks) {
    Vector distance = beam_center - object.center;
    // If the object is not close to the beam center, attract it slowly
    if (magnitude(distance) > 10) {
        object.velocity += distance.normalized() * ticks * 0.1;
        return;
    }

    // Here comes the part we're talking about. That magic 0.5 is just high enough
    // that the object isn't lost while moving around. But it's still so high that
    // other objects are repelled with way too much force.
    object.velocity = distance * ticks * 0.5;
}

```

From what I see, this happens when the carried object pushes another object away:

1. The carried object collides with another object
2. The objects' velocities are distributes properly, so the carried object is pushed away from the center of the beam in the process
3. The code above causes the carried object to return to the center of the beam, with so much velocity that it'll get back there quickly
4. When the carried object moves back towards the center of the beam, half of its high velocity is transferred to the other object, repelling it violently. Since the initial velocity of the carried object appears to be sane, I can imagine that steps 2 to 4 are repeated multiple times, building up such a high velocity.

That appears to be the cause. I can't think of a nice way to fix it though :(

# Answer
> 1 votes
Essentially what you are looking for is have the 'beamed' object behave exactly as if you would grab it with your hands.
One option would be to make it share the acceleration a/o speeds of the 'hand' that holds it instead of adjusting its velocity to fill the gap with the center of the beam.

Let's say the center of the beam is the holding hand. if your character rotates 90 degrees to his left in 1 second, then the velocity of the hand would be:

`If R = length of the arm: which is the radius of the rotation circle
R^2 *PI /4 would be the distance traveled over a second.` make it times the elapsedTime of the frame to find the speed you must apply to your object. Find the horizontal normal to the beam to find its direction vector.

My point is that you don't have to solve problems if you try other implementations that wont cause it in the first place.

I would go play with the gravity gun in HL2 to get some inspiration on the problem, but i have other plans for today.

EDIT: im sorry i thought it was for a 3D beamgun, but its essentially the same thing with 2D except the axes are different (and there is no complex geometry)

# Answer
> 4 votes
How about adding a spring connection, i.e. force the object carried to move back to the carry position based on the distance, but still allow it to be pushed away by solid things (like walls).

Constantly adjust the carried object's velocity (by changing acceleration based on position/distance) to point towards the position of the tractor beam (i.e. your second approach). If the object is pushed away too far, drop the connection (and the object).

I'm not really sure why you'd need high velocities. Especially the "player lets go" case would indicate that your rotation velocity might be too high or unrealistic. Also don't forget things such as air resistance and gravity.

---

**Edit:** Considering the updated code, the problem is rather trivial to find:

```
if (magnitude(distance) > 10) {
    object.velocity += distance.normalized() * ticks * 0.1;
    return;
}

```

The problem here is the case where the object's distance to its goal position is constantly too far (i.e. `> 10`). As long as this condition is true, it's velocity simply increases over and over again (i.e. indefinitely).

Two possible solutions for this:

*Define a maximum velocity:*

```
object.velocity = min(object.velocity + distance.normalized() * ticks * 0.1, max_velocity);

```

*Apply a fixed velocity rather than accelerating:*

```
object.velocity = distance.normalized() * ticks * magic_factor;

```

Just accelerating while being too far away is definitely a wrong approach here. Thing about pulling a spring or rubber band: It won't matter whether you hold it for one second or one minute. In the end it will accelerate the same way (considering it hasn't been in motion and there are no other forces applied).

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


# Question
Title: Using different shaders on the same model at runtime
I've already asked similar but a bit unclear question here but this time I will be very specific and to the point.

Suppose I have an actor which grabs a power up. He starts to glow using bloom shader and after 10 seconds back to normal attaching the default shader again. The question basically boils down to:

***How to use different shaders on the same model at runtime?***

Consider following very simple example: **Default shader:**

```
attribute vec4 Position;
uniform mat4 ModelViewProjMatrix;

void main(void)
{
    gl_Position = ModelViewProjMatrix * Position;
}

```

Render code inside RendererGLES20 will be:

```
void RendererGLES20::render(Model * model)
{
    glUniformMatrix4fv(mvpUniform, 1, 0, &mvpMatrix);
    GLuint positionSlot = glGetAttribLocation(_program, "Position");
    glEnableVertexAttribArray(positionSlot);

    // interleaved data, But for now we are ONLY using the positions, ignoring texture, normals and colours.
    const GLvoid* pCoords = &(model->vertexArray[0].Position[0]);
    glVertexAttribPointer(positionSlot, 2, GL_FLOAT, GL_FALSE, stride, pCoords);

    glDrawArrays(GL_TRIANGLES, 0, model->vertexCount);

    glDisableVertexAttribArray(positionSlot);
}

```

Simple enough! Now imagine that the actor got some power up and following crazy shader is applied:

**Crazy Shader:**

```
attribute vec4 Position;
attribute vec4 SourceColor;
attribute vec2 Texture;
attribute vec4 Normal;
attribute vec2 tempAttrib0;
attribute vec2 tempAttrib1;

// A bunch of varying but we don't need to worry about these for now
varying vec4 .........;
varying .........;

uniform mat4 MVPMatrix;
uniform vec2 BloomAmount;
uniform vec2 BloomQuality;
uniform vec2 BloomSize;
uniform vec2 RippleSize;
uniform vec2 RippleAmmount;
uniform vec2 RippleLocation;
uniform vec2 deltaTime;
uniform vec2 RippleMaxIterations;

void main(void)
{
    // Some crazy voodoo source code here...
    // .........
    gl_Position = ..............;
}

```

As you can clearly see, in order to attach this shader to the model I would need to modify the actual **renderer source code** to following:

```
void RendererGLES20::render(Model * model)
{
    glUniformMatrix4fv(mvpUniform, 1, 0, ....);
    glUniformMatrix4fv(bloomAmountUniform, 1, 0, ....);
    glUniformMatrix4fv(bloomQualityUniform, 1, 0, ....);
    glUniformMatrix4fv(bloomSizeUniform, 1, 0, ....);
    glUniformMatrix4fv(rippleSizeUniform, 1, 0, ....);
    glUniformMatrix4fv(rippleAmountUniform, 1, 0, ....);
    glUniformMatrix4fv(rippleLocationUniform, 1, 0, ....);
    glUniformMatrix4fv(rippleMaxIterationsUniform, 1, 0, ....);
    glUniformMatrix4fv(deltaTimeUniform, 1, 0, ....);

    GLuint positionSlot = glGetAttribLocation(_program, "Position");
    GLuint sourceColorSlot = glGetAttribLocation(_program, "SourceColor");
    GLuint textureSlot = glGetAttribLocation(_program, "Texture");
    GLuint normalSlot = glGetAttribLocation(_program, "Normal");
    GLuint tempAttrib0Slot = glGetAttribLocation(_program, "TempAttrib0");
    GLuint tempAttrib1Slot = glGetAttribLocation(_program, "TempAttrib1");

    glEnableVertexAttribArray(positionSlot);
    glEnableVertexAttribArray(sourceColorSlot);
    glEnableVertexAttribArray(textureSlot);
    glEnableVertexAttribArray(normalSlot);
    glEnableVertexAttribArray(tempAttrib0Slot);
    glEnableVertexAttribArray(tempAttrib1Slot);

    // interleaved data
    const GLvoid* pCoords = &(model->vertexArray[0].Position[0]);
    const GLvoid* sCoords = &(model->vertexArray[0].SourceColor[0]);
    const GLvoid* tCoords = &(model->vertexArray[0].Texture[0]);
    const GLvoid* nCoords = &(model->vertexArray[0].Normal[0]);
    const GLvoid* t0Coords = &(model->vertexArray[0].TempAttrib0[0]);
    const GLvoid* t1Coords = &(model->vertexArray[0].TempAttrib1[0]);

    glVertexAttribPointer(positionSlot, 3, GL_FLOAT, GL_FALSE, stride, pCoords);
    glVertexAttribPointer(sourceColorSlot, 4, GL_FLOAT, GL_FALSE, stride, sCoords);
    glVertexAttribPointer(textureSlot, 2, GL_FLOAT, GL_FALSE, stride, tCoords);
    glVertexAttribPointer(normalSlot, 4, GL_FLOAT, GL_FALSE, stride, nCoords);
    glVertexAttribPointer(tempAttrib0Slot, 3, GL_FLOAT, GL_FALSE, stride, t0Coords);
    glVertexAttribPointer(tempAttrib1Slot, 2, GL_FLOAT, GL_FALSE, stride, t1Coords);

    glDrawArrays(GL_TRIANGLES, 0, model->vertexCount);

    glDisableVertexAttribArray(positionSlot);
    glDisableVertexAttribArray(sourceColorSlot);
    glDisableVertexAttribArray(textureSlot);
    glDisableVertexAttribArray(normalSlot);
    glDisableVertexAttribArray(tempAttrib0Slot);
    glDisableVertexAttribArray(tempAttrib1Slot);

```

}

You see how vastly different code you need to write in order to attach a different shader. Now what if I want to re-attach the default shader back? (this is attaching and detaching of shaders has to happen at run-time, e.g.: actor collected power up).

Any ideas how can I efficiently and easily implement this to allow a model to change shaders at run-time? I am just looking forward to a nice implementation/idea. How would you guys handle the above problem?

# Answer
> 5 votes
You compile your shaders and bind them into *programs*. You can use the same VBOs again and again but with different uniforms or even programs, in the same frame, without problems.

For each program, your calls to `glGetAttribLocation` will return `-1` if that attribute is not in the program, or has been optimised-out (e.g. you declare it but don't use it). `glGetUniformLocation` likewise.

My `draw_mesh` code usually checks for all the attribute and uniform names I've standardised on, and sets the field if its in the program.

To take a real-world example from my code, I often use a model format called Glest G3D which is a keyframe-based animation format. I have two shaders; one will draw a single frame, the other will interpolate two frames. In my `G3D.mesh.draw` function I see if the program has a `tween` uniform; if so, I set `vertex1` and `normal1` attributes and the `tween` uniform. I always set `vertex0` and `normal1` attributes. So one shader gets two frames to interpolate between, and the other just gets one frame, and the standardisation of uniform and attribute names is the contract between my custom shaders and my utility mesh drawing code.

# Answer
> 0 votes
Are you worried about runtime overhead of switching shaders or are you worried about redundant code? Don't worry about the first one until you need to. Avoid premature optimization.

If you are worried about the second, put the code for each shader program attachment in a separate function so you can choose which to call at runtime. If there are many overlapping uniforms, group the common set uniform calls into one function.

You might also find this page helpful: https://stackoverflow.com/questions/7235929/glsl-problem-multiple-shaders-in-one-program

# Answer
> 0 votes
A bit late, but if I understood correctly, you're worried about making your render code general without having to worry about which shader the object being draw has currently, right?

I think you could implement the idea of **materials** and **shaders** in your renderable objects, and make it related to the shader somehow. Then it's a matter of enforcing that such variables EXIST for that given material-shader combination.

The code would be something like this:

```
void RendererGLES20::render(Model * model)
{
    model->Material.ActivateMaterial(model->shader);
    //This model HAS a specific shader, or if you're playing with effects
    //then each effect also has a specific shader

    for(unsigned int i = 0; i < model.Effects.count; i++)
    {
        //Activate it as well
    }

    //generic renderable code for all models
    //here you'll bind your vertexes, normals, uvs, everything else all models share
}

```

Note: This is NOT OPTIMAL! Just get the idea.

And in **Material.ActivateMaterial(Shader\* shader)**, something like:

```
void Material::ActivateMaterial(Shader* shader)
{
    //Here you know the shader, know the material, and can get your variables correctly
    glUniformMatrix4fv(paramLocation, 1, GL_TRUE, &paramValue[0][0]);
    //Other variables
}

```

For effects:

```
void Effect::ActivateEffect(Shader* shader)
{
    glUniform3fv(0, 1, &thisEffectAlphaValue);
    //etc

    //for better control, you could
    glUniform3fv(shader->AlphaLocation, 1, &alphaValue);

    //and for even better
    shader->SendParameter("locationName", &alphaValue); //alphaValue being a vec3 and this being a overloaded SendParameter for various types

    //With this last one you could also keep track of which shader failed to get the location of a variable and save the error somewhere with your Shader class
}

```

So by the time you call **glDrawElements()**, all your variables were sent accordingly.

In my case, my effects have a specific shader each, and I just attach them to objects. Objects will keep rendering themselves since they all do the same thing: receive a MVP matrix, vec3 position, normal, etc, and output a vec4 color in the fragment shader.

For the optimal part, the best way would be to sort objects by shader before rendering. Switching shaders is a big performance issue, so if you can, you should sort objects by shader, then it's effects, and then draw.

---
Tags: opengl, shaders, rendering, scene-graph, pipeline
---


title: Light is not spreading evenly

text:
# Question
Title: Light is not spreading evenly
I am using SunBurn for lights and rendering, when i create sceneobject in code, effect is like this

see in this light is in the middle so sceneobject in middle is well lit and as we go to corner light fades

I want to make it like this

see in this light spreads gradually, this i created with block imported in editor but i want to do it with blocks created with code.

This is how i am adding sceneobjects :

```
var vertexBuffer = new VertexBuffer(GraphicsDevice,
    VertexPositionNormalTextureBump.VertexDeclaration,
    tile.quad.Vertices.Length, BufferUsage.None);

VertexPositionNormalTextureBump.BuildTangentSpaceDataForTriangleList(
    tile.quad.Indices, tile.quad.Vertices);

vertexBuffer.SetData(tile.quad.Vertices);

 BoundingSphere bSphere =
     new BoundingSphere(tile.quad.Origin,
     tile.quad.Height > tile.quad.Width ? tile.quad.Height : tile.quad.Width);

 SceneObject obj = new SceneObject(tile.Effect,bSphere,
    BoundingBox.CreateFromSphere(bSphere),
    Matrix.CreateWorld(tile.Position, Vector3.Forward, Vector3.Up),
    vertexBuffer,PrimitiveType.TriangleStrip,2, 0, 0);

 obj.Visibility = ObjectVisibility.Rendered;

 tile.SceneObjectId = obj.UniqueId;

 sceneInterface.ObjectManager.Submit(obj);

```

I think this is because tangent vectors are not correct, this is my code to add position, tangent, uvs, normals and binormals

```
public Quad(Vector3 origin, Vector3 normal, Vector3 up,
  float width, float height,float u=1, float v=1)
{
    Vertices = new VertexPositionNormalTextureBump[4];
    Indices = new short[6];
    Origin = origin;
    Normal = normal;
    Up = up;

    Width = width;
    Height = height;

    // Calculate the quad corners
    Left = Vector3.Cross(normal, Up);
    Vector3 uppercenter = (Up * height / 2) + origin;
    UpperLeft = uppercenter + (Left * width / 2);
    UpperRight = uppercenter - (Left * width / 2);
    LowerLeft = UpperLeft - (Up * height);
    LowerRight = UpperRight - (Up * height);

    if (u != 1 || v != 1)
        FillVertices(u, v);
    else
    FillVertices();
}
private void BuildTangentSpaceDataForTriangleList(short[] indices,
    Vector3[] positions, Vector2[] uvs, Vector3[] tangents, Vector3[] binormals)
{
    for (int i = 0; i < indices.Length; i += 3)
    {
        int index_vert0 = indices[i];
        int index_vert1 = indices[i + 1];
        int index_vert2 = indices[i + 2];

        Vector2 uv0 = uvs[index_vert0];
        Vector2 uv1 = uvs[index_vert1];
        Vector2 uv2 = uvs[index_vert2];

        float s1 = uv1.X - uv0.X;
        float s2 = uv2.X - uv0.X;
        float t1 = uv1.Y - uv0.Y;
        float t2 = uv2.Y - uv0.Y;

        float r = s1 * t2 - s2 * t1;
        if (r != 0.0f)
        {
            r = 1.0f / r;

            Vector3 position0 = positions[index_vert0];
            Vector3 position1 = positions[index_vert1];
            Vector3 position2 = positions[index_vert2];

            float x1 = position1.X - position0.X;
            float x2 = position2.X - position0.X;
            float y1 = position1.Y - position0.Y;
            float y2 = position2.Y - position0.Y;
            float z1 = position1.Z - position0.Z;
            float z2 = position2.Z - position0.Z;

            Vector3 tangent = new Vector3(
                (t2 * x1 - t1 * x2) * r,
                (t2 * y1 - t1 * y2) * r,
                (t2 * z1 - t1 * z2) * r);

            Vector3 binormal = new Vector3(
                (s1 * x2 - s2 * x1) * r,
                (s1 * y2 - s2 * y1) * r,
                (s1 * z2 - s2 * z1) * r);

            tangents[index_vert0] += tangent;
            tangents[index_vert1] += tangent;
            tangents[index_vert2] += tangent;

            binormals[index_vert0] += binormal;
            binormals[index_vert1] += binormal;
            binormals[index_vert2] += binormal;
        }
    }

    for (int i = 0; i < tangents.Length; i++)
    {
        tangents[i].Normalize();
        binormals[i].Normalize();
    }
}
private void FillVertices()
{
    // Fill in texture coordinates to display full texture
    // on quad, its rotated as planes are rotated while applying
    Vector2 textureUpperLeft = new Vector2(1.0f, 1.0f);
    Vector2 textureUpperRight = new Vector2(0.0f, 1.0f);
    Vector2 textureLowerLeft =new Vector2(1.0f, 0.0f);
    Vector2 textureLowerRight = new Vector2(0.0f, 0.0f);

    // Provide a normal for each vertex
    for (int i = 0; i < Vertices.Length; i++)
    {
        Vertices[i].Normal = Normal;
    }

    // Set the position and texture coordinate for each
    // vertex
    Vertices[0].Position = LowerLeft;
    Vertices[0].TextureCoordinate = textureLowerLeft;
    Vertices[1].Position = UpperLeft;
    Vertices[1].TextureCoordinate = textureUpperLeft;
    Vertices[2].Position = LowerRight;
    Vertices[2].TextureCoordinate = textureLowerRight;
    Vertices[3].Position = UpperRight;
    Vertices[3].TextureCoordinate = textureUpperRight;

    // Set the index buffer for each vertex, using
    // clockwise winding
    Indices[0] = 0;
    Indices[1] = 1;
    Indices[2] = 2;
    Indices[3] = 2;
    Indices[4] = 1;
    Indices[5] = 3;

    var tangents = new Vector3[4];
    var binormals = new Vector3[4];
    var uvs = new Vector2[4];
    var positions = new Vector3[4];

    for (int i = 0; i < 4; i++)
    {
        positions[i] = Vertices[i].Position;
        uvs[i] = Vertices[i].TextureCoordinate;
    }
    BuildTangentSpaceDataForTriangleList(Indices, positions, uvs, tangents, binormals);
    for (int i = 0; i < 4; i++)
    {
        Vertices[i].Tangent = tangents[i];
        Vertices[i].Binormal = binormals[i];
    }

}

```

i ll be glad if somebody could help me, thank you

# Answer
> 1 votes
Unless you are leveraging the tan/bitan for normal mapping, and you have some really strange normal maps, that is unlikely to cause the issue.

It looks to me like you are performing per vertex lighting calculations in the top frame, and the bottom is per pixel. Or, the position data you are using to perform attenuation calculations is a bit odd. Notice each block seems to have a flat shading, as if every pixel for each block is being attenuated using the same distance calculation.

---
Tags: xna, textures, 3d-meshes, sunburn
---


title: Does Windows 8 still support DirectX 9?

text:
# Question
Title: Does Windows 8 still support DirectX 9?
Is Windows 8 supporting DirectX 9? Because I was looking through some samples written in C++ and DirectX 9 made for Windows 8. It wasn't that, like I know it ( look here http://directxtutorial.com/Lesson.aspx?lessonid=111-4-2 ). E.g. Inizialising DirectX with COM:

```
ComPtr<ID3D11Device1> dev;
ComPtr<ID3D11DeviceContext1> devcon;

```

It's just weird because I know it with the old way:

```
ID3D11Device *dev;
ID3D11DeviceContext *devcon;

```

( I hope you understand what I want to tell )

I hope it hasn't change completely due the released their new OS.

# Answer
> 12 votes
**Yes**, Windows 8 does support DirectX 9.

For development, the old DirectX SDK is now deprecated, but you'll have all the libraries and headers you need within the new Windows 8 SDK, which comes included with Visual Studio 2012. You can go for the "old way" with no problem. If you need PIX for some debugging, or the high level D3DX library, you'll have to install the old DXSDK again, as this is *not* in the Windows 8 SDK.

**However** this is only valid for plain old desktop apps. For Metro-style apps, I'll let Chuck Walbourn from Microsoft speak:

> Direct3D9 and Direct3D9Ex are not supported for Metro style applications. Use of the DirectX SDK with Metro style applications is not recommended or supported. See http://msdn.microsoft.com/en-us/library/ee663275.aspx.
>
> There are a number of resources available to help you in porting a Direct3D 9 codebase to Direct3D 11. The majority of the material for porting from Direct3D 9 to Direct3D 10.x applies fully here since Direct3D 11's API is very similiar to Direct3D 10.
>
> See http://blogs.msdn.com/b/chuckw/archive/2011/07/11/getting-started-with-direct3d-11.aspx. Be sure to review the Windows to Reality: Getting the Most out of Direct3D 10 Graphics in Your Games presentation as it covers numerous pitfalls and performance issues developers have hit in the past, and DirectX 11 Technology Update for a summary of the differences between Direct3D 10.x and Direct3D 11.
>
> MSDN has a porting guide as well http://msdn.microsoft.com/en-us/library/ff476190.aspx which points you to http://msdn.microsoft.com/en-us/library/bb205073.aspx for going directly from Direct3D 9 to Direct3D 11.

Sorry, you can't use D3D9 directly for Metro-style apps. But you can use D3D11 and limit yourself to some feature level (e.g. `D3D_FEATURE_LEVEL_9_3`) if you want to support legacy hardware.

# Answer
> 3 votes
Windows 8 has the same basic support for Direct3D 9 applications as was present in Windows 7 and Windows Vista. Direct3D 9 is legacy and there are definitely some compat issues that can potentially impact Direct3D 9-based games, but they more or less function as well as they did on Windows 7.

Development with Direct3D 9 on Windows 8 is a bit more challenging than it was on Windows 7. The standard Direct3D 9 headers are part of the Windows 8.0 SDK (included with VS 2012), but that does not include D3DX9. The Direct3D 9 Debug Runtime is not supported on Windows 8. You can use the legacy DirectX SDK on Windows 8, but there are a number of challenges getting it installed and limitations.

The recommended API to use for writing new applications on Windows 7 and Windows 8 is Direct3D 11. This works for both Win32 desktop applications and Windows Store apps. Also, it is recommended that you make use of the Windows 8.x SDK and not make use of the DirectX SDK.

See Games for Windows and the DirectX SDK for lots of posts on this very topic.

# Answer
> 2 votes
DirectX will install on Windows 8, Windows 7, Windows Vista, or Windows XP.

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


title: Input in OpenTK

text:
# Question
Title: Input in OpenTK
How to use Input in OpenTK 1.0? There is not much info around, some classes are unfinished.

What I want to achieve, is to be able to use input not only in OnUpdate function, but also in other classes created by myself.

# Answer
Check out OpenTK.Input.

From there you can get access to `OpenTK.Input.Mouse` and

Some examples from the page include:

To check whether a button is pressed:

```
using OpenTK.Input;

var mouse = Mouse.GetState();
if (mouse[MouseButton.Left])
{
    // Left mouse button is pressed
}

```

To check whether a mouse button is not pressed:

```
using OpenTK.Input;`

var mouse = Mouse.GetState();
if (!mouse[MouseButton.Left])
{
    // Left mouse button is not pressed
}

```
> 2 votes

---
Tags: opengl, c#, opentk
---


# Question
Title: What version of OpenGL should I code for, given compatibility and performance considerations?
When the OpenGL spec is updated, they only ever add features. So in theory, the latest and greatest hardware with support for the Core and Compatibility profiles should run super old OpenGL1.1 code just fine. This has turned out to be true. I've spent 12 months learning OpenGL1.1 and have a fair grasp on it.

I had a read of a few chapters of one of those fancy new OpenGL4.2 books. Almost all of the features that I rely on have been deprecated (like Display Lists), which lets me assume that there are better ways of doing all these things.

Lets consider that 1.1 is likely to be supported, in full, by ALL modern hardware. 1.1 was released in 1992. I'm not coding the hard way ***just*** to support 20 year old PCs. :-p I think its reasonable to assume most gamers are running hardware that bottoms out at about 5-year old mid range.

I think the newer methods are designed to universally be either one of two things: better performing, or easier to code. I read somewhere that its never both though! XD

**What version of OpenGL is most widely supported by ~5ish year old hardware? What version makes most sense to use, given these considerations?**

# Answer
Given your considerations, I then popped over to see when OpenGL specs for each version was released and also factored in some overall insight from what I've seen.

OpenGL 3, which introduced FBOs, VAOs and other things, was released in July 11, 2008, almost 5 years ago. Of course, you can't expect all cards after that date to immediately to have OpenGL 3 available.

Taking a look at the Steam Hardware Survey, 40% are DirectX 10. As OpenGL 3 required a similar graphics card, it is generally safe to assume most DirectX 10 cards can run at least OpenGL 3.

OpenGL 3 is supported on cards all way back to GeForce 8xxx series, which were pretty popular if I recall correctly. Also interesting to note is that Intel HD 2000 and 3000 Graphics (Sandy bridge) only support up to OpenGL 3, so keep that in mind if you plan to target those.

Conclusion: OpenGL 3 is a good bet (also remember that most gamers, depending on your target audience, will probably have better hardware than average).
> 20 votes

# Answer
I'd start here: http://store.steampowered.com/hwsurvey

I wouldn't target a time period so much as a percentage of users, for instance, if you target 4cpus, you'll only hit 45% of users, but if you work to 2, you'll get close to 90%
> 8 votes

# Answer
The answer depends on whether or not you need to or want to run on Intel graphics released within the timeframe you mentioned.

If you do, then limit yourself to OpenGL 2.1 (or even 1.5), if you don't then 3.x seems reasonable.

Yes, older versions of OpenGL do still run, and yes, from one perspective they can seem simpler. Where things go bent out of shape is when you try to do things (and you will) that they don't support too easily. OpenGL 1.1 isn't just the hard way - it's often the impossible way if you want to achieve certain results.
> 3 votes

# Answer
Firstly OpenGL 1.1 stuff like Display Lists will still work in a new context provided you have the compatibility profile (which is generally the case). The only problem is if you expect to port to OpenGL ES, one of the console specific graphic library (they are generally stripped down OpenGL similar to OpenGL ES) or even WebGL (which would require quite a bit of reworking anyway).

Personally I would recommend using vertex/fragment shaders and VBO's. They have been around for quite a long time now and offer great performance improvements. You could probably even provide a simple fall back if you wrap the functions in a class.

You may also be able to emulate things like Vertex Array Objects.
> 1 votes

# Answer
With 5-ish year old hardware, some people are still using XP. And that means that you can't even code with DirectX 10 or OpenGL 3. And OpenGL 3 has a lot of features that you'd really benefit from, like framebuffers and such. Honestly, I'd bump up your system requirements just a bit so that you can include those features.
> 0 votes

# Answer
It is common for 3d software to have code paths for both a "baseline" graphics api version and a "latest and greatest" api version.

Common baseline graphics versions are D3D9 and OpenGL 2.1 / GLSL 120 .. Which are both notably missing geometry shaders because old hardware does not support them.

Another baseline option is ANGLE, which is GLES 2.0 plus EGL that runs on D3D9, desktop OpenGL, and mobile GLES 2.0. It is the back end for Google chrome and webgl in chrome and Firefox.

http://code.google.com/p/angleproject/

As for the "latest and greatest" version you choose, that is more challenging. The more recent api and hardware you target, the better looking features you can support - but only on the latest and greatest hardware.
> 0 votes

---
Tags: opengl
---


title: Controlling Constantly Running AIs

text:
# Question
Title: Controlling Constantly Running AIs
*So, I'm not really sure where to start with this question. Feel free to tell me I'm stupid and Off Topic but I'd also like you to tell me why.*

So, the maps in the game I am designing will consist of lots and lots and lots of voxels. Most of the voxels will just sit there and some of them will have methods run when they are touched or something happens around them. However, some blocks will constantly being doing something. Now, I'm not sure if I should have a array in every chunk (Group of voxels) that contains all the 'active' blocks or if there is another way. I know that some voxels will run code when they are loaded that makeup for all the time that they hadn't been doing anything but I may need to constantly run some voxels. (Machine that overheats or powers something can't just be loaded in 20 minutes after it blew up; or can it?)

So, now that that basic background is over, here is my question: **Will an array storing all active entities in an area suffice as a way to run all the frame by frame methods of the blocks?** Or is there a "normal" way to do this that I am unaware of?

**EDIT:** I just realized that the client that does rendering will not do a majority of the operations for the game engine. I will have a server that does it. The answer to this question is still largely relevant and helpful though. I just thought I'd mention my change.

# Answer
1. Yes, this is a reasonable approach. Note that in principle what you need is not an *array*, but a *set*. This is relevant because if one of your active voxels is destroyed/replaced, you need to be able to efficiently remove it from the set. If your platform doesn't have a set type, then use a hash table with the voxel coordinates as keys and dummy values.
2. Another case that might arise is a voxel which does something on a schedule (once or repeating), but not every frame. If you want to support this efficiently, then you should keep track of the voxels to be triggered and the in-game-time to trigger them, and the best kind of data structure for that is a priority queue, which allows you to efficiently ask the question “which voxel needs to run *next*?” so you don't have to check the entire set.
3. However, if you have many voxels which should update on the **same** schedule, but less than every frame, the set approach is again appropriate; you simply don't do it every frame. (If you need to spread the CPU load you could choose to do part of the work in each frame. Say you're doing it every 3 frames: Copy the set into an array, divide the length by 3, and iterate over one third for each of the next three frames.)

Note that these options are different not just in efficiency but in the resulting behavior of the game: a periodically triggered set will cause voxels to update all in sync at the same instant (there can be no *phase difference*), whereas the priority queue can represent the exact time instants of something like "this voxel does something 1.5 seconds after it comes into existence, and every 1.5 seconds after", but takes more resources to manage that extra information.
> 3 votes

---
Tags: performance, entity-system, voxels
---


# Question
Title: How does collapsable structures in a voxel based game like Ace of Spades/Build and Shoot work?
I know that once all the cubes that are connected are destroyed, the unconnected blocks collapse. How do you find out the unconnected blocks?

edit 1: How would you determine the collapsible object if it spans multiple chunks?

# Answer
I would assume that each voxel object contains a reference to its adjacent voxels. When a voxel is changed it calls some kind of update function on each of those references.
> 0 votes

---
Tags: python, voxels, panda3d
---


title: Pathfinding in hex grid based game

text:
# Question
Title: Pathfinding in hex grid based game
I'm making a TBS using a hex grid. Player can move units from one hex to another using bridges, which will be randomly generated. I'm using cubic and axial coordinate system for my grid, it's well described in Red Blob Games' Hexagonal Grids.

I don't know how to make a hex understand connection with another one and then calculate best path for units.

I'm not sure how to approach the issue - should I make six slots for bridges in my hex class and then calculate path or should I make movement system somehow and then use absence of bridge as a "blocker"?

# Answer
> 4 votes
You can just apply A\*( A-star ). Compared to a uniform square grid the only difference is the way you collect the adjacent tiles ( aka your hexagons ).

Each tile should have a table of booleans representing the bridges corresponding to their direction like so

```
//Depending on your hexagon order
enum Direction{
   NORTH,
   NORTH_EAST,
   SOUTH_EAST,
   SOUTH,
   SOUTH_WEST,
   NORTH_WEST
}

```

And in your tile object:

```
Bool[] bridgeTable = new Bool[Direction.length];

```

In your A\* just iterate over your enum list and check the corresponding boolean table that goes with it. This however assumes you always start with the tile which is placed north from the current tile.

For example:

```
//If there is no bridge
if(!bridgeTable[Direction.NORTH]) continue;
else //calc costs etc

```

You could also pre-calculate the shortest path from one end to another. If new bridges are added or removed you need to recalculate the table/graph: Floyd\_algorithm

---
Tags: algorithm, path-finding, hexagonal-grid, turn-based-strategy
---


title: XNA Shader has an unwanted tint

text:
# Question
Title: XNA Shader has an unwanted tint
I'm working on a shader but it has a weird tint to it and I'm not sure why. Right now it's extremely simple, it just sets a rendertarget, draws to it, passes it as a texture to the shader then oututs the pixels to a fullscreen quad. If I remove the rendertarget/texture part and just directly pass it into the shader it comes out properly, but once I start including rendertargets the colors get a little weird.

Here are two images showing what I mean:

This is how it should look normally

This is how it looks with the rendertargets I've included the code for the shader and the draw method below:

Shader:

```
float4x4 World;
float4x4 View;
float4x4 Projection;

Texture glowTexture;

sampler glowSampler = sampler_state
{
texture = <glowTexture>;
magfilter = LINEAR;
minfilter = LINEAR;
mipfilter = LINEAR;
AddressU = clamp;
AddressV = clamp;
};

struct VertexShaderInput
{
float4 Position : POSITION0;
};

struct VertexShaderOutput
{
float4 Position : POSITION0;
};

VertexShaderOutput VSOutline(VertexShaderInput input)
{
VertexShaderOutput output;

output.Position = input.Position;

return output;
}

float4 PSOutline(VertexShaderOutput input, float2 pixel:VPOS) : COLOR0
{
float2 uvPixel = (pixel + 0.5) * float2(1.0 / 1280, 1.0 / 770);

float4 finalColor = tex2D(glowSampler, uvPixel);

return finalColor;
}

technique Outline
{
pass Pass1
{
    AlphaBlendEnable = TRUE;
    DestBlend = INVSRCALPHA;
    SrcBlend = SRCALPHA;

    VertexShader = compile vs_3_0 VSOutline();
    PixelShader = compile ps_3_0 PSOutline();
}
}

```

Draw method:

```
            GraphicsDevice.SetRenderTarget(renderTarget);
            GraphicsDevice.Clear(Color.Black);

            scene.RenderGrid();
            playerList.Render();
            scene.RenderObjects();

            GraphicsDevice.SetRenderTarget(null);

            renderTargetTexture = (Texture2D)renderTarget;

            for (int l = 0; l < resourceLoader.GlowShader.CurrentTechnique.Passes.Count; l++)
            {
                resourceLoader.GlowShader.Parameters["glowTexture"].SetValue(renderTargetTexture);

                resourceLoader.GlowShader.CurrentTechnique.Passes[l].Apply();
                renderQuad.Render();
            }

```

# Answer
> 2 votes
I think it is either that the SpriteBatch changes the GraphicsDevice states or that you haven't cleared your rendertarget like Vodáček suggested.

For more information on the device states see BlendState and the others

---
Tags: xna, shaders
---


# Question
Title: Where can I modify the default damage system on UDK
I want to make a custom damage system on my game but I can't find the function that handles it...

I looked on Actor.uc but the only thing I've found is the event TakeDamage, but there's nothing on it that actually deals the damage.

Thanks in advance.

# Answer
TakeDamage is the ticket. Pawn::TakeDamage is where the default damage system for characters and vehicles is located.
> 0 votes

---
Tags: udk, scripting
---


# Question
Title: What's the current preferred method for serving/storing game data on html5 games
Given all the recent improvements on web platform (webgl, websockets, etc.), it should be now possible to see great games on web. However my biggest concern so far has been around serving and storing the game assets. AFAIK the webstorage only supports a few megabytes and it is not enough for the majority of the games. Even if I work around that limit by providing a ton of different origins, is it possible to claim that it's a safe method? For desktop games we have a lot of anti-cheat mechanisms (steam has one, most A+ have them builtin) If I store my game assets using the webstorage can I claim that they won't be modified by the user?

My game has assets around 800 mbs and I would love to get some feedback on how to serve them and store them properly. I'm trying to satisfy the following:

* People shouldn't be forced to download all of the assets every time they want to play the game \[unless there's a patch, etc.\]
* It shouldn't be trivial to make client side hacks and change configs to get all the good stuff without playing/paying for them \[greasemonkey!\]
* Ideally, the solution should work on all the browsers \[latest version of IE, Chrome, FF and Safari\]\[no mobile is OK\]

# Answer
No browser supports an unlimited amount of storage space (or anywhere close to your 800MB) for arbitrary web apps out of the box, and most are limited to 5MB to 10MB.

The *easiest* way to explicitly cache data is to use the Application Cache (manifest). You can also use LocalStorage if you want to programmatically download levels in advance rather than precaching the entire app. These both have size limits in every actual browser, however, though the specs don't explicitly mention a size.

You can request a size increase when your page loads, though you need to deal with the case where a user or the browser rejects the request. Note that simply failing to load is not ideal as it is not particularly easy in some browsers to get the request to reappear, so if you refuse to run without the increase in storage your game will just never run and the user is stuck. Use this as an *optional* way to speed up your game, not as a mandatory feature.

Exceptions to the rules can be found in some browsers under special circumstances, such as the ability to use more space if your app is registered in the user's Chrome App list, which requires them to "install" it via the Chrome Store (the app itself still lives on your server; the store just adds a record of the URL and some permissions to the Chrome app list).

Note that browsers naturally cache files. So long as your server respects the `If-Modified-Since` and `If-None-Match` headers and properly sends the `Expires`, `ETag`, and `Last-Modified` headers, the browser *might* cache your files. You hence might be able to get away without explicit storage so long as your game doesn't download more than ~50MB of content at a time, though the caching is purely *opional* for the browser and it might not cache or evict the cache items as it chooses (unlike the app manifest or local storage).
> 4 votes

# Answer
You've confused the assets with client-side data storage.

You can load assets using normal HTTP requests that the browser makes. These are subject to normal HTTP rules about caching, expiring and conditional requests. If you have 800M of asset data, you definitely need to do this.

There is no limit to how many assets you can load in the "normal" way (these are typically loaded by either - img elements, audio elements etc or XmlHttpRequest, which can nowadays be used to load non-XML and even binary data)

There is also no real limit to how much data you can store server side in your own system. If you decide to store player's replays, screenshots etc, you won't be limited by LocalStorage limitations if you post the data using XHR to your server. (Obviously there is a practical limit to this as most users have fairly limited upstream bandwidth)

---

As far as anti-cheating, etc, is concerned, you can't stop people cheating. They can trivially substitute your assets with their own versions, and there's nothing you can do about it.

You can probably make it difficult enough for them to get the premium content without paying to convince them to pay though. Pirating a game served online is fairly tricky and won't work any more once you update it.
> 2 votes

---
Tags: html5, web, security
---


# Question
Title: When do you get Mouse.getstate().X or Y as negative?
I am creating a game in which I use a function:

```
int x()
        {
            int px = 100;
            int pxend = 128;
            int xx = 0;
            for (int i = 0; i < 6; i++)
            {
                l = Mouse.GetState().X;
                if (l> px && l < pxend)
                {
                    xx = px;
                    break;
                }
                else
                {
                    px += 128;
                    pxend += 128;
                }
            }
            return xx;
        }

```

and

```
int y()
        {
            int px = 100;
            int pxend = 128;
            int xx = 0;
            for (int i = 0; i < 4; i++)
            {
                l = Mouse.GetState().X;
                if (l > px && l < pxend)
                {
                    xx = px;
                    break;
                }
                else
                { px += 128;
                pxend += 128;
                }
            }
            return xx;

        }

```

But when I debug I get value a `l` as negative even though the debug is initiate after a click on the `GameWindow` screen. Sometimes it works fine sometime does not. I dont know why does it give me negative value. And when I used them with my `Rectangle` i get `Rectangle.X and Rectangle.Y` as `0`.

# Answer
> 3 votes
As per this MSDN article: http://msdn.microsoft.com/en-us/library/microsoft.xna.framework.input.mousestate.x.aspx, The mouse location is based on the top left of the game window. So, if the mouse escapes the window, the mouse location will be negative. Also, some windows counts a pixel or two to the left of the screen, so this is not an uncommon behavior.

If you are getting strange values in general, make sure you turned on the mouse in the Game's Property list, and that you are retrieving the values right. In general, you don't want to use the value of Mouse.GetState() straight.

---
Tags: xna, input, mouse
---


# Question
Title: If you want to script a game engine, do you embed the script in the engine, or the engine in the script?
I'm new to scripting and combining languages with each other, so I have a question about something that confuses me. If you want to script a game engine, do you embed the script in the engine, or the engine in the script?

If you embedded the script in the engine, I can't really wrap my head around how that would work. Would you have this big script function you called every time you went through the game loop, passing along the inputs and etc.?

If you embedded the engine in the script, I could see how it would be convenient to just treat the whole engine just like a object in the script, and call a simple function each time you wanted to create something. On the other hand, how would the game loop inside the engine work? Having an extra thread for that seems like it could complicate things.

I haven't really found any good information that deals with scripting game engines. My engine is written in C++, and I am planning to script in Python 2.7.

# Answer
You embed the scripting engine inside the game engine.

I've never used this but you probably want boost::python
> 4 votes

# Answer
Do you really need to script things?

If the project is just you, and you're not making a sprawling RPG you arent really going to gain much in the way of productivity by using a scripting language. But what about recycle time and ease of programming I hear people chime in with. Well.

* C++ has a slew of excellent tools and debuggers (visual studio), scripting langauges often do not have such tools, making error tracking and debugging difficult, especially as script code often increases in complexity over time
* You will have no performance issues with interop code
* Your state will be contained in a single place, with no duplicity that often occurs with scripting code
* If your recompile/re-boot time is longer than a few seconds, you should fix how your engine is compiling.

If you really absolutely must use a scripting language (and there are reasons it makes sense, for example, a sprawling RGP will have a lot of scenario logic that may be difficult to express in pure data) Its a good idea to push the scripting interfaces all the way out to the edges of your code. And only query single functions which contain no state.

You want to avoid building parts of your engine in script, and you certainly want to avoid duplicity of state at all points. You want to use script calls to answer "Questions", eg: "how do I react when I see the player", or "what sound do I play when I die". You dont want to be implementing your entire AI layer in script!.
> 4 votes

# Answer
For my implementation, I embed the script in the engine (I'm using Lua and my engine is C++). I use Lua to define the contents of the game, e.g. monsters, items, map generation, and maybe using it to script the enemy AI (haven't reached that part yet).

What I do is I have functions in my engine that are used to register these definitions into the engine, which are called during the initialization stage. When I need to create a new instance of, say a monster, I simply refer to the definition of the monster, e.g. its stats, graphics and instantiate it with those values.
> 2 votes

---
Tags: scripting
---


title: iOS paralleling of game tasks (Client)

text:
# Question
Title: iOS paralleling of game tasks (Client)
What good practice in paralleling of rendering, main game logic and networking on iPhone/iPad? If I program on Windows I use threading and IOCP, but I am new to iOS. So what patterns, io async libraries or something like kernel queues you choose when program complex mobile games? I need your advices on how do not stuck on waiting of server's answer and show animation at the same time? How must be organized main loop of client of the game? My interest first of deals with C++ approach and Marmalade SDK, but I'll be happy to any solutions!

So, for game logic, rendering, networking, user input and audio:

1. What paralleling mechanisms do you use? Pure threading or some library?
2. How does your waiting logic for server's answer work? I guess that animation, rendering and game logic still play and not wait server.
3. Any know how, links, post mortems from client-server iPad/iPhone games?

# Answer
> 1 votes
1) iOS and most mobile device needs main thread to call OpenGL ES commands. So there is no way you can move them out, So in our case, the main thread will always concentrate only on drawing.

2) While, the main thread is busy drawing, we use another thread for Game Physics and collision logics. If the game uses very complex physics, then we use more threads. We use Bullet Physics which is already good at multithread ready. So we give it one thread per CPU core. This works efficient.

For downloading things from server, we use background process that updates the progress to a variable and the draw thread just uses the variable to draw the progress. To maintain cross-platform, we use posix thread for physics and game logic. For drawing, we use displaylink callback.

---
Tags: c++, ios, marmalade
---


# Question
Title: Reading from depth textures always returns 1
I create a packed depth/stencil texture and attach it to a framebuffer like this:

```
glGenTextures(1,&_depthStencilTexture);
glBindTexture(GL_TEXTURE_2D,_depthStencilTexture);
//set filtering to gl_nearest, not shown cause not important
glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH24_STENCIL8,width,height,0,GL_DEPTH_STENCIL,GL_UNSIGNED_INT_24_8,nullptr);

//... create framebuffer and attach some color attachments
glFramebufferTexture(GL_FRAMEBUFFER,GL_DEPTH_STENCIL_ATTACHMENT,_depthStencilTexture,0);

```

The creation of the framebuffer causes no OpenGL status errors.

In terms of usage for depth and stencil testing, the texture/attachment seems to work correctly. If I disable depth testing, I get the usual artifacts of objects in the back being drawn over objects in the front if they are drawn in the wrong order. If I disable stencil testing, the effects I'm using related to that don't work anymore (I'm masking out areas that shouldn't be lit by the lighting pass). Also, if I simply don't attach the depth/stencil buffer to the framebuffer, the related tests stop working (as expected).

However, reading from that texture in a shader always returns 1 if I read the depth part, and 0 if I read from the stencil part.

I confirmed this via glReadBuffer(GL\_DEPTH\_STENCIL\_ATTACHMENT) and glReadPixels. All integers read show up as 0xffffff00, directly after clearing them via glClear and a black clearcolor and also after the screen is drawn full of stuff.

Drawing to and reading from the rest of the attached textures (four color buffers for now) works fine.

I have to note that I'm not actually manually drawing anything to the depth-stencil attachment in the fragment shader when rendering - I'm assuming OpenGL automatically draws depth and stencil values to the correct buffer.

What could be the cause of these incorrect values showing up when reading from the texture?

# Answer
> 1 votes
I have the same problem with preview of depth textures, but not from code level, but from CodeXL from AMD. I'm not 100% sure but maybe they try to draw textures in the same way as you.

My solution to see the content of depth attachment is using this simple shader:

```
// vertex
#version 330
in vec4 vertex;

void main(){
    gl_Position=vertex;
}

// fragment
#version 330
out vec4 frag;
uniform vec2 screen; // screen size

uniform texture2D depth;
void main(){
    frag=texture2D(depth,gl_FragCoord/screen);
}

```

to 'depth' pass your \_depthStencilTexture and use this shader when rendering fullscreen quad. You can also add linearization to see better what the content of depth attachmnet is.

---
Tags: opengl
---


# Question
Title: How can I convert a 3ds Max .max to a Cinema 4D .c4d and maintain the animation?
I have recently purchased this asset from the3dstudio.com:

http://www.the3dstudio.com/product\_details.aspx?id\_product=193089

It has a corrupt .3ds file available, and a .max (as well as what appears to be a broken .dfx and a textureless and animation-less .obj).

I wrote the site administrator, who attempted to make me a new .3ds file from his master copy (I'm assuming the working .max file) but said:

"The .3ds export doesn't seem to be completed so normally we would just re-export it but I can't get a good export on this model. Only the low-poly control mesh wants to export so I emailed the author to see if they can get us a better file and will let you know as soon as they reply.

"With any non-max format you will not have any rigging in the model as common formats (3ds, dxf, obj, etc) do not support things like rigging (which are program specific) so any export to 3DS (and thus C4D) would just be the geometry, textures, and basic materials."

So it was my understanding based on my very limited knowledge and this e-mail I got that none of the formats that I'd be able to get into Cinema 4D would be able to carry animation data. Then I saw this Elance job posting:

http://www.elance.com/j/convert-3d-studio-max-animation-cinema-4d/19612175/

Now obviously that's not, like, internet canon: I realize just because there was a listing on some site somewhere that made it seem like it was possible doesn't make it true. But it looks like that team in India was willing to do it for sixty bucks, which makes it hard to believe it could be that in-depth of a process. But maybe that's my naïveté about either 3D or American to Indian currency conversion rates or both.

So, is this possible?

# Answer
> 3 votes
Cinema 4d seems to support FBX format. Even the cheapest C4D. You might be using a very old Cinema, thugh. Check if you can import FBX.

FBX is a format that does support perfectly bones, weights, animation. So, all you need to do is get someone that opens in Max that \*.max file you have, and export as FBX. Then you could import into your Cinema4D, and have it ready.

This is not 100% safe path, in the sense that always there can be issues, that is, when importing an FBX file into any package. But it should work with some settings tweaking: FBX is a format thought for exchange.

So, possible solutions (go with whichever bellow, but I'd go trying in the listed order...):

* Ask the The3DStudio crew, which have fame to be eficient and serious, to export for you in FBX format (considering the initial corrupt \*.3ds file problem, might be a kind detail...though dunno if is legally allowed by the file author) , is easy for them and would have use very little time unless appears some big issue.
* Have one friend having a Max license open the max file and simply got to menu, export fbx (it comes by default, needs no plugin)
* Have those guys from elance take care as well of the C4D import, so you might ensure no issues, if they know their stuff.

Note: Sometimes is not enough to play with FBX i/o settings, and you need to try a pair of FBX versions, usually 5.x or 6.x. I don't know which is the current number. I tested to be safer to export in default Max FBX, the one that comes included, than installing as a plugin. Anyway, sometimes older versions work better with older packages.

About the 60$ of the third option, I guess they charge that for in case some issue arises, as the actual thing is open, export, import. Just that there might be fixing involved. Sometimes really easy ones, other times can even make it impossible, depending on package versions, status of original file, etc.

# Answer
> 0 votes
For the reference of others in the future, this is the one & only way to do a full, 1:1 conversion from 3ds Max to Cinema-4D, with no intermediate file formats like .3ds (which is a deprecated, 16-bit DOS file format):

http://www.okino.com/conv/pt4max.htm http://www.okino.com/conv/exp\_c4d.htm

---
Tags: 3d, animation, 3dsmax, models, cinema-4d
---


# Question
Title: Unity3d reading profiler binary information
So I'm using Unity's profiler to help debug some of my code in the standalone. I've got it running smoothly, and writing all it's data to a .data file which I can read.

However, the binary file Unity creates for profiler information gets quite huge very quickly. I'm hoping to get past this by writing the profiler data log to a zip archive. I have dotnetzip installed, and can add files to a zip archive.

What I'm trying to figure out is how I could possibly either write the profiler data log directly to the zip archive, or write the profiler binary data to a variable of some sort which I could store in a stream and write to the zip archive on quit. This way I won't ever have to have the large file on the user's drive.

Another option would be to continuously write the binary data to the log on the drive, then get the binary info from that log, write it to a stream, put it in to a zip archive, then delete the log. However I'd have to do this every few seconds, and that may get slightly process intensive.

# Answer
> 2 votes
So I figured out how to do this efficiently. What I do is every X minutes write all the data to a stream and delete the data file. This causes the data to not take up so much disc space. Then on application quit I write all that data from the stream to a compressed archive. I end up getting roughly 1 megabyte a minute from the Profiler, rather than 1 gigabyte.

---
Tags: c#, unity, file
---


# Question
Title: How do you implement input handling in a C game engine?
I am starting to learn C programming, though I have a lot of experience using higher-level languages. I want to write a game engine using C and OpenGL. I think I understand the graphics rendering part, but now I'm curious about how to receive and process keyboard, mouse and controller input. How does one implement this sort of thing in C?

# Answer
While you can certainly pick a cross platform library, if you want to write the input functions yourself, you'd need to create some generic code interfacing rules or C++ objects which would cover all platforms to do this neatly. Then you would create implementations that are platform specific, only compiled when the library is being built for that platform.

At least that piece, I can assist with. The following link shows how to use preprocessor directives to detect Windows, and it should work in most cases, although there may be some caveat for 32-bit versions. You would still need to find platform specific APIs to manage the input gathering for each target platform, and perhaps manage the project settings for the compiler / IDE to create multiple build targets, each one for a different target environment. In short, it's the complicated method...

https://stackoverflow.com/questions/3213037/determine-if-linux-or-windows-in-c

If you instead wish to use GLUT, a tutorial is available here that should set you on the right path. I don't think it includes creating Windows, but I hear that GLUT does that as well...

http://www.lighthouse3d.com/tutorials/glut-tutorial/keyboard/

If you have any other questions, I can see what can be done to answer them.

--- EDIT ----

Since it was requested, I can provide a high level idea of how input gathering works, and with some more direction, I can give something more concrete, although I've never used GLUT personally.

There are two methods of gathering input, polling and event based. Polling is preferred for gaming, because you want to be able to get all the input that happened in a frame at once during your update loop. However, in reality, it's all happening in an event based model, even if you go as deep as interrupt handlers in your operating system kernel, interacting with the lowest levels of circuitry. I won't belabor that part, because someone else is probably better licensed to answer that question.

In an event based model, some callback function is fired each time a key is pressed. This happens asynchronously, so some form of multitasking is involved, such as threading, or interrupts, at the lower levels. In this model you hand the input engine a function, which is called each time the event happens, in this case, a key press or a mouse movement. Let's say it looks like this, for a fictitious InputObject API...

```
void gatherInput(InputObject input)
{
 if(input.isKey())
 {
      doKeyPress(input.getKeyCode());
 }
 else if(input.isMouse())
 {
      doMouseMovement(input.getMousePosition());
 }
}

```

Obviously, you would want more functionality, like getting modifier keys, or getting mouse button presses and the position, but you get the idea.

The best idea for a video game, though, if it's not already done for you, is to create a polling environment. In this environment, the polling mechanism is basically a queue or some other structure into which our fictitious InputObject entries would be logged. Then all at once, we would call some methods on our input poll, which would allow us to dequeue InputObjects and respond to them, one at a time. This has the obvious advantage that all input since you last ran update in your game loop is collected and responded to at the same time, so that the game logic isn't updating at a different timestep than the input gathering.

An input polling method might look like the following...

```
void update(Time time)
{
    while(this.inputQueue.hasNext())
    {
     InputObject i = this.inputQueue.dequeue();

     if(i.isKey())
     {
         doKeyPress(i.getKeyCode());
     }
     else if(i.isMouse())
     {
         doMouseMovement(i.getMousePosition());
     }
     // etc...
    }

    simulate(time);
    animate(time);
    draw(time);
    //etc...
}

```

For some input libraries, you may have to convert events into a polling queue of your own design. In this case, the events simply enqueue the objects containing input into some input queue, and you get them one at a time on each update. This is the preferred method, as previously stated.

Hopefully, that's clear as mud, but if it's ever so slightly clearer, please feel free to offer points:)
> 2 votes

---
Tags: input, c
---


title: MMO, server-side line of sight

text:
# Question
Title: MMO, server-side line of sight
I am working on a simple tile-based multiplayer game. I am rather experienced programmer, but not so experienced game developer.

The players will see each other depending if there is a blocking object between them or not. The objects can be moved around, so the map is not static.

If A moves (or performs other action) and B sees that (LOS is not blocked) then B client will be notified and will update it's view. If B does not see A, then B will not be notified.

Question:

1. Should I notify client A about B's movement regardless of LOS, perform all the LOS checking on the client-side and update the view accordingly, or...
2. should I do all the LOS server-side and notify client A only in case of visible movement?

I know than, in principle, I should not trust client-side and not send anything to the client that is not necessary (client code can be hacked and show movement out of LOS). But, if there is a significant number of players at once, then I am afraid than the server will not cope with tracking all LOS for all the events and all the players.

How to cope with this problem? Is there some "standard" solution here? I know that it might be a premature optimization (I don't have this problem *yet*), but protocol and map data structure will depend on that.

P.S.

The client and the server will be open source, so hacking the client will be easy

# Answer
Do the LOS and AOI (Area Of Interest) filtering on the server. Yes, any data you send the client can be hacked. OR extra programs can be inserted as a proxy between client and server to sniff excess data, like the old EverQuest viewer that lets players not only see far-away monsters but even what loot they would drop (which is a bit mind-boggling why that was pre-determined, but even with the loot bits it would be bad). It's also excessive bandwidth usage to tell clients about actors they can't possibly see or interact with.

Remember that you might also need some gameplay effects to be dependent on LOS down the road. The server is going to need to know LOS anyway in this case.

The server should be able to *easily* cope with calculating LOS for many players. First, you can use spatial partitioning and node graphs to quickly know if a player in node A is ever capable of seeing a player in node B or if the players are so far apart that they can never see each other. The actual LOS calculation can be done on greatly simplified meshes, too, as the server does not need every single triangle used for rendering to figure out LOS for gameplay and network purposes.

You can also move all LOS test into other threads relatively easily as most of the needed data is static (no synchronization needed) and a simple event queue can keep player positions updated between threads with no synchronizaton as well.

One thing to keep in mind is that you might want your LOS to err towards false-positives rather than false-negatives in most cases, especially for networking. If a player is just around a corner and still not visible, you might want to prime the client with some basic information so that there isn't any visibility lag when either play moves around the corner. Or you might want to err on the side of secrecy if ambushes and surprise are important to your gameplay. As always, networking realities are going to limit gameplay possibilities and gameplay is going to drive networking needs; part of the job of the networking engineer is to figure out this balance to the best extent and work with the gameplay engineers to make it work satisfactorily.

In general, especially for an MMO-style game without a lot of heavy shooter action, design towards all smarts being on the server and the client being as close to a dumb terminal as possible. All LOS checks, hit tests, movement, etc. should be server-side. The client might run some of these systems in parallel for prediction and lag-compensation purposes, but nothing the client does should be authoritative and the client should have zero information that the server doesn't explicitly want the player to have.
> 7 votes

# Answer
The best data sent is data not sent. This is basically information the client does not need; this is network bandwidth for useless data, and large-scale network bandwidth is costly.

Also consider that the processing taken up to calculate LOS would be (slightly) offset by not having to process and send all the additional network packets.

Edit: I suppose what I was trying to say was that, despite the added difficulty of handling LOS on the server, and any gameplay-related positives that would add, you should consider than not sending updates to the client for EVERY player/target, but rather only the ones they can perceive, is itself a big savings in bytes transmitted, which in a MMO type game results in lowered operating costs.
> 0 votes

---
Tags: mmo, server, line-of-sight
---


# Question
Title: Adobe Air Mobile AS3 app: challenges and how to overcome them?
I made a PC flash game for LD 26 - minimalism and I am working on porting it to Android.

Some questions I'd like to ask:

1. Is it *bad* to heavily use vector graphics (ie. `this.graphics.lineTo()`) in Mobile Air?
2. Does Stencyl completely alleviate this issue?
3. Are there any inherit disadvantages to using Air Mobile that I'm missing?
4. Where is the documentation for Air mobile (I googled and found no recent books or documentation pdf so far)

# Answer
Old question, but:

1. If you have your games using Vector graphics, it's not *bad*, but it's likely not good. You get much better performance with bitmaps, especially if you're using a framework to use hardware acceleration for those bitmaps (e.g. Starling). Sure, some games can work with vector graphics, especially if it's in the desktop. On a mobile device or the OUYA, though, using hardware acceleration is pretty much a requirement for 60fps.

Now, you can use `graphics.lineTo()` to create your assets prior to drawing them to a bitmap that is later used as a texture. Perfectly reasonable approach.

1. They don't give many details of how their stack run on the platforms they support. I'm normally wary of any platform that says "do without code!" where is something that always requires code. It means they want to make something simple and easy, but normally very templated and limited.
2. Inability to use native features like, say, platform-specific billing. This is a problem every cross-platform solution faces. With AIR, this is somehow solved by using Native Extensions.
3. "AIR mobile" doesn't exist, it's just AIR. You use the standard AS3 Reference. Be sure to select the version of AIR you're supporting from the header combo, and latest "Flash Player". The same classes are available on desktop and on mobile, although certain capabilities might not be supported (hence why some APIs have `isSupported` properties).
> 2 votes

---
Tags: android, flash, mobile, flex
---


title: Make a fake random distribution?

text:
# Question
Title: Make a fake random distribution?
Sometimes a "real" random event seems unfair and makes players frustrated. For instance a enemy has probability of 20% to cause double damage("critical hit"). Thus he could make 4 critical hits in a row with 1/725 probability. It's not as small as it sounds.

I hope the probability could be adjusted after each hit. If the player just got a critical hit, the probability decreases for the next hit. Otherwise it increases.

Is there a mathematical model for this behaviour?

# Answer
> 9 votes
You may wish to completely rethink what "critical hits" do in your system and why you're using them. "Well, other RPGs use them!" is not a valid reason. One warning sign of a skewed design is the need to apply more and more special rules.

Any kind of random bonus takes away from direct, tactical player skill and adds to strategic planning (RPG item load-out, prioritizing stats on gear, etc...). Because of this shift of focus **you have to decide what your game is about** before wantonly applying old standards like criticals and fumbles.

My suggestion is that if you want randomness to take any part in your game then glory in it, let it **be** random.

But if you really want to add more arbitrary rules you can simply **start a countdown when the first critical** happens and during that countdown any more criticals are reduced to 50% and then 25% and so on. **Each critical, of course, resets the countdown**. This gives you two places to tune your arbitrary rules: how long is the countdown and how much reduction is accumulated at each critical. A combination of those two controls lets you clearly avoid the unspoken problem of "what if the boss gets a critical, then normal, then second critical?" that a simple chain check wouldn't fix.

# Answer
> 5 votes
Dota 2 uses PRD (pseudo random distribution) which doesn't significantly affect the expectation, but decreases the chances of a streak, e.g. bash streak. Have a look at this, explains everything in detail. http://www.youtube.com/watch?v=KdS-K\_rosCI

# Answer
> 3 votes
I think this is a case where trying to be too smart will lead to a spiral of tweaks and adjustments to the random number generator that will make it very complex.

The answer might be in the question: if a player may get frustrated by too many critical hits in a row, well, directly reduce the odds of this happening. If the RNG draws a 4th critical in a row, you may for instance wish to re-roll it. Or even enforce `critical = false`.

# Answer
> 3 votes
One fairly common approach you can use that should give the results you're after: rather than *rolling a die* every time, instead *pick a card* : suppose you have a 1/10 chance of 'critical failure', a 4/10 chance of failure, a 4/10 chance of success, and a 1/10 chance of 'critical success'. Then rather than rolling a (metaphorical) d10 and handling the result, instead shuffle a stack of ten (virtual) result cards and deal them out, one by one, whenever you need to generate such a result. When you run out of your deck, just reshuffle and start dealing again. This can still generate back-to-back critical failures, but it guarantees that there will be success (and critical successes) within some reasonable span. If you want things to be not so obvious (and don't mind introducing a small chance of successive extreme results), you can always 'double up' your deck; build a stack of twenty cards which contains two copies of each result and shuffle that instead. (Note that in the limit of putting infinitely many copies of the deck together and shuffling them, this becomes exactly the roll-a-die approach.

# Answer
> 1 votes
Bayesian Inference deals with situation quite a bit. You start with a probability distribution for an event occurring, then once it does, you update this probability to a new one. These are the prior and posterior probabilities respectively. It's often most useful to view this in tree form (grabbed this off the internet).

In the tree, the branches represent the probability of taking that branch, and the nodes are the event. So in your case, let's make A,B,C the events of getting a critical hit with attacks A,B, and C resp. Then P and NP will be the events of getting another or not. We notice that at point (B -\> P) there is a 25% chance of getting another critical hit **given** that you got one the last turn. Of course your tree wouldn't look just like this, but it's the best I could do in 5 minutes.

# Answer
> 1 votes
I think there are already some nice answers given above but would suggest a different approach.

When the player makes a critical hit you are giving him a small reward to entice further play. Sort of like how a gambling addict will stay at the poker table for 'just a little longer' after winning a hand. When the enemy gets hit by a critical it might not be increasing the game experience at all but rather just feel unfair, especially if that was what made them lose the fight.

Thus my suggestion would be to just keep the crits for the player and not use them for the enemies at all. After all the player is a hero and should be favored by the gods themselves to achieve greatness :)

# Answer
> 0 votes
Here are random-but-not-completely random techniques I use.

1) Shuffle bag. Put all valid outcomes in a bag, choose one randomly and remove it from the bag. Repeat until the bag is empty then refill the bag. To add back in randomness, refill the bag when it only has X items remaining.

2) Progressive percentages. First roll X% chance, if fails second roll is X+Y%, then X+2Y% etc. Reset to X% on success. Both the start value, and progression can be adjusted (even non-linear).

3) Internal cooldowns. Roll X& chance, if success, do not roll for next N seconds or M attempts or whatever. Can be combined with other methods. To add in more randomness have multiple event checks with different coodlowns, ie make 2 rolls at 25% with 3 and 7 second internal cooldowns as opposed to 1 roll with 50% with a 5s icd (not exactly the same probability, but you can calculate and match if important).

4) Pre-rolled spacing. Rather than checking vs a percent each event, simply choose when the events happen. For example, "this boss crits every 1d4+4 attacks." Works well when the want something to happen relatively consistently, and somewhat random, but you don't want back to back events. In someways a special case of methods (2) plus (3). Again for more randomness you can have 2 or more overlapping sequences.

---
Tags: mathematics, random, probability
---


# Question
Title: Spawning entities in groups on a 2d tile-based map
I have a 2d game that generates an "infinite" map of tiles based on a "noise" height map. Each time a new "chunk" of 16x16 tiles is loaded, I have code that randomly chooses a "creature" to spawn into the game. Whether or not a creature will spawn on the tile is random, and which creature type is weighted/random.

However, I'd like to take this to the next level and design a creature that can spawn in **groups**.

I have a few choices:

* Spawn additional entities in a random set of surrounding tiles. Multi-chunk groups are impossible unless I write code to base spawns off of what already exists next to it.
* Create a new noise/height-map value that I then use to spawn entities with.

There are pros/cons to each, but I'm hoping someone with more experience can suggest which is better, or a third choice.

# Answer
> 1 votes
(Sorry, I don't know java, so I'll give my suggestion as if it was C++)

If the enemies that spawn in groups are logically related (ex. swarm of bees or something), you could make a swarm or herd or whatever class: `Class Swarm<EnemyType>`.

The swarm entity would basically just be a container that then itself spawns a certain number of whatever enemy it is related to (ex. bees) in it's constructor: `new Swarm<BeeEntity>`. You could even have it randomly choose how many to spawn

I'm not sure if this fits with your current implementation, but I see a few side benefits to it:

1) You could more easily implement group behavior as the individual enemies are collectively grouped by the swarm class. (For example, have the enemies in the group generally stick together, or act differently/more aggressive if they are the last one left).

2) The swarm is a single object, so you wouldn't need to make many changes to your height map.

# Answer
> 1 votes
In reference to the second choice of basing the groups off of the things next to them, I've done similar in path finding code, although the two may seem pretty dissimilar at first glance. It's a long answer, but it probably suites what you want nicely...

You may want the enemies to come from neighboring tiles. Picking neighboring tiles is probably something you've already precomputed if you do pathfinding, as it's computationally expensive to compute it whenever you need to build a new path.

The idea I have is to pick one random tile in which a Swarm is to begin, then use the neighboring tiles list or functionality you have to pick a neighboring tile. If it's uninhabited, then you can spawn the next one, and keep going until you have boatloads of bees, goblins, or Scientologists.

To do this, I can offer psuedocode. First, if you don't have neighboring tiles, sometime during initialization, you'd want something like this...

```
public class Tile
{
     // Tile stuff like location...
     private List<Tile> neighbors = new List<Tile>();

     public List<Tile> getNeighbors()
     {
          return this.neighbors;
     }
}

```

Now, in your level object, you'd want an initialization step that does basically the following, assuming Tile objects are stored in an array of width (width) and height (height), although I know you want to dynamically create the field, so you'd probably have 16 for both values, and create neighbors listings for each. You may also want to go back and connect the previous set of 16x16 to this one too..

```
public void createNeighbors()
{
     int i = 0;
     int loc = 0;
     int bounds = 0;

     for(i = 0; i < this.width * this.height; i++)
     {
          // Get the tile above...
          // Note that in normal person math, bounds cancels, but in integer math,
          // it actually gives you the start of a row of tiles...
          loc = i - this.width;
          bounds = (i / this.width) * this.width;
          if(loc >= bounds)
               this.tiles[i].neighbors.add(this.tiles[loc]);

          // Get the right tile...
          loc = i + 1;
          bounds = (i + (this.width - (i mod this.width));
          if(loc < bounds)
               this.tiles[i].neighbors.add(this.tiles[loc]);

          // Get the bottom tile...
          loc = i + this.width;
          bounds = this.width * this.height;
          if(loc < bounds)
                this.tiles[i].neighbors.add(this.tiles[loc]);

          // Get the left tile...
          loc = i - 1;
          bounds = (i - (i mod this.width));
          if(loc >= bounds)
                this.tiles[i].neighbors.add(this.tiles[loc]);
     }
}

```

The point to that bit of code is to precompute the neighbors so you can make an algorithm that searches the neighbors to spawn the next guy in a swarm. Let's say that you want to give a function the number of enemies, and a center tile, and it returns a list of tiles in which each enemy should spawn. That looks a lot like this...

```
public List<Tile> spawnGroupTiles(Tile start, int number)
{
     List<Tile> group = new List<Tile>();
     Tile current = start;

     if(number <= 0)
           return group;

     for(int i = 0; i < number; i++)
     {
           if(this.isOccupied(current) == false && group.contains(current) == false)
                  group.add(current);
           else
           {
                  Tile next = getNext(current, group, index);

                  if(next == null)
                          return group;

                  group.add(next);
           }

           current = group.last();
     }

     return group;
}

protected Tile getNext(Tile current, List<Tile> group, int index)
{
      List<Tile> neighbors = current.getNeighbors();
      boolean isFound = false;
      int i = 0;

      while(i < neighbors.size() && isFound == false)
      {
           Tile next = neighbors.get(i);

            if(this.isOccupied(next) == false)
                  isFound == true;
            else
                  i++;
      }

      if(isFound)
           return this.tiles[i];

      index--;

      if(index < 0)
          return null;

      return getNext(group.get(index), group, index);
}

```

This looks complicated, but basically, we're building a search out for unoccupied Tiles. If we can't find one next to current, then we go back one index in our list and try its neighbors, and so on, until we either find an unoccupied tile, or we've exhausted every connected searchable space. It's recursive, and a bit ugly, and I bet there is an error or two, but it should build a rough cluster of spawned enemies once all that is fixed.

For extra credit, it would be nice if it picked randomly from the neighbor list, so that the groups would not build first up, then left, then down, then right, however, I'll leave that one in your able hands.

---
Tags: java, game-design
---


# Question
Title: how do I make an enemy target an ally unit?
I have 2 different classes, a EnemyFighter class, and a EnemyBomber class. both are planes that I have that can fly around the map.( i also have AllyFighter, and AllyBomber)

So far they can follow me, and eachother, but how would I set up a target variable or something?

like I could set up a target variable for the enemyfighter

```
AllyFighter target;

```

and a variable holding the location of the allyfighter as a Vector2.

but then what if I want to target an AllyBomber? do I have to make 2 variables? or is there some other approach I should take?

Thanks

EDIT: Maybe a better question would be how can I target different enemy types (ones with different classes)? or at least hold there information in a 'target' variable

# Answer
> 3 votes
Ideally you'd have some parent class that all these classes inherit from. For example, if all of your planes inherited from `Plane`, then you could easily create a list of those different classes with something like:

```
List<Plane> targets = new List<Plane>();

```

Now you can add all your targets to the same list. Of course you can just have a single target too:

```
Plane target;

```

And then as long as `AllyFighter`, `AllyBomber` and so on all extend `Plane`, you can use the same variable.

Do note that you will only be able to access the data that's commonly stored your targets at the `Plane` level (apart from casting the object to the correct type). This means you'll want to store the important information for targeting at the `Plane` level (you likely would anyway since most of the information is going to be common to them all). So stuff like position, health, armor, etc. should be data inside `Plane` not inside `AllyBomber`.

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


title: Air Resistance of a Falling Object

text:
# Question
Title: Air Resistance of a Falling Object
I am applying air resistance to a falling sphere using the Euler method. If someone could have a look and tell me if my implementation is correct or offer any tips, it would be highly appreciated.

Calculations taken from http://en.wikipedia.org/wiki/Drag\_(physics)

```
float Mass = 10;
float Radius = 5;
Vector Gravity = Vector(0, 9.8, 0)

float p = 1.293f;              // Air Density;
float A = pow(Radius, 2) * PI; // Cross Section Area;
float Cd = 0.47f;              // Drag Coefficient For Sphere;

float terminalVelocity = sqrt(2 * Mass * Gravity.magnitude / p * A * Cd);

// Update

Vector acceleration = Gravity * ( 1 / Mass);

m_velocity += acceleration * Time.deltaTime;

float drag = 0.5f * p * pow(m_velocity.magnitude, 2f) * Cd * A;

m_velocity -= new Vector3 (0, clamp(drag, 0, terminalVelocity), 0);

m_position += m_velocity * Time.deltaTime;

```

Cheers

# Answer
Let `x` and `v` be the original position and velocity, respectively. Your update loop should look like:

```
fg = -g * m
vn = normalize(v)
fd = -vn * 0.5f * p * Cd * A * v^2
a = (fg + fd)/m
v += a * dt
x += v * dt

```

where `g` is the gravitational magnitude, `m` is the mass, `fg` is the gravitational force, `fd` is the drag force and `a` is the acceleration. You can see that when you run this with your values `v` approaches your above calculation for terminal velocity.
> 1 votes

---
Tags: physics, euler-method
---


# Question
Title: How should I distribute the values of equipment stats when I know the average value?
I am making a Diablo-like game and I want to randomly generate the stats of the loot that gets dropped. I'll use "damage per second" as an example. I've filled a spreadsheet with two columns of numbers. The first column is the `level`, the second column is the `average damage per second`. So when you look at a row of the spreadsheet it'll say something like, "at level 50, the average damage per second should be 100". From here there are many branches I could take:

1. Decide that the range values are not weighted. In which case, all you have to do is find a range below and above the average and randomly generate numbers in that range. For example, I'll arbitrarily decide that 20% is a good number and then the random range goes from 80 to 120. AFAIK, as long as that same % is added and subtracted to the number, then it should average out to 100.
2. Decide that the range values *are* weighted. In this case, I want the higher stats to be more rare than the lower stats. So *if* the range were between 10 to 20, it would be more common to get a 10 than a 20. But, I think that there are other unknowns I have to solve first. Like, I probably need to figure out *how* I want the numbers weighted. I know how to set up weighted random values. But I don't know how to guarantee the average of the values is the number I want. How would I figure that out?

1) Seems way easier to code and balance. But I'm wondering if it's a poor choice for a loot system. If all the popular games out there use this, that's good enough for me and I'd consider that an answer.

On the other hand, if they use something like 2), I'd like to figure out how I can use the average as input to get the weighted range as output.

And if there's a 3) I haven't thought of that most games use, I'd like to hear about that.

# Answer
> 0 votes
I found an answer here that gives a really easy to understand algorithm that can be used. He says himself it's not correct, but rather an approximation, but that's good enough for my needs. I'd like to know if this is an accurate approximation. I'll inline a summary in case it goes down some time:

> Random numbers are an essential part of computer games and simulations. Functions in most software development tools output random numbers with uniform distribution. Simulations often need random numbers in normal distribution. An easy way to approximate normal distribution is to add three random numbers:

```
G = X + X + X

X = a uniformly distributed random number between -1 and 1.

G ~ a standard normal random number.

```

> To adjust the result for your needs, just multiply by your desired standard deviation and add your desired mean.

```
R = Gσ + μ

```

# Answer
> 2 votes
For 2, you could sample your values from a limited normal distribution. That way, you would be guaranteed to have a set mean and variance that you define, and extreme values would be less likely than those closer to the mean. This seems better to me than 1 which I assume would be uniformly sampled.

I use Python most, so the numpy docs give a good overview of how to use the normal distribution: http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html#numpy.random.normal

Of course, with a normal distribution, it's possible (but extremely unlikely) to get extreme values, so you would want to put explicit bounds on it, like:

```

while s<90 or s>100:
    s = np.random.normal(mu, sigma)

```
.

I'm not a programmer by nature, so maybe there's a better way to do that, but hopefully you get the picture. Hopefully you would play around with the variance enough to where that loop wouldn't run more than a couple times.

# Answer
> 0 votes
If you decide to go with 1, I would strongly encourage you to use a standard random deviation. To do this, you would have your mean (average) value for every level and then the standard deviation for everyone level. You could really just use the same deviation for all of the different levels if you wanted to. 95% of the random values would be between your mean+- your deviation. This would give you control over what the 'normal' values would be and still allow 'rare' items buffs. You could even determine buffs such as 'legendary' or 'great' by how many deviations to item is from the mean.

This question should tell you all you need to know about generating the numbers based on a standard deviation.

Wikipedia on Standard Deviation Wikipedia on Box-Muller transform

---
Tags: game-design, random, balance
---


# Question
Title: how to add different class items to the same list C# XNA
I am trying to make a modular ship system, where parts can be added or removed to the ship entity.

I am using a class I made called `ModuleManager` and it has a list of `ShipModules`. this works fine for very basic block building ships, but I want to add a `ThrusterModule` that has thrust capabilities, and possible a `GunMountModule` for obvious reasons.

the problem is that I cannot do this.

```
List<ShipModules> modules = new List<ShipModules>();
ThrusterModule engine = new ThrusterModule();
modules.Add(engine);

```

I know that I cannot do this because they are different types.

Question: How can I add all these modules to the module manager? because I don't want to have to deal with having several different type modules that need several different variables to hold them

I have an idea of what to do, but I want to know if it would be the best route, I have heard of Class Composition. would that be beneficial for what I have explained? thanks.

# Answer
> 1 votes
This is essentially the same problem you had before. If all the modules inherit from the same class you can add all of them to the same list.

You could store a type ID in the `ShipModules` class to identify what type of module the module is for the purpose of casting it. However, I'd suggest that if you want to have specific module functionality, you keep all those modules of the same type in a separate list.

So, if you want to have a list of `ThrusterModule`'s only, you can create a list specifically for them.

# Answer
> 0 votes
your ship must have a components map, then it can have one IEngine, by example, but you can create a lot of inherited Engine and switch as you want.

A good book about game architecture : http://www.amazon.fr/Game-Coding-Complete-Mike-McShaffry/dp/1133776574

# Answer
> 0 votes
as Blau said, try with interface instead. Create a basic IShipModule interface, and you'll extend it to all the classes that will act as module for your ship.

```
 class GunMount : IShipModule

 class Thruster : IShipModule

```

and your list will holds all the classes that extends the interface IShipModule .

Look here for explanation, its in java but you should understand anyway

---
Tags: xna, c#, component-based
---


title: Modern opengl for direct3d programmers

text:
# Question
Title: Modern opengl for direct3d programmers
I don't think this is quite the same questions as this one but if you disagree feel free to close this :)

With SteamOS being announced yesterday I can see that it's entirely possible that opengl will get a big boost in usage in the near future. Now I already know direct3d11 quite well but I think maybe it's time to learn opengl too.

Are there any good resource for learning **modern** opengl that are aimed at programmers who already know direct3d11 pretty well. So don't need any education on the concepts and math, just on how to use the API and any important differences?

# Answer
Since you already know the math and 3D programming and only want to learn the API I might say that OpenGL Superbible 5th Edition (which is the one I read) or the newer OpenGL Superbible 6th Edition might be your best bet, the books don't talk about all the deprecated features in OpenGL (which isn't the case with the red book). The book explains the "modern" API nicely, the problem though it suffers from; is that it uses its own wrapper library, especially in the introductory chapters where it hides a lot of the details, that is to be able to explain how basic math and rendering work for beginners without dealing with a lot of the openGL details. I read the 5th edition book to upgrade from openGL 2 to OpenGL 3, and I didn't find this a problem, so I would say if you are not a beginner in 3D programming ( regardless of your background ) it will be "enough" to get started.

\[Edit\] Based on comments, the books cover the different kinds of buffer objects including but not limited to Vertex Buffer Objects(VBO), Pixel Buffer(PBO), Frame Buffer Objects(FBO) and Texture Buffer Objects(TBO).
> 2 votes

# Answer
If you already know D3D, then it's only a matter of getting used to the API. For that, specifically these three tutorial series should cover everything you need to know. For other stuff, the official OpenGL reference pages are pretty excellent and rarely leave questions open.
> 1 votes

---
Tags: opengl
---


title: Entity systems, creating new entities?

text:
# Question
Title: Entity systems, creating new entities?
How do I create new entities (the collection of their components) in an entity system? I have space ships in my game, for example, they need a lot of information set in their components when I create them. For example I set the mass, size and a moment of inertia tensor in a physicscomponent of the ship. I also have a component that contains a list of engines on the ship (is that right by the way? My ES doesn't support multiple components of the same type, should it?), each engine has a position and a force.

Now when creating a basic ship I see a couple of options. I can just hard-code it in my game. This is the way I have it at the moment, and it doesn't feel too good, there will be a lot of code to create different kind of space ships that are very similar except for some properties which would create lots of code duplication.

I could also use a database, I've seen this used before and I can definitely see how it'd be a good fit. Although it's a pretty small hobby project that I'm working on and it seems like it would be a little overkill. I'm not sure though, maybe it's worth it?

So the only thing remaining I can think of is describing entities in a text file of some sort, which might work. I guess it would require writing lots of code to parse different kinds of values, and where would I put the code that actually sets the values on the components? I'm using C# so I guess I could use reflection on the properties but I fear it'd be slow? And I don't want to clutter up my component code.

Maybe I should mention that it's a multiplayer game. So some components are client-only which could easily be marked in some way.

So how do you create new entities, or their components, in an entity system?

# Answer
Create 2 factories : the ship factory, and the component factory.

All your ship's components and their configurations are storage in XML, then you feed your ship factory with the XML, it creates the ship first, and it call the component factory on each component described in the XML, to create the appropriate objects and bind them to the ship

By Example :

```
<ship>
 <Mass>100</Mass>
 <Size x="12" y="18" z="20"/>
 <thruster>
  <force>200</force>
  <warmupTreshold>500</warmupTreshold>
 </thruster>
</ship>

```
> 4 votes

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