title: How do you parameterize turn based AI?

text:
# Question
Title: How do you parameterize turn based AI?
I would like to create/find an AI algorithm/process that can be parameterized such that a change in the parameters causes a change in the AI behavior. I am specifically looking to apply this to a turn based game environment where the player is able to perform several moves (or none at all) in a single turn. The player has full knowledge of the board and should be able to take the opponent's current positioning into account when deciding what moves to make in the current turn.

My question is how can I create this type of AI? An example of behavior that I would like it to show in various situations would be:

```
Turn X: Attack location A with 7 units and attack location C with 12 units
Turn Y: Do nothing
Turn Z: Invest in resource collection

```

Then a small change in a parameter may cause the AI to only send 6 units to location A instead of 7 in the same situation as Turn X.

My only thought of how to implement something like this would be to have the parameters act as probabilities of doing action T with magnitude R. However, I could imagine how this wouldn't facilitate long term thinking, and I also have no idea how that approach would take the opponent's positioning into account. I also suspect that this approach would cause the AI to overspend within a single turn, as in, it tries to attack 3 locations with a total of 30 units, but it only has 15.

I've spent the last few hours looking through Google Scholar and have found a few papers that say that they have used a parameterized AI approach, but they don't discuss any actual implementation details. If anyone could tell me what this concept is normally called (so I can Google and research it further) or has any reference links to code that uses an implementation like this then I would really appreciate you adding it as an answer.

Also, just so people don't waste their time answering something that isn't needed, I'm only interested in the design/structure of the described process, I am *not* looking for ways to get good values for the parameters.

Thanks everyone!

# Answer
> 2 votes
I communicated with Christoph Salge who was one of the authors of "Using Genetically Optimized Artificial Intelligence to improve Gameplaying Fun for Strategical Games" and he had the following helpful advice:

> If it helps, I can tell you in a nutshell what we have told the students who have been developing the AIs back in our project.
>
> The basic idea is to first develop a classical AI that plays the game.
>
> This can be a rule based system, some swarm intelligence approach, etc. You saw the list in our paper, but basically anything that can play the game to some extend works.
>
> Then you go through your code an identify anything that is a parameter. Basically anything that is a specific value that you guessed or just fixed, like thresholds, probabilities, etc. For example, lets say that your AI send agents to search for food when their health is low; how low, ... well you just guess that below 30 % would be a good value. So, 30% would be such a parameter.
>
> I don't know what programming language you are working with, but a lot of them offer the option to define certain values as constants. C++ for example has the #define CONSTANT *value* precompiler command, which basically just replaces every mentioning of the word CONSTANT with *value*. So you could then replace 30% in the code with Constant\_Search\_For\_Food, and define Constant\_Search\_For\_Food as 30%.
>
> After you identified which values you can tweak in your AI code, you can then put them into a container class which stores the genome. You then replace all the CONSTANTS with functions. So Constant\_Search\_For\_Food will then be replaced by genome.whatIsTheValueOf(Constant\_Search\_For\_Food), which looks up the value. This class can then also be used to map parameters with different value ranges to the range between 0 and 1. So, externally, Constant\_Search\_For\_Food goes from 0 to 100 percent, but internally in the genome class, it is then represented as a value between 0 to 1.
>
> After that is done, you can then apply a genetic algorithm to optimize the genome. So, your genome is an array of values between 0 to 1. You take a genome, and evaluate its fitness by having the AI play the game with this genome, and tallying the result. The fitness is the success in the game, and you can use this fitness to determine who should procreate. There are also a lot of good toolkits for that out there, so you do not necessarily need to write your own.
>
> This should then produce AIs that are better at the game, or just better against other AIs, or as we found out, good at crashing the game, if that is rewarded.
>
> As an afterthought: If you are going for machine learning approach, such as using a neural network, the idea is slightly different. In this case, your whole AI basically is parameter values, so you can skip the design an AI part, and immediately start with the artificial evolution, like we did in "Relevant information as a formalized approach to evaluate game mechanics". But then the technique is not explained in great detail there either.

When I get around to applying this technique to the 'Counselor AI' paradigm that Christoph mentions in section 7.2 of his paper I'll add that info to this answer.

---
Tags: architecture, algorithm, ai
---


title: Directional light and matrix issues

text:
# Question
Title: Directional light and matrix issues
I'm trying to implement basic directional lightning in OpenGL 3.3 by emulating the logic shown in this guide: http://www.arcsynthesis.org/gltut/Illumination/Tutorial%2009.html

I do not understand what matrix to send to the vertex shader to use for calculating lightning effects. The guide says modelView matrix, but to me, and when I'm running the game, it dosn't make sense; when I orient myself in the world with mouse and keyboard, the lightning direction gets altered aswell!

Here's the items to which I fill my 'render queue', which contains all data needed to draw the models:

```
/* RenderItem definition */
    struct RenderItem
    {
        VertexBufferPtr mVertexBuffer;
        const Vec4 mColor;
        const Mat4 mMVP;
        const Mat3 mMVMatrix;    // I used model-view matrix here, but I dont know really which one to use

        const Vec4 mLightIntensity;
        const Vec3 mDirToLight;

       // simply extracts all the struct data into one buffer to be uploaded as UniformBuffer to shader
        void CopyUniformData(std::vector<float>& buffer) const
        {
            std::vector<float> colorValues = GetTypeValues(mColor);
            std::vector<float> mvpMatrixValues = GetTypeValues(mMVP);
            std::vector<float> mvMatrixValues = GetTypeValues(mMVMatrix);
            std::vector<float> lightIntensityMatrixValues = GetTypeValues(mLightIntensity);
            std::vector<float> dirToLightMatrixValues = GetTypeValues(mDirToLight);

            buffer.insert(buffer.end(), colorValues.begin(), colorValues.end());
            buffer.insert(buffer.end(), mvpMatrixValues.begin(), mvpMatrixValues.end());
            buffer.insert(buffer.end(), mvMatrixValues.begin(), mvMatrixValues.end());
            buffer.insert(buffer.end(), lightIntensityMatrixValues.begin(), lightIntensityMatrixValues.end());
            buffer.insert(buffer.end(), dirToLightMatrixValues.begin(), dirToLightMatrixValues.end());
        }

        RenderItem(VertexBufferPtr vertexBuffer, const Vec4& color, const Mat4& mvp, const Mat3& mv, const Vec4& lightIntensity, const Vec3& dirToLight);
    };

```

Here's where I create all the RenderItems for my renderqueue:

```
void Engine::CreateModelRenderables(const Model* model, const Mat4& viewMatrix, const Mat4& perspectiveMatrix, const Mat4& nodeTransform, std::vector<RenderItem>& renderQueue, const std::vector<LightPtr>& activeLights)
    {
        const Mat4 modelMatrix = nodeTransform * model->mTransform;       // 'nodeTransform' is the SceneNodes transform, while model->mTransform is the models transform... so this gives the model-world matrix
        const Mat4 modelViewMatrix = viewMatrix * modelMatrix;
        const Mat4 modelViewProjMatrix = perspectiveMatrix * modelViewMatrix;

        // 'activelights' is a vector, but for now only one light is supported, so I just pick the first element

        // TODO: handle multiple lights
        BOOST_FOREACH(const Mesh& mesh, model->mMeshes)
            if (activeLights.size() >= 1)
                renderQueue.push_back(RenderItem(mesh.mVertexBuffer, Vec4(1.0f, 0.3f, 0.3f, 1.0f), modelViewProjMatrix, Mat3(....???....), activeLights.front()->mLightIntensity, activeLights.front()->mLightDirection));
            else
                renderQueue.push_back(RenderItem(mesh.mVertexBuffer, Vec4(1.0f, 0.3f, 0.3f, 1.0f), modelViewProjMatrix, Mat3(....???....), Vec4(0.0f), Vec3(0.0f)));

        BOOST_FOREACH(const Model& childModel, model->mChildren)
            CreateModelRenderables(&childModel, viewMatrix, perspectiveMatrix, modelMatrix, renderQueue, activeLights);
    }

```

for drawing, I just loop over the renderitems, update the UniformBuffer object and glDrawElements (vertexbuffer-\>render):

```
void OpenGLRenderer::DrawRenderables(const std::vector<RenderItem>& renderQueue)
    {
        BOOST_FOREACH(const RenderItem& renderItem, renderQueue)
        {
            mUniBuffer.SetData(renderItem);

            renderItem.mVertexBuffer->Render();
        }
    }

```

this is my vertex shader:

```
const std::string gVertexShader =   "#version 330                                               \n  \
                                                                                \n  \
                                        layout(std140) uniform DefaultUniform                       \n  \
                                        {                                                           \n  \
                                            vec4 Color;                                             \n  \
                                            mat4 MVPMatrix;                                         \n  \
                                            mat3 MVMatrix;                                          \n  \
                                                                                \n  \
                                            vec4 LightIntensity;                                    \n  \
                                            vec3 DirToLight;                                        \n  \
                                        };                                                          \n  \
                                                                                \n  \
                                        layout(location = 0) in vec3 vert_position;                 \n  \
                                        layout(location = 1) in vec3 vert_normal;                   \n  \
                                        out vec4 frag_color;                                        \n  \
                                                                                \n  \
                                        void main()                                                 \n  \
                                        {                                                           \n  \
                                            gl_Position = MVPMatrix * vec4(vert_position, 1.0f);    \n  \
                                                                                \n  \
                                            vec3 normCamSpace = normalize(MVMatrix * vert_normal);  \n  \
                                            float angIncidence = dot(normCamSpace, DirToLight);     \n  \
                                            angIncidence = clamp(angIncidence, 0, 1);               \n  \
                                                                                \n  \
                                            frag_color = LightIntensity * Color * angIncidence;     \n  \
                                        }

```

the fragment shader simply passes-through the frag\_color..

Here is my camera class used to generate the viewMatrix through getCameraTransform(), in case there might be something wrong there? I don't think so though, as I can move around in the world with WASD + mouse just as expected

```
Camera::Camera() : mTranslation(0.0f), mHorizontalAngle(0.0f), mVerticalAngle(0.0f)
    {
    }

    Camera::~Camera()
    {
    }

    void Camera::SetPosition(const Vec3& position)
    {
        mTranslation = position;
    }

    void Camera::TranslateCamera(const Vec3& translateVec)
    {
        mTranslation += translateVec;
    }

    void Camera::RotateCamera(const float offsetHorizontalAngle, const float offsetVerticalAngle)
    {
        mHorizontalAngle += offsetHorizontalAngle;
        mVerticalAngle   += offsetVerticalAngle;
    }

    Vec3 Camera::Forward() const
    {
        Vec4 forward = Inverse(Orientation()) * Vec4(0, 0, 1, 1);

        return Vec3(forward);
    }

    Vec3 Camera::Right() const
    {
        Vec4 right = Inverse(Orientation()) * Vec4(-1, 0, 0, 1);

        return Vec3(right);
    }

    Mat4 Camera::Orientation() const
    {
        Quaternion rotation;
        rotation = AngleAxisToQuaternion(mVerticalAngle, Vec3(1.0f, 0.0f, 0.0f));
        rotation = rotation * AngleAxisToQuaternion(mHorizontalAngle, Vec3(0.0f, 1.0f, 0.0f));

        return QuaternionToMat4(rotation);
    }

    Mat4 Camera::GetCameraTransform() const
    {
        Mat4 viewMatrix(1.0f);
        viewMatrix = Orientation() * Translate(viewMatrix, mTranslation);

        return viewMatrix;
    }

```

SO, my question is, what matrix should the MVMatrix be in the vertex shader? The guide says the 'modelToCameraMatrix', which I suppose is my modelViewMatrix in Engine::CreateModelRenderables(), but I don't want the lights direction to change when I re-orient my camera!

EDIT: Alright, I tried to perform the lighting in world space; so I pass the 'modelMatrix ' as the 'mMVMatrix' in the shader and change nothing else. What happens is, lighting is only applied when changing the X-value of LightDir; changing Y/Z values have no effect. Why is this?

# Answer
> 0 votes
Alright, I solved it.

First I did as people mentioned; use world space instead, but I got some very strange unexplainable lighting effects.

After some experimentation I realised I can do the lighting calculations in world space just fine if I supply a mat4 model-to-world matrix rather than a mat3 model-to-world matrix to the vertexshader for the normal. I believe it has something to do with translation, since the objects in question were translated away abit from the camera, but if anyone has a complete answer I would be happy to hear it.

# Answer
> 1 votes
From the linked article:

> You certainly could use world space to do lighting. However, for our purposes, we will use camera space. The reason for this is partially illustrative: in later tutorials, we are going to do lighting in some rather unusual spaces. By using camera space, it gets us in the habit of transforming both our light direction and the surface normals into different spaces.

So feel free to use the model-to-world matrix instead of model-to-camera matrix. If you are going to use model-to-camera matrix as the article suggests, you also need to transform your lights to the camera space in the shader.

# Answer
> 0 votes
I'm not sure what you're trying to do there but try and send the light's world matrix to the shader, after all, all light effects are relative to that space. The only situation where the position of your camera interferes with your lighting calculations is when you implement specularity.

---
Tags: c++, opengl, mathematics, shaders, matrix
---


# Question
Title: Why texture coordinate of flat surface reflection is calculated like this in fragment shader?
The whole project is here: https://developer.apple.com/library/mac/#samplecode/GLEssentials/Introduction/Intro.html

The rendering flow is like this:

1. Render the character upside down to a texture.
2. Render the character normally.
3. Render the flat reflection surface below the character using the texture from step 1.

I don't understand the texture coordinate calculation in the fragment shader, specifically the block marked with `???` below:

```
precision highp float;

// Color of tint to apply (blue)
const vec4 tintColor = vec4(0.0, 0.0, 1.0, 1.0);

// Amount of tint to apply
const float tintFactor = 0.2;

varying vec3  varNormal;
varying vec3  varEyeDir;

uniform sampler2D diffuseTexture;

void main (void)
{
    // Compute reflection vector
    vec3 reflectDir = reflect(varEyeDir, varNormal);

    // Compute altitude and azimuth angles
    vec2 texcoord;

    texcoord.t = normalize(reflectDir).y;
    // ???????????????????????????????????????????????
    reflectDir.y = 0.0; // Why clear reflectDir.y?
    texcoord.s = normalize(reflectDir).x * 0.5; // Why times 0.5?

    // Translate index values into proper range
    if (reflectDir.z >= 0.0) {
        texcoord = (texcoord + 1.0) * 0.5;
    } else {
        texcoord.t = (texcoord.t + 1.0) * 0.5;
        texcoord.s = (-texcoord.s) * 0.5 + 1.0; // Why translation of s is like this, different from t?
    }
    // ???????????????????????????????????????????????

    // Do a lookup into the environment map.
    vec4 texColor = texture2D(diffuseTexture, texcoord);

    // Add some blue tint to the image so it looks more like a mirror or glass
    gl_FragColor = mix(texColor, tintColor, tintFactor);
}

```

Thanks in advance to anyone who can demystify this for me!

# Answer
> 1 votes
They seem to be using a kind of quasi-polar coordinates for the texture. The code you marked off is concerned with measuring the relationship of `reflectDir` to the coordinate axes and mapping that into texture coordinates.

First, it takes `reflectDir.y` to be the t component of the texture coordinate. In both cases of the if-statement, it adds 1 to this and multiplies by 0.5 in order to map it from the \[-1, 1\] interval to \[0, 1\].

It then zeroes out the `reflectDir.y` and renormalizes, in order to look only at the horizontal components of the vector in what follows. For the horizontal component there are two cases, based on whether z is positive or negative. In either case, it uses `reflectDir.x` for the s component of the texture coordinate, but mapped in a different way: for positive z, it maps \[-1, 1\] to \[.25, .75\], and for negative z it maps \[-1, 1\] to \[1.25, .75\]. After texture wrapping, the latter case will end up occupying the intervals \[.75, 1.0\] and \[0, .25\], so it fills the parts of the texture not already occupied by the positive-z case.

The net result is that you have something a kind of like a latitude-longitude map, but much cheaper to evaluate since it uses only normalizes, dot products, and linear math rather than inverse-trig functions. Like a lat-long map, it has the +Y axis at the top and the -Y axis at the bottom, with the entire 360 degrees of the horizon laid out along a horizontal line through the center of the texture. It will probably appear more distorted than a lat-long map, though; it'll be more pinched at the poles and it will have pinching also on the vertical lines at s = 0.25 and 0.75, where the positive/negative z parts come together.

---
Tags: textures, reflection-rendering
---


# Question
Title: How do I implement my old OpenGL-based gfx_render_triangle_list using DX11?
I am working at a game that has lots of procedural content. I had built a game engine using OpenGL that handles everything needed for creating a basic 2D game, sprites, primitives, blending, polygons etc. At a particular moment I decided to implement target textures to obtain interesting effects and problems started to arise: Sometimes the engine did not initialize OpenGL and GLEW properly and could not isolate the exception. Finally I abandoned the idea of using OpenGL because of similar issues (SOMETIMES cannot use newer GLEW functions...NOTE:drivers up to date). I decided to use DX11 instead and take benefit from the new technologies of the latest GPUs. So I did. Now I am porting my engine to DX11 and I am quite stuck.

I had procedures to be called in a `render()` function, like:
`engine->gfx_render_triangle_list(pointer)`
which in principle just called a procedure like

```
glBegin(GL_TRIANGLES);
...
glVertex2f(.....);
...
glEnd();

```

Now the problem that arises for me is the new pipeline of DX11. Load up vertices in the VertexBuffer, process them by the VertexShader then fill them with pixels and transform with the PixelShader. This is great as I have full access to what is being displayed on the screen, but, how do I do it the 'old-fashion' way?

I mean, how do I draw primitives like in OpenGL, each frame sending unique, new triangles to the screen. I didn't find any resources that explain this and I cannot think this through myself, loading some vertices in the vertex buffer is designed for meshes that are human made and static and they are only transformed by the shaders.

Long story short: How do I implement my old gfx\_render\_triangle\_list using DX11? NOTE: My engine will be used as a DLL.

# Answer
> 5 votes
The `glBegin`/`glEnd` API is actually deprecated (i.e. you're not supposed to use it anymore) in OpenGL, and Direct3D has no equivalent functionality. This is as it should be, because making several function calls to specify each vertex is *horrifically inefficient* if you have any substantial amount of geometry.

The modern way to do this - in *either* API - is with vertex buffers, which can be static or dynamic. Static vertex buffers are typically used for models that are loaded once from disk and rendered many times without alteration. Dynamic vertex buffers are used for things like particle systems, where the geometry changes every frame. It sounds like for your animating procedural geometry, dynamic vertex buffers are the way to go.

There's a more in-depth tutorial on D3D11 dynamic vertex buffers here \- and note that the same thing can be done in OpenGL, with vertex buffer objects \- but the basic idea is as follows:

1. During startup, create a vertex buffer with "dynamic" usage.
2. Each frame, "map" the buffer with the "discard" flag. This gives you a pointer to the buffer's memory. The "discard" flag means you don't need access to the previous contents of the buffer (since you're going to regenerate it from scratch anyway). This allows the vertices to be double-buffered (or triple-or-more-buffered) under the hood by the graphics driver, which is necessary to keep the CPU and GPU running efficiently.
3. Using the pointer, fill the buffer with your vertices, generating them however you please.
4. Unmap the buffer and render it.

---
Tags: opengl, c++, directx, directx11
---


# Question
Title: LWJGL Game crashes on some other machines
I just tried running my game on a friend's laptop, but for some reason it crashes. The exported .jar runs fine on my machine, and some others too. I can see that is has something to do with the glDrawArrays function, that is this code:

```
glPushMatrix();

glTranslatef(pos.x*world.chunkSize.x, 0.0f, pos.y*world.chunkSize.z);

glBindBuffer(GL_ARRAY_BUFFER, vao_id);

glVertexAttribPointer(world.game.positionAtt, 3, GL_FLOAT, false, 36, 0);
glVertexAttribPointer(world.game.normalAtt, 3, GL_FLOAT, false, 36, 12);
glVertexAttribPointer(world.game.texCoordAtt, 2, GL_FLOAT, false, 36, 24);
glVertexAttribPointer(world.game.lightAtt, 1, GL_FLOAT, false, 36, 32);

glDrawArrays(GL_TRIANGLES, 0, arraySize / 9);

glBindBuffer(GL_ARRAY_BUFFER, 0);

glPopMatrix();

```

As said, the exact same .jar runs fine on my system, and some more I have tried it on.

My friend's pc has Intel HD Graphics 3000, with GLSL version 1.40 and OpenGL 3.1.0.

Crash dump: http://pastebin.com/X8x4xX8j

Thanks in advance.

# Answer
> 1 votes
Ok, found it. It was a problem in the fragment shader. I passed a vec3 in a vec2 to the fragment shader. For some reason my Ati card driver accepted it, but for example Intel didnt. Thanks for the help all.

# Answer
> 1 votes
LWJGL comes with `lwjgl.jar`, which is needed in your classpath to run the program. It also comes with `lwjgl-debug.jar`, which can be used instead to find out incorrect OpenGL usage. Either replace `lwjgl.jar` with `lwjgl-debug.jar` in your classpath or just rename the files accordingly if that is easier.

The debug version of LWJGL will call glGetError after all OpenGL calls where it is allowed. If the result is not GL\_NO\_ERROR, it throws an Exception containing the type of the error. You can then check from the stacktrace or by using a debugger which of your OpenGL calls was incorrect. Together with the documentation of the the function you can find out what is wrong.

While this approach doesn't find out all problems and the results differ between graphics cards, it does pretty good job on ensuring that you are using OpenGL correctly. For example I just found out few days ago with this method that I was also passing vector of wrong dimension as a uniform to a shader. I recommend to test the application with the debug version with at least AMD and nVidia cards.

When you are releasing the game, make sure to use the non-debug version of the library again.

---
Tags: opengl, java, glsl, lwjgl
---


title: XNA draw model partially

text:
# Question
Title: XNA draw model partially
Is it possible to draw a model partially (along the X, Y or Z axis) to make an extending barrier or something like that? (Scaling doesn't work because of the textures)

# Answer
It is possible. There was a nice feature in XNA pre-4.0 called ClipPlanes. There are several good tutorials on how to use them, I'd recommend this one:

Riemers XNA Tutorial - Clip planes

Now the problem is, ClipPlanes have been removed from XNA 4.0. Developers are supposed to implement it using shaders. I've found the following piece of code to do exactly this:

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

float4 ClipPlane0;

void vs(inout float4 position : POSITION0, out float4 clipDistances : TEXCOORD0)
{
    clipDistances.x = dot(position, ClipPlane0);
    clipDistances.y = 0;
    clipDistances.z = 0;
    clipDistances.w = 0;

    position = mul(mul(mul(position, World), View), Projection);
}

float4 ps(float4 clipDistances : TEXCOORD0) : COLOR0
{
    clip(clipDistances);

    return float4(0, 0, 0, 0); // TODO: whatever other shading logic you want
}

technique
{
    pass
    {
        VertexShader = compile vs_2_0 vs();
        PixelShader = compile ps_2_0 ps();
    }
}

```

I didn't test it myself, but I hope it helps.
> 2 votes

---
Tags: xna-4.0, models
---


# Question
Title: What is the best design pattern to apply effects and abilities?
What would be the best design pattern to apply effects and abilities in a game. For example:

I have a unit that has base stats like attack power, defense etc. The unit can hold several items that will boost one or more of these effects. Also the unit can have several skills that can either boost stats, or be like a special attack. The trick behind the skills is, it should get stronger per level.

I have the following requirements:

1. Data for the skills and items should be loaded through (for example) xml or serialized classes.
2. The skills should contain a level system. Each level they increase in strength (but not with a fixed percentage each level).
3. An item or skill can have multiple effects (time based and immediate effects).
4. The skills should have something like an Execute method with a target unit (for example special attack on unit Y) This effect has a graphical representation (like a rocket firing) that should occur and an effect (damage, armor decrease etc) on the target. This effect could be applied over time or instantaneously.

What is the most usefull design pattern to achieve this?

I can think of the following:

I have several classes: Unit, Ability, Effect.

The Unit class has an array of applied Effects. On add to and on remove from this array the Apply and Remove methods on the Effect class are called, with the Unit object as parameter. The Effect class then handles the appropriate Boost or Decrease on the Units properties. This will work, however, I don't see this working with time based effects.

Are there better solutions?

# Answer
> 4 votes
So this sort of system can be really long winded to describe, I'll try to summarize briefly how we've usually done it in the past with some variation depending on needs but the starting point of my design has usually been something like the following.

### Unit/Entity

Unit has many behaviors, behaviors are "stepped" per time step.

### Behavior/Modifier

Behavior belongs to a target, behaviors are functors with variations such as, apply effect behavior, applies an effect every N seconds for T seconds, expires after LT seconds.

### Ability/Action

Ability applies an effect to a target.

### Effect

Effects are functors, with variations like modify unit, create unit, apply behavior, apply effect set (supports conditionals).

### Example

So a basic flow for lets say a damage over time ability would be something like this, Unit uses ability A, ability A ensures the target is valid, if valid applies an apply behavior effect to target of ability A.

The behavior applied expires after 10 seconds, and every two seconds it applies an effect to modify subtracting 10 health.

---
Tags: design-patterns
---


# Question
Title: What are some good learning resources for OpenGL?
I have been using the OpenGL ES on the iPhone for a while now and basically I feel pretty lost outside to the small set of commands I've seen in examples and adopted as my own. I would love to use OpenGL on other platforms and have a good understanding of it.

Every time I search for a book I find this HUGE bibles that seem uninteresting and very hard for a beginner. If I had a couple of weekends to spend on learning OpenGL what would be the best way to spend my time (and money)?

# Answer
Be careful when you look at OpenGL tutorials, because many of them (NeHe) included just teach you things that you shouldn't do anymore. Todays OpenGL is a different beast that it was 10 years ago.

Some nice examples avoiding the deprecated stuff can be found here: http://www.g-truc.net/post-tech-content-sample.html

> The OpenGL Samples Pack 4.0.1.0 is an update that brings the number of samples to a total of 58 samples; including 13 OpenGL 4 samples, 33 OpenGL 3.3 samples and 12 OpenGL 2 samples for Visual Studio 2008 and 2010 in 32 and 64 bits.
> 36 votes

# Answer
There are many things you could learn from. Here's my thinking on each, from the perspective of someone new to OpenGL.

# OpenGL Examples

There is plenty of example code out there that you can read. G-truc's examples are pretty extensive and cover a lot of advanced features.

However, if you are a *beginner*, learning from examples is a terrible way to learn. Reading code that you don't really understand will not teach you why it works. Indeed, the text on the above linked page specifically and rightly states that the examples are not for beginners.

Learning from bare source code, unless it is heavily commented (at which point it's a tutorial) is not an easy thing. Attempting to do so encourages cargo cult-style programming and copy-and-paste coding. It is very easy to convince yourself that you understand how something works when all you're really doing is just copying code from one place to another. You may be able to mix and match things, but true *understanding* is difficult to achieve without proper instructional material.

# OpenGL Books

There are a fair number of actual purchasable books for OpenGL development. I'll cover my thoughts on the two biggest here.

## OpenGL Redbook

This one is somewhat problematic from a purely practical standpoint. See, the 7th edition covers GL 3.0 and 3.1. Which is rather old. There have been a *lot* of useful features added to OpenGL since then, features which change how you would write things. And not all of them are hardware features.

The 8th edition is coming "soon", and will cover 4.1. There's no word on whether it covers old fixed-function stuff.

I'd say this book is OK. The biggest problem with it is the organization of information. It's more like a comprehensive reference manual than a book made for learning. Here's what I mean.

One of the most important things that one should do when teaching is to not overload the student with unimportant information. But the Redbook does exactly that. When introducing material, it introduces a *lot* of material. Much of it superfluous to the task at hand.

What you talk about and when you talk about it are crucial to making your book a good learning resource. The Redbook never holds back information until a more appropriate time. When it talks about how to draw triangles and primitives, it talks about *everything* about drawing them, all at once. It covers every option, every function, every parameter, etc.

That's just not a good organization of information.

## OpenGL Superbible

The fifth edition of this book covers only core GL 3.x, so no fixed-function.

However, the general organization of the book is more or less identical to the organization of the fourth edition version. This seems impossible since the 4th edition used fixed-function and didn't introduce shaders until much later.

The way this was accomplished is my #1 complaint about the book. Essentially, the author built a library that implements a form of fixed-function OpenGL. It wraps VAOs, buffer objects, shaders, and various other things, so that he can get to drawing objects, matrix math, and textures without having to talk about things like how the GL pipeline works in detail.

By hiding all of these details, it makes the material easier to digest. But you will often see people walking away from the Superbible without knowing how to actually function without the library. They don't really understand how shaders connect to buffer objects, how data flows up the pipeline, etc.

It is a serviceable book, moreso than the Redbook. If all else fails, it will do the job. But I think it could be better.

Also, according to some reviewers, it seems to miss out on certain useful information, like packing attribute data using normalized values and such.

# OpenGL Online Materials

There are many online materials that one could learn from.

## NeHe's Tutorials

NeHe's tutorials, as others have stated, are *extremely* out of date. They focus on fixed-function OpenGL. It is often stated that it is easy to learn fixed-function GL, which is true. But that doesn't make it a good idea.

Understanding how the fixed-function pipeline *truly* works is hard. I would go so far as to say that it's harder than learning shaders. Once you get it, shaders are simple. Understanding the intricacies of texture environment stuff, combiners and whatnot, is very tricky and requires frequent visits to reference docs to make sure everything is set up right. Even if you understand everything correctly, it's easy to make a small mistake that causes everything to break.

The difference is that you can make fixed-function work *without* understanding it. This encourages cargo cult programming. It makes it possible to get *something* on the screen without really knowing what one is doing. Over on the OpenGL.org forums, we see questions constantly about minutiae surrounding fixed-function, from people not knowing how gluLookAt works, to difficulties with lighting, to people trying to get some particular effect to work with the texture environment.

So no, I do not think NeHe is a good way to learn OpenGL.

The above commentary can be used for any non-shader based tutorial, like Swiftless, Lighthouse, and so forth.

## Wikibook's OpenGL Programming

The Wikibook OpenGL Programming is probably the modern equivalent to NeHe. It covers GL version 2.1, because they want to keep it relevant to mobile platforms. If that's important to you, then by all means look here.

The other issue with NeHe, and thus this Wikibook, is the large focus on source code. The text to code ratio is very small; there is a *lot* of code, but the text doesn't really explain how it all works.

As an example, look at the bottom of Tutorial 2. It introduces blending. It doesn't say how blending works. It doesn't say what `glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)` actually means or does. It just says, "Here's some code that makes things transparent."

That's not the best learning environment.

## Incomplete Tutorials

Swiftless has a set of OpenGL 4.x tutorials. Durian Software also has some shader-based OpenGL tutorials. And there's the "OpenGLBook.com" tutorials.

The thing these all have in common are... that they're incomplete and abandoned. They all got about 4-5 tutorials in, and then were dropped. None of them reached texturing, lighting, or anything like that. Well, Durian did hit texturing but not lighting.

Much can be gleemed from them, but there is much that is missing as well.

## Shameless Self-Promotion

Reviewing my own Modern 3D Graphics tutorials would be a horrible conflict of interest. So instead, I'll hold forth at length about the organization behind them and why I think they're good.

Oh and yes, I am working on Tutorial 17. The project's not dead.

The first three chapters are really about learning how the OpenGL pipeline works. The Superbible failed because it tried to hide details. Instead, I attempt to explain those details really, really well. Repeatedly. The introduction explains the pipeline in plain text. The first tutorial explains it with code accompaniment. And the second tutorial visits it even more.

From there, I naturally move on to positioning objects. This introduces uniforms, but I didn't want to jam uniforms and perspective projection in at the same time. So I separated the two concepts. After projection, depth buffering seemed a reasonable next step, followed by how transforms and matrices work. After that, cameras. Rotation with quaternions was a late addition, but I feel that it was an important thing to talk about for the budding graphics programmer.

The lighting tutorials again build one on the other. Diffuse, then per-fragment lighting, then specular. Dynamic range was an interesting choice. Most introductory material tries to stay away from that, but I embrace it. You're not a graphics programmer these days if you think light intensity always is on the range \[0, 1\]. And you're not a graphics programmer these days if you don't know how to maintain a linear color pipeline.

The final one in lighting, on imposters, was a weird one. I try to design tutorials that solve problems rather than just show some OpenGL functions, particularly as the book goes on. So much of my tutorial design comes from finding ways to talk about certain topics while still making them real issues and not obvious, "we're learning X now." Geometry shaders are a hard one, because they don't really solve very many problems.

Imposters represented a problem that GS's were actually useful for solving. Also, it allowed me to talk about other less used things like `discard` and changing a fragment's depth. And it really shows the power of shaders: you can make a flat square become a sphere.

The texturing tutorials are also interesting. One of the reasons I put off talking about diffuse color textures until the third one was to hold off on talking about sRGB textures for a while. This way, I could talk about the basic issues around textures (loading data, putting them in shaders, filtering, clamping, etc) without having to deal with linear issues. So then I could spend a whole tutorial on just that topic. That allowed me to really, **really** emphasize how important maintaining a linear color pipeline is.

It's one of my pet-peeves.
> 65 votes

# Answer
I would recomend starting with this tutorial series, they are good and use more modern features than the nehe ones http://duriansoftware.com/joe/An-intro-to-modern-OpenGL.-Table-of-Contents.html
> 21 votes

# Answer
My only book on OpenGL is "OpenGL SuperBible, 4th edition" and 5th is about to be released in a few weeks. I think it's good for both beginners and advanced programmers.

Edit: I might add don't go for the latest technology trends if you're just learning to program. Chances are once you become an expert using one methology, 5 new interfaces / versions just released. We've seen shaders advance every 3 months, it seems. So pick what has the best documentation (generally primitives), make a few programs, and gradually advance because more than likely you'll bump into older code in the future. Hope it helps!
> 8 votes

# Answer
As usual the best way to learn is to do it. I would hold off on spending money unless you feel you really benefit from having a textbook to read from, most (if not all) information can be found online. On top of learning OpenGL you may want to brush up on your Linear Algebra as well, it never hurts.

The big issue I faced is a lot of stuff that's out there has been depricated in recent version of OpenGL.

The best resource I've been able to find has been at Joe's Blog. It does it's best to introduce the modern pipeline and get you through some examples in a more readable fashion than what I've been able to find elsewhere. It seems Nehe has been getting a couple updated recently and while their lessons are still old, some of the news may be of interest. Lazy Foo' was also a great resource, but like Nehe it's tutorials use depricated material.

I think after a weekend or 2, once you get comfortable go off and do a small project to apply everything. Breakout, or tetris - something where you can concentrate on the code itself. You learn so much more when you go off and try to do an actual project, regardless of how simple.
> 5 votes

# Answer
Here is another one. Its very good. Though it has only 4 chapters.

http://openglbook.com/

Another one is, http://www.arcsynthesis.org/gltut/. This one is huge, slow and high profile.

Don't forget to track the http://www.opengl.org/wiki/Getting\_started
> 4 votes

# Answer
The best way to learn OpenGL is to use it. I would recommend writing your own engine. This may seem like a daunting task, and it is. Your first engine won't be very good, but you'll have learned a lot.

Basically: write an engine, use it for a game, figure out what you don't like about it and rewrite it. Keep doing that and you'll get better at OpenGL. :)

What you will need:

* Some way to load models (.obj)
* Some way to load textures
* Lighting, either in the fixed function pipeline or in a shader
* For any slightly more complex scenes than a teapot on the screen, a scene graph
* Lots of tiny tools (3d vector class, quaternion class, camera class, scene manager, etc)

This is already a lot of work.
> 3 votes

# Answer
I learned opengl by writing a "simple" game: 3D Tetris!

Try creating your own simple game/app:

* Asteroids
* Pong
* Simple side scroller (you could learn to load in models for the player/enemies. Don't have any? Use Quake models)
* 3d terrain generator

Do something **simple** that interests you!
> 2 votes

# Answer
We do some OpenGL(ES) in our Orchard's Craps game for the iPhone but it was handled by a programmer with mad 3D skillz. So, because of this I've been learning OpenGL(ES) so that I know what I'm talking about and so that I can code along with the team.

One site I found helpful, with a series of tutorials, is Jeff LaMarche's blog: http://iphonedevelopment.blogspot.com and here is a link for his OpenGL posts: http://iphonedevelopment.blogspot.com/2009/05/opengl-es-from-ground-up-table-of.html

And from OpenGL.org there are these two links that are useful: http://www.opengl.org/code/ and http://www.opengl.org/resources/features/

The best way, was stated above several time. Jump in and do something small, that's interesting, and work your way up. It's all about understand the scene, the camera and materials (shaders). Once you get your head around these concepts you can start to look at physics engines, collision detection, particle effects and the like. Woot! (^\_^)

Good luck with all of your endeavors, Kevin
> 2 votes

# Answer
Well no one talked about the OpenGL Programming Guide, I don't have this particular edition but older ones was pretty good.
> 2 votes

# Answer
I wouldn't say this video tutorial series is the best way, but it is very well explained: www.71squared.com/2009/03/iphone-game-programming-tutorial-1
> 2 votes

# Answer
http://www.opengl-tutorial.org/

Has tutorials for 'modern' OpenGL (3.0/4.0 core, e.g. no obsolete stuff (like glBegin/glEnd) is teached). Although the tutorials use shaders, the basics are explained in great detail, building a solid mathematical foundation along the way. The text is rounded out nicely with code\* samples and helpfull visualisations.

Intermediate tutorials cover stuff like e.g. use of Quaternions or Lightmaps.

.\* glm is used as a math library
> 2 votes

# Answer
Just note the best way to learn OpenGL is *task oriented*. Try to *do something* (like add a feature to your game) then **look up what is required to do that**.

Manuals and tutorials are really boring without a greater context - ie something *beyond* the tutorial that you want to achieve on your own.
> 1 votes

# Answer
Start with NeHe to quickly get your first triangle on the screen. Do a few of the beginner tutorials there to understand the basic concepts of 3D programming. If, as you imply, mentioning OpenGL ES, you already know the basics of 3D programming (what are matrices, what they're used for, how different matrices are used to project vertices on the screen, what vertices are, etc.), then I suggest you don't waste time with NeHe at all, because it might slow you down (by teaching you things you have to "unlearn" later on).

Apart from that, I agree that the best way to learn it is by doing. A good first non-hello-world project might be a 2D game (or a 2D game engine). Using modern OpenGL for 2D applications can teach you a lot of the relevant concepts (buffer and shader use, for example), and it will be less daunting than a 3D project. Then, afterwards, you can apply what you've learned in doing a 3D application.
> -1 votes

# Answer
Well I have been told over and over that nehe's tutorials are the best, I guess they'll fit for you too ! http://nehe.gamedev.net/ I bought the red book...
> -3 votes

---
Tags: opengl
---


# Question
Title: League of Legends Spectator Stream Format
# Intro

I have been fiddling around with the spectator system for LoL in hopes of eventually scraping data from the streams and building a dataset with it for analysis. I understand that there are already some unofficial APIs and techniques, but I am looking for really specific game events (champion kills, turret kills, item puchases, jungle mob kills, champion co-ords for particular events, etc).

# What I have figured out so far

When you begin spectating a game (in NA), your client connects to the following host:

*spectator.na.lol.riotgames.com:8088*

I assume this host is backed by Amazon AWS or similar. Anyways, the next thing that happens is the client sends a version request to the spectate server:

*GET /observer-mode/rest/consumer/version*

This returns whatever the current spectator server version is. Ex: '1.80.54'

Next, the client sends a request for the game metadata:

*GET /observer-mode/rest/consumer/getGameMetaData/NA1/\[gameid\]/\[some random nonce\]/token*

This returns metadata about the game. An example of this data: http://pastebin.com/3N4qs0hx

The client now knows the parameters by which the spectate session should progress. It tries to locate the latest data chunk by calling:

*GET /observer-mode/rest/consumer/getLastChunkInfo/NA1/\[gameid\]/30000/token*

Sample of this data: http://pastebin.com/Cj7dEAr9

Once the data chunks have been identified, they are requested:

*GET /observer-mode/rest/consumer/getGameDataChunk/NA1/\[gameid\]/\[token#\]/token*

Sample of a token's data (binary converted to hex): http:// pastebin.com /GyqPRP5J

The game cycles between calling getLastChunkInfo and getGameDataChunk as data becomes available from the replay stream. There is also a call which occurs after about 5 chunks are grabbed to the following:

*GET /observer-mode/rest/consumer/getKeyFrame/NA1/\[gameid\]/\[somechunkid\]/token*

I believe this call only occurs at the replay start up and whenever the user seeks to a different time.

I know the game uses encryption at some level. I believe it to be Blowfish ECB, with the actual key specified on the command line. I have attempted to decrypt these tokens using the session's key, but they still look pretty random.

# Edit 3/23/2013

* I have determined that the tokens are most likely not encrypted by modifying the command line argument containing the key and re-launching the game from debugger (it loaded the replay correctly).
* The tokens seem to be compressed. There is a call to a subroutine which if returns non-zero integer will trigger the following:

```
if ( sub_B71120(v21, v15, (int *)&Size, *(_DWORD *)(v6 + 108)) )
{
sub_BAD700(
(int)"!\"Error Decompressing data chunk.\"",
(int)"D:\\jenkins\\workspace\\Code-CI-Releases-Public\\code\\HeroWars_clientServer\\Sources\\ReplaySystem\\ReplayServerConnection.cpp",
6,
(int)"Riot::Replay::ReplayServerConnection::GetChunk",
(int)"Assert occurred, game may crash.");
sub_9BB750("ReplayServerConnection GetChunk error. Error decompressing chunk data. Error: %d\n");
}

```
* Upon investigation of sub\_B71120 I have located a call which eventually enters a fairly large function. This function contains strings like:

+ "incorrect header check"
    + "unknown compression method"
    + "invalid window size"
* A quick Google search of these strings reveals the following: http://www.opensource.apple.com/source/zlib/zlib-22/zlib/inflate.c
* I have also found the string reference "1.2.3" in a function call just before the call to inflate.c method, as well as another reference "inflate 1.2.3 Copyright 1995-2005 Mark Adler". It definitely looks like they are using Zlib version 1.2.3 for the decompression of the tokens. I just can't get them to decompress regardless of what file offset I start at.

# My question(s)

Does anyone know how these 'tokens' might be formatted or if there is some type of compression/encryption I am unaware of? I have a suspicion that they are some compressed or packed form of the ethernet packets used during live play which are simply played back internally to the client.

Alternatively, can anyone think of some other method by which to scrape this data without running the actual game client? Keep in mind I would like to grab data from many streams simultaneously.

# Answer
I've been researching the same thing and I found this repo to be extremely helpful. The file decrypt.rb decrypts both chunks and keyframes.

Edit: check out this reddit thread too.
> 4 votes

---
Tags: encryption, protocol
---


# Question
Title: XNA Framework doesn't recognise controller
So just a little bit of XNA code:

```
if (this.IsActive && (Keyboard.GetState().GetPressedKeys().Length > 0 || Mouse.GetState().LeftButton == ButtonState.Pressed || Mouse.GetState().RightButton == ButtonState.Pressed || Mouse.GetState().MiddleButton == ButtonState.Pressed) || GP_state.GetButton(8) == ButtonState.Pressed)
                    {
                        Current_GameState = GameStates.Game;
                            bg_music.Play();
                    }

```

If something is done --\> Switch to a different game state. Works with: Keyboard and Mouse, but not with the gamepad (which is new and it works with other games) So why does XNA not recognise it correctly??

EDIT: I do have a working solution and mark my own answer as soon as possible as right...

# Answer
Well, found out, that is indeed not supported, but found the following: http://nuclexframework.codeplex.com/releases/view/62687 \<-- Only Nuclex.Input.dll is needed to Reference...

How to use:

1. Class level variable: `InputManager ManageI;`
2. List item On Initialize() or in the Game Constructor:`ManageI = new InputManager();`
3. 2 Using needed: `using Nuclex.Input;
using Nuclex.Input.Devices;`
4. Before trying to get a gamestate, don't forget to call `ManageI.Update();`

Because I am only developing for Desktop, I have no idea how you are able to use it on a XBox or Windows Phone 7 (well, of course there are .dlls included....) and why you should...

For testing the joystick I can recommend: http://sandbox.yoyogames.com/games/155175-joystick-input-tester-v100
> 1 votes

---
Tags: xna, c#, xna-4.0, input, gamepad
---


# Question
Title: Isn't it redundant to implement both lights and shadows?
Most games come up with their lighting implementation and their shadow implementation. Due to deferred shading, we are able to simulate lights independent from the scene geometry. But realistic shadows are still a big challenge in game development. They would have to overlap with each other, have soft edges and are calculated in real time to support dynamic scenes.

There is a presentation where the author, Chun-Fu Chao, mentions this about lights and shadows in game development.

> 1000 lights without shadow is easy, but 100 lights with shadow is impossible, now.

I wonder where is the problem, at all? I understand that shadow maps and shadow volumes have their problems, though they are very popular. From my understanding, shadows are just the absence of light. So if we use a very dark ambient color, and use deferred shading for handling all light source with easy, wouldn't that result in shadows for free?

# Answer
The problem is that "cheap" lighting is a calculation based solely on the light source and the object it is applied to, any possible intermediate object that would block the light is not a part of the calculation.

Therefore a lot of games use such lights coupled with some shadow system.
> 7 votes

---
Tags: lighting, shadows
---


title: How expensive is OpenGL Texture Binding

text:
# Question
Title: How expensive is OpenGL Texture Binding
I'm currently working on a renderer for Tiled's .tmx maps. Among one of the features there is that layers and tilesets are independent, so that a layer can use any tile set on any tile. It's not so much of a problem, though, as my `Image` type is basically:

```
data Image = Image { imageTexture :: TextureObject
                   , imageMinTex2 :: TexCoord2
                   , imageMaxTex2 :: TexCoord2
                   } deriving (Show, Eq)

```

Drawing an image is therefore

1. Bind texture
2. Render Quad using min/max texture coords

A quite simple implementation. However, if every `Tile` is an `Image`, in my implementation, then this would mean that on every tile, a texture is bound. Often times it will be the same, and quite often just a few tiles have entirely different texture.

So how expensive is a texture binding in OpenGL? Do I have to sort the Tiles by texture or will the OpenGL drivers do that for me?

# Answer
> 8 votes
Guessing a bit here but from the little information you gave it sounds like you are thinking of something like the following

```
for each layer
    for each tile
        bind texture
        draw quad
    end
end

```

If that is the case this is the most inefficient way of drawing, and you will not get any good performance out of this because you end up with a draw call per tile rather than a draw call per tileset.

You should batch your draw calls, a simple implementation could be something like the following

```
// draw
for each layer
    for each tile
        add to render queue
    end
 end

 // flush
 sort render queue items by texture
 let buffers be index/vertex buffers on the GPU with a fixed size.

 for each item in render queue
    if item texture is not bound or buffers are full
        bind texture
        draw buffers
    end

    append item to buffers
 end

```

---
Tags: opengl, textures
---


# Question
Title: Generate inner polygon from a parent polygon
I want to produce a polygon inside an arbitrary polygon. The inner polygon shall be distanced from the outer polygon with a fixed distance, d. I will use the inner polygon as a border for player movements, and the player radius will be 2 * d.

If the outer polygon contains sections with width less than 2 * d the inner polygon will not fill that space, or any space on the other side of that passage.

Keeping the distance to the outer polygon means that the inner polygon will form circles, by a number of segments, around sharp vertexes.

How do I generate the red polygon?

# Answer
> 1 votes
Note, that your "inner polygon" is not a polygon (!!!) (because, as you said, it contains parts of circles).

If you just want your object to move inside polygon, keeping the distance from edges, I recommend you to compute the distance between your inner point and the closest point on polygon edges, then compare, whether is that distance bigger or smaller than your **d**, to check the collision.

BTW. here is the Javascript library & demo of finding closest point on polygon edge: http://polyk.ivank.net/?p=demos&d=closestedge

---
Tags: geometry
---


title: Moving character on x axis

text:
# Question
Title: Moving character on x axis
I am new to unity scripting.

I am trying to move my character towards right side(on x-axis) to create a running effect, I've imported the character from blender which contains two animations, "jump" and "run". What I want to do is I want my character to move on x-axis for which I've written following code

```
void Update () {
    transform.Translate(5f * Time.deltaTime, 0f, 0f);
}

```

But I am facing one problem, if I set my character's y-axis rotation to 90 degrees in order to make him look towards right side I am getting strange results. That is, in play mode instead of moving towards right side(on x-axis) it move on x-axis and z-axis simultaneously & if I set the y-axis rotation to zero it behaves like I want it to. Please see the attached image for detail. How can I solve this problem?

# Answer
Use `Translate` overload, which takes `Space` enumeration values, indicating, that shift is an absolute value, like:

```
transform.Translate(5f * Time.deltaTime, 0f, 0f, Space.World);

```

or in more readable way

```
transform.Translate(Vector3.left * 5f * Time.deltaTime, Space.World);

```

`Vector3.left` returns a unit vector pointing left
> 3 votes

# Answer
I found the solution to my problem. And just like I thought, When Switching to my player model I had to change the movement direction from

```
transform.Translate(speed* Time.deltaTime,0,0);

```

to

```
transform.Translate(0,0,speed* Time.deltaTime);

```
> 1 votes

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


title: Physics engine for Billiard game

text:
# Question
Title: Physics engine for Billiard game
I need to write a simple 3D billiard game using OpenGL. Which physics engine is simple and best to use in this case? Or it's better to write physics by myself?

# Answer
I've written a simple *2D* billiard-like game using Box2D before.

As Digital Architect pointed out, unless the ball jumps from the table, 3D physics is overkill. And you *can* use 2D physics with 3D graphics.

If you decided to implement physics by yourself, this is what you'd have to do (which are already implemented in Box2D):

1. Circle-Circle collision detection (when balls collide)
2. Circle-Polygon collision detection (when balls collide with the edges, which are **not** rectangles)
3. Handling collision (so that balls that collide move accordingly, depending on the coefficient of restitution)
4. Damping
5. Applying forces (or at least set the velocity of a ball)
6. Sensors (for the holes)

Also, you'd have to make sure everything works properly (no obvious bugs, which can be a pretty hard problem unless you really know what you are doing) and efficiently.
> 4 votes

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


# Question
Title: Actually utilizing relational databases for entity systems
Recently I was researching several entity systems and obviously I came across T=Machine's fantastic articles on the subject. In Part 5 of the series the author uses a relational schema to explain how an entity system is built and works. Since reading this, I have been wondering whether or not actually using a compact SQL library would be fast enough for real-time usage in video games.

Performance seems to be the main issue with a full blown SQL database for management of all entities and components. However, as mentioned in T=Machine's post, basically all access to data inside the SQLDB is done sequentlially by each system over each component. Additionally, using a library like SQLite, one could easily improve performance by storing the entity data exclusively in RAM to increase access speeds.

Disregarding possible performance issues, using a SQL database, in my opinion, would allow for a very intuitive implementation of entity systems and bring a long certain other benefits like easy de/serialization of game states and consistency checks like the uniqueness of entity IDs.

**Edit for clarification:**

The main question was whether using a SQL database for the actual entity management (not just storing the game state on the disk) in a real-time game would still yield a framerate appropriate for a game or even if someone is aware of projects that demonstrate SQL in a video game.

# Answer
> 2 votes
In my experience using a relational database for these situations is fairly clumsy. It *can* be fast, in very simple cases, but translating object oriented entities into relational tables is itself a burden. You might look into some of the newer object database solutions like VelocityDB. But don't take my word for it - do some testing to see what works best for you.

# Answer
> 1 votes
In most cases the objects/entities in a game change over time, sometimes very quickly for purposes of animation, sometimes less often. I think it is obvious that any object that is changed several timer per second is probably not a good candidate to be managed by a database. So anything that requires 1 or more SQL queries for each frame is right out.

This does not mean that databases should not be used, but in the past I have used them to store objects not visible/used at the moment. Database, especially SQLite, are very fast if you need to select a group of objects, and then load them all at once. So, what I ended up doing is maintain the objects in memory (no SQL) while they are being actively used, and as they go out of scope they get saved to DB, and more objects that become active loaded.

Another situation where I have used DB heavily is when creating a multiplayer server, especially where transactions are required for 'crafting' new objects and trading them between players. You can see how in such situations it is critical that the transactions are serialized and that no loss of data is allowed.

If I had to sum up quickly, databases are great for objects that do not change very often (many times per second), but I would not dare use them for anything that needs to store changes due to animation.

# Answer
> 1 votes
You could combine SQL persistence with some ideas described here: Best practices for periodically saving game state to disk

Essentially, you don't want to use SQL server to load/store your entities real-time on the fly. But if you load/update/insert the entities in a background thread through some memory buffer, it could work just fine. I myself am trying to implement my own game server that way.

Also I suggest this article: Evolve Your Hierarchy, especially the "IMPLEMENTATION DETAILS" part - it explains some issues you might face when implementing entity systems and what compromises could be taken to improve performance.

---
Tags: entity-system, sql
---


# Question
Title: Implementing tile-based movement on 2D platformer
I'm trying to make a cinematic platformer, in the veins of the first two Oddworld games, Flashback, Prince of Persia, Blackthorne and so on. This article describes very well how this kind of movement should work:

> (...) The algorithm is then as follows:
>
> 1. Create a copy of the character where he’d like to move to (e.g., if moving one tile to the right, make a copy where every tile of the character is shifted 1 tile to the right)
> 2. Check that copy for intersection with the background and other characters.
> 3. If an intersection is found, the character’s movement is blocked. React accordingly.
> 4. Otherwise, the path is clear. Move character there, optionally playing an animation so the transition looks smooth.
>
> This kind of movement is very ill-suited for traditional arc-shaped jumps – so games in this genre often have no jump at all (Toki Tori, Lode Runner), or only allow vertical or horizontal jumps (Prince of Persia, Flashback), which are nothing but special cases of linear movement.

Eventhough the idea seems very clear to me, the actual implementation of it raises a lot of questions in my mind. For some of them I feel I have very complicated solutions, while I have no idea how to solve others.

For starters, the basic mechanism for moving: if the player presses *right*, the character will enter a "walking right". While on that state, the character will move from the starting tile until the next one, even if the player releases the *right* key; if the player is still pressing the key when the character reaches the next tile, the same thing will happen. However how exactly should that movement inbetween tiles work? Should it be just a regular speed being applied to the character's x position? What should that speed be in order to assure that the character will stop in the precise location in the next tile? And should that speed work with the update's delta time?

Another thing that has me at a loss is how much of the sprite's positioning has to be done by the actual x,y positioning and how much should be done inside the sprite. For example, in the case of a running jump, which is, as noted, a special case of linear movement, should there just be empty space below the character (and position the sprite by its bottom) or should the y position be adjusted accordingly?

I'd really appreciate some help with implementing this kind of platformer. That article above is the only thing I've found that sheds any light on how to do it, and I'm struggling to figured out the rest on my own.

# Answer
I've tried to copy the movement/controls for an Oddworld-style game before.

Here is some of the code for the state machine: https://gist.github.com/tomdalling/5201751

Here is a video of the movement: http://www.youtube.com/watch?v=Ni2hE-bCZTA

> However how exactly should that movement inbetween tiles work?

See the `StandingMove` state. In my code, the player always has a discreet x/y coordinate on the grid, which doesn't change during animation. Let's say the grid is 16x16 pixels, then the "walk right" animation will be 32 pixels wide, because it covers two horizontal cells. Once the animation is finished, the x coordinate is updated to `x += 1`. The "move left" is a little different, because it does `x -= 1` *before* the animation runs, but it's basically the same thing.

> Should it be just a regular speed being applied to the character's x position?

Because the x/y doesn't change, the speed is completely controlled by the length of the animation. The `StandingMove` state checks if the animation is finished before it returns to the `StandingIdle` state:

```
if(p->_anim.isFinished())
    return &p->_s_StandingIdle;

```

> should there just be empty space below the character (and position the sprite by its bottom) or should the y position be adjusted accordingly?

I just took the empty space approach. This is the sprite sheet for the ledge grabbing/climbing animations:

You can tell from the image that the y coordinate is on the ground during jumping/climbing. Once the player is actually on top of the ledge at the end of the `LedgeClimbUp` state, the y coordinate gets updated with `y += 3`.
> 5 votes

# Answer
Here's a different approach, taken by electrolyte, from the TIGSource forums. He was making this platformer project (some footage here).

Here's some of his explanation:

> The way my platformer worked was to send a 'sequence' request to a function. So for example, I might press the right key and this tells the sequencer function that the player is trying to walk right, so start the 'Walk Right' sequence.
>
> Inside the 'Walk Right' sequence not only do you have the animation information, but you also move the character a set and precise amount of pixels to it's next grid space. This loop isn't broken until it's completed.
>
> Next up, once the sequence is completed you need to see what the user is pressing or not pressing and react to that. This in essence is how you can create fluid animations.
>
> Example:
>
> 1up presses right key, start ' Walk Right' sequence.
>
> 'Walk Right' sequence is completed, see what keys 1up is pressing
>
> 1up is now pressing left key, start 'Turn Right to Left' sequence
>
> 'Turn Right to Left' sequence finished and 1up is still pressing left key so start 'Walk Left' sequence
>
> and so on
>
> The problem starts when you have to capture every combination and call a sequence / animation! How you do this is up to how you want to programme it, but I recommend just jotting down on paper some of the combinations to start with and then add more and more. In flash I used a pretty dirty Switch statement which worked well.

And regarding movement, I was thinking maybe interpolating the player's position between one tile to another, but he had this to say:

> So the movement is still handled as you would a normal platform game. I would stay away from tween engines :D
>
> Simply work on X and Y, so to walk right, x + 1. Then make sure your 'Walk Right' sequence loops say 16 times ... which is the pixel width of the grid and you know that in the loop it will move exactly to the next grid position! Of course tailor that number to your requirements.
>
> Also what's really handy is if you then set the animation frames to 16 frame cycles (the width of grid squares), each time you add 1 to the X you can move forward a frame in animation.
>
> In terms of jumping, that really was handled like a traditional platform game, so some Y inertia, but split the jump into sections, so "jump up", "Falling down", "Landing" etc. That way at the end of the jump up sequence you can check for hanging onto stuff etc.

The only thing that should be noted with this approach is that ideally, you need a fixed timestep in your updates. I think the "Constant Game Speed with Maximum FPS" solution in this article would work pretty well.
> 1 votes

---
Tags: tiles, movement, platformer
---


# Question
Title: How can I obtain a copy of the Kinect commercial SDK?
As far as I know, in order to publish a Kinect game on XBOX console, you need a commercial version of the Kinect SDK. The problem is, I couldn't find a reliable source to research about the subject. Do you know:

1. What are the conditions for getting the Kinect commercial SDK?
2. Is it possible to buy it without owning a company?

# Answer
You'll need to be an "Xbox 360 Registered Developer". It's not as simple as just wanting to do it. There's more information on the Xbox 360 Registered Developer page on Xbox.com. I believe XNA doesn't support Kinect for Xbox 360, you'd need to gain access to a proper devkit and access to the libraries available only to registered developers.

If you have an idea you want to pursue, you might find it easier to find an existing approved publisher and get them to help develop your project.
> 2 votes

---
Tags: licensing, kinect
---


# Question
Title: Can I transfer C# coding I do in Unity for practice to another 3d engine?
If I use a C# coding in Unity 4, can I transfer that coding into another non-Unity engine as long as it accepts C# too? I hope this question makes sense. Thank you in advance.

# Answer
It depends on WHAT exactly you'd like to 'transfer' (or port). This is really just a simple library dependency matter. I'll try to put it simply. Suppose you have a class:

```
class AnimatedCharacter : MonoBehavior
{
     public GameObject SomeObject;
     // more code here
}

```

Can you just take this class, add it to another project that's developed under a different engine, and expect it to work? If you don't have a definition for `GameObject` in the destination project, and there's no `MonoBehavior` class to inherit from, then the answer is "NO". Here, `GameObject` & `MonoBehavior` are data types typical to Unity, and won't be recognized by any other engine.

```
class PairOfInts
{
   public int Element1;
   public int Element2;
}

```

This on the other hand has nothing to do with Unity's stuff. It will be compiled without a problem by any C# compiler and thus, it will work under any project you might be thinking to add it to.

In short: any code that works directly with Unity's own data types and/or functionality (inspector view things for example) will not work as expected (if at all) under another engine.
> 3 votes

# Answer
It sounds like you're a beginner, and are concerned with investing time in a tool and not getting any transferrable skills out of it.

The most valuable thing that Unity3d is teaching you isn't C#. It's teaching you how to work with a 3D game engine. Working with vectors, thinking about your asset pipeline, and how to translate input from a player into interesting transformations on screen that they can then use to accomplish some goal you set forth for them.

Don't concern yourself with code reuse. I'm still working off of the assumption that you're a beginner, so you likely won't have enough code to justify being serious about code reuse, and having to re-implement some feature or translate it from C# to another language is good for you.

Switching languages/toolsets as you evolve as a game developer opens your mind to new ways of doing things, earns you greater understanding of past problems you've already solved, and enables you to evaluate the quality of your future ideas for solutions to problems.
> 3 votes

# Answer
In short the answer is yes but there may be many things you will have to refactor or re-implement entirely. The more you depended on Unity's libraries, the more you'll have to modify.
> 1 votes

# Answer
Maybe. Any bits of code that only rely on standard C# constructs will be fine. Code that directly uses Unity APIs (including all the custom math libraries) will not be directly portable to another engine.

In general (for any language or engine), you can reuse most game logic code between engines, but it takes work to port it between APIs. It's often not worth it. The hard part is figuring out what the code should do to achieve desired results, not writing the code itself. It can take less effort in many cases to rewrite the code than to port. Depends on the circumstance of course.
> 1 votes

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


# Question
Title: Source control for storing everything of game project?
Is it usual to manage not only source code, but all assets, textures, art, documentation files, etc under git repository for version controlling? For example I wanna to get back old version of texture. If it is very bad practice what tools do you use for version control of assets and other stuff?

# Answer
I would say that's a very good practice. Source control should be used for source and assets. You can think of it like a backup, you want to be able to restore from source control everything needed to build your game.

I linked a question that's about storing assets in a repository. There are some repositories that work better than others for storing art. They'll allow you to "diff" the art and see what's changed. Others will just treat the assets as binary data, so you'll have to check it out to see what's different. This also means you'll have to upload the entire asset when it changes, as it won't be possible for the repository to "know" (parse) what has changed between versions.

I store everything in the repository. When I got my new laptop, I was able to check out my repository and build my game, without the need to copy any assets from anywhere else. That means I also store the 3rd party libraries, assets and source control in my repository.
> 13 votes

# Answer
Git is not great for non-text files. Cloning a git repo requires downloading all historical versions of a file, unless using a big file extension (non-standard, often not supported by GUIs) or special commands (requires being a git guru to do). The same goes for most DVCS systems. For a texture, model, or audio clip, this means pulling many copies of a very large file. 1GB of assets can easily be 200GB of historical revision data, and git makes you download it all when you clone a new repo, and download all intermediate revisions when grabbing the latest. This becomes a huge bottleneck down the road when you can least tolerate production delays.

Subversion, Perforce, and so on are better choices for assets, as they only require downloading the desired revision (the latest, usually). You can use them only for assets and use git for code, or also use them for source too. Perforce has some features that let it act like a very clunky DVCS, and is better than SVN functionality (though much more conplex) in my experience, however cost means you'll likely use Subversion.

Most content professionals have little need for DVCS, and some have trouble with even the basics of classic VCS anyway. Don't saddle the with git. Or Mercurial, DARCS, etc.
> 8 votes

# Answer
It's good practice, even as an artist when you are working on a project there tends to be some form of version control, file corruption or bugs do happen, without source control artists tend to do revision saves anyways which is just a huge mess.

Real world example you can see of this is the open movies projects made with Blender (Big Buck Bunny, Durian, etc)

Art pipeline for a game is more or less the same, except there might be a build step for the assets themselves to do some conversion from big fat data to engine specific format, such as texture compression and model format conversion.

Some tools, like GitHub even offer nice image comparison tools and alike, which is a lot better than comparing a binary blob.

Since an assets repository can be absolutely huge, my/our preference is to keep a seperate assets repository which is a submodule in the project repository. You don't want to pull down gigabytes of assets when all you want is to branch the source for instance.
> 3 votes

---
Tags: assets, version-control, git
---


# Question
Title: Interpolating a player between two 2D points?
I would like a player to be able to move in a direction smoothly, whilst sticking to a fixed grid. Much like in Pokemon, how the player can move, but when the key is pressed and released quickly, they move to the next 'grid square' smoothly. Currently, my player moves at a stupid pace, because I am moving them on the "grid" axis (16px squares). I have tried but failed many a time to make a player smoothly move between squares. Here are the two important classes related to my issue;

Grid.java

```
package com.jackwilsdon.walktest;

import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;

public class Grid {
    public static final int BLOCK_SIZE = 16;

    public void drawDebugGrid(GameContainer gC, Graphics g)
    {
        int width = gC.getWidth();
        int height = gC.getHeight();

        int block_count_x = width/BLOCK_SIZE;
        int block_count_y = height/BLOCK_SIZE;

        boolean color = false;
        for (int cX = 0; cX < block_count_x; cX++)
        {
            for (int cY = 0; cY < block_count_y; cY++)
            {
                Location current = new Location(cX, cY);
                current = gridLocationToExact(current);

                if (color)
                {
                    g.setColor(new Color(180, 180, 180));
                } else {
                    g.setColor(new Color(200, 200, 200));
                }

                g.fillRect(current.x, current.y, BLOCK_SIZE, BLOCK_SIZE);

                color = !color;
            }
            color = !color;
        }
    }

    public static Location exactToGridLocation(Location l)
    {
        return new Location(l.x/BLOCK_SIZE, l.y/BLOCK_SIZE);
    }

    public static Location gridLocationToExact(Location l)
    {
        return new Location(l.x*BLOCK_SIZE, l.y*BLOCK_SIZE);
    }
}

```

Player.java

```
package com.jackwilsdon.walktest;

import java.util.ArrayList;
import java.util.List;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.SpriteSheet;

public class Player {

    // Grid related location
    public Direction direction = Direction.NORTH;
    public Location location = new Location(0, 0);

    // Actual (pixel) location
    private Location actual = new Location(0, 0);

    // Sprite stuff
    private SpriteSheet player = null;

    private int maxSteps = 2;
    private int step = 0;

    public List<Image> north = new ArrayList<Image>();
    public List<Image> east = new ArrayList<Image>();
    public List<Image> south = new ArrayList<Image>();
    public List<Image> west = new ArrayList<Image>();

    public Player() throws SlickException
    {
        player = new SpriteSheet("res/player.png", 16, 16);
        north.add(player.getSprite(0, 0));
        north.add(player.getSprite(1, 0));

        east.add(player.getSprite(0, 1));
        east.add(player.getSprite(1, 1));

        south.add(player.getSprite(0, 2));
        south.add(player.getSprite(1, 2));

        west.add(player.getSprite(0, 3));
        west.add(player.getSprite(1, 3));
    }

    public void nextStep()
    {
        step++;
        if (step > maxSteps-1)
        {
            step = 0;
        }
    }

    public void draw()
    {
        actual = Grid.gridLocationToExact(location);
        switch (direction)
        {
        case NORTH:
            north.get(step).draw(actual.x, actual.y);
            break;
        case EAST:
            east.get(step).draw(actual.x, actual.y);
            break;
        case SOUTH:
            south.get(step).draw(actual.x, actual.y);
            break;
        case WEST:
            west.get(step).draw(actual.x, actual.y);
            break;
        }
    }

    public void move()
    {
        switch (direction)
        {
        case NORTH:
            location.y -= 1;
            break;
        case EAST:
            location.x += 1;
            break;
        case SOUTH:
            location.y += 1;
            break;
        case WEST:
            location.x -= 1;
            break;
        }
    }
}

```

So, how do I (linearly?) interpolate between the two points? I am using Slick2D, so I have an `update()` method that is called where logic can take place.

# Answer
> 3 votes
It's as simple as

```
(1-t)A + tB

```

Whereas 0 \<= t \<= 1

A and B are your two points. You might need to write it like so:

```
player.x = (1-t)tileA.x + t*tileB.x;
player.y = (1-t)tileA.y + t*tileB.y;

```

So simply update t

```
t += speed*deltaTime;
//Do position interpolation
if(t > 1)
//change state.

```

---
Tags: movement, transformation, interpolation, slick
---


# Question
Title: How to solve artifacts caused by vertex lighting in my voxel engine?
My current lighting system bakes the light amount based on ray-tracing from the light source to the 8 corners of the block (so per-vertex) and the distance to the light on the blocks. It works acceptable, but it's definitely not perfect.

Of course the blocks are made out of faces, which are made out of triangles. In the situation shown in the screenshot, where there is a light directly behind the camera, you get those weird triangle lighting issues.

How can I fix this problem?

# Answer
> 3 votes
There may be a bug in your raytracing, though there's a broader issue with your lighting here.

In general, this kind of lighting artifact is caused by not properly tessellating your faces. If each face is a single quad of only four vertices, then there is no lighting calculation in the middle of the face or in the middle of the edges. You end up with roughly triangular lighting artifacts along the edges of complex features in your terrain. This is because a single occluded vertex affects a large amount of the surface while ideally it should only affect a small area.

The solution is to further tessellate your faces, giving them more than four vertices. Your faces could be four quads (16 vertices) for example. The artifacts will be smaller. Tessellate further if desired. Find an acceptable balance between visual quality and the speed of baking the lighting.

Graphics are almost always a trade-off between an acceptable loss of quality (increase in artifacts) and performance. Even if all the baking is done offline (your terrain never changes), you might decide that making a designer wait 2 hours for lights to bake is not worth the increase in quality. Maybe you have two light baking quality levels, one for quick iteration and one for final production. At runtime, you can have options for users to get a visual quality they like that performs well on their hardware.

You can go a long way with different techniques, too. For example, if your only lights are one you carry and the Sun, you can ignore ray casting the light you carry (any unlit surfaces will also be occluded surfaces) and use a shadow map instead of ray casting for good-lucking shading from the Sun. Again, tessellating surfaces improves lighting results, but it removes the massive overhead of raycasting to each vertex in the CPU.

You can also try doing dome GPGPU ray casting to improve baking performance after raising the vertex count. Or at least parallelize the baking on the CPU so today's multi-core CPUs can chew through all the raycasting much faster.

Doing delayed lighting is also an option. After changing the voxels, do X ms of lighting calculations each frame until it's up to date, radiating out from the view position. This way you can bound the banking time per frame to maintain smooth framerates, even if the total process takes way longer than a single frame.

Short version: use smaller quads and more vertices to get smoother lighting, and find solutions to any performance problems that creates.

---
Tags: opengl, glsl, lighting, voxels
---


# Question
Title: Are interleaved vertex data formats better than non-interleaved formats?
I have been reading up on data formatting for 3D objects so that I can render my meshes as fast as possible in OpenGL. I am quite new to OpenGL so bear with me.

The format for interleaving your meshes goes something like:

`position, normal, texture1, texture2 //this I understand`

Most formats for 3D meshes, however, don't use this structure. From my understanding the interleaved format is fast for execution but isn't necessarily the best in terms of size, since you never really have as many unique normals as you do vertices, since (if you are using hard shading) all normals for a face would be the same.

A hard shaded basic cube for example has 8 unique vertices and 6 unique normals.

So my question is, is it worth it to set up an interleaved format like this despite the fact that if you had 3 separate buffers you would use MUCH less data?

Also (remember I'm new) is it somehow possible to do pack your vertex information like:

`all positions, all normals, all tex1, all tex2 //so all of one type in a sequence`

and have different sets of indices for each type? Or is that just dumb?

# Answer
> 4 votes
Yes, interleaved is worth it.

Interleaved VBOs has no effect on the size of data. Even with separate VBOs for each attribute, you only have a single index buffer, so you need to duplicate any vertex attributes appropriately. That means that you have a single value of an attribute shared by multiple vertices, you must duplicate it for each vertex, no matter how you laid out your buffer objects. Yes, this means that some model formats require a lot of processing to put into a renderable format.

The GPU is generally much happier with a single interleaved buffer. Vertex processing happens by taking all the data for a single vertex and then running the shader. It's much faster to grab all that data in one go from a single memory location than to query multiple memory locations, due to how memory buses and caches work.

You could use a library like Open Asset Import Library to read your source format and then process it into a custom, efficient-to-render (for your engine) format and save that to disk as part of your content pipeline. You could also write a model software plugin that directly loads/saves the engine format, though this tends to be harder and you generally want the fully-featured native format around as your asset source (you almost certainly do want a plugin that can visualize the model in your renderer, though, so artists can see how things look while working on it and not being forced to guess or wait; iteration speed is king). Your engine then loads that efficient, processed file for rendering. Ideally your format is something you can copy directly into a vertex buffer and index buffer and whatever metadata structures you need (again, this is why this format is generally custom for an engine and not a general-purpose format).

You can pack multiple attribute streams into a single VBO end-to-end like you ask, though again it's still inefficient. The GPU must access multiple locations in the buffer for each vertex, which negatively impacts memory performance (same goes for CPU memory accesses). Interleaved is the way to go.

---
Tags: opengl, 3d, software-engineering, opengl-es, 3d-meshes
---


# Question
Title: Canvas isometric translations to integer coordinates
I'm creating a canvas based game with an isometric playing board. I use the following transformations to get my square tiles to render on the screen:

```
'applyViewportTransformation' : function() {
    context.translate(this.settings.camera_x, this.settings.camera_y);
},
'applyIsometricTilt' : function() {
    context.scale(1, this.settings.tilt_ratio);
    // Rotating the grid around it's center.
    context.translate(this.settings.pixel_grid_width / 2, this.settings.pixel_grid_height / 2);
    context.rotate(Grid.degreesToRadians(45));
    context.translate(-this.settings.pixel_grid_width / 2, -this.settings.pixel_grid_height / 2);
},

```

My issue is I would now like elements rendered on specific tiles that aren't translated like this. I also need to be able to map mouse clicks to isometrically drawn elements etc.

So as far as I can tell I need a formula to go into the grid and a formula to go out of the grid.

Mathematically I'm lost and also a little stunned the 2d context doesn't have a public way of simply applying these transformations to a set of coordinates.

Help would be much appreciated.

Edit, if anyone wants a peek at the source or would like to suggest some edits you can view the source on github.

# Answer
Fortunately the basics are quite easy, although there are many small bits of trickiness that may confuse anyone.

To convert from a rect to an integer-iso coordinate, use this forumala:

```
    r = 4;
    d = 50;

    xi = floor(px/d + r*py/d);
    yi = floor(r*py/d - px/d);

```

The value `r` controls the how much the tiles are "stretched". 1 gives a perfect square, sqrt(3) gives cells that are two equilateral triangles joined together.

The value `d` is the length of the horizontal diagonal. In the images below, its the length of the longest diagonal of the cells.

Below are the grids you get with `r = 1`, `r = 2`, and `r = 4`.

* Note that you must use a proper floor function that works correctly with negative numbers (i.e floor(-1.1) == -2). Many languages truncate results of integer division. (If you always non-negative values for x and y this won't be a problem).
* (1) You may need to add constant values to `xi` and `yi` depending on how you want to map grid coordinates to screen.
* (2) You may need to flip the sign of `xi` or `yi` (or both) depending on how you want to map grid coordinates to screen.

To convert iso to rect, you can use the following:

```
x = (xi - yi) * d / r;
y = (xi + yi) * d;

```
* You must do the inverse of what you did in (1) or (2) on `xi` and `yi` first, before applying the above formula.
* You may get a coordinate that corresponds to a corner, instead of the centre of the cell, so may need to transform `x` and `y` further if this is not what you want.

---

Debug tips:

* To find problems easily, first apply the function to an image, choose colors based on the coordinates, and render this out to the screen. This will immediately help you see whether you have the right cell-shape.
* Make it easy to find the hex coordinate of any spot you click (by printing it out). Once you have the image rendered, you can click on it and see what further transformation you need to apply.
> 2 votes

---
Tags: mathematics, html5, html-canvas, transformation
---


title: Pixel Shader gradient problems

text:
# Question
Title: Pixel Shader gradient problems
I have pretty much zero experience working with shaders as my first couple phone games were just 2d games that didn't use any sort of shaders. Now I'm working on a PC game that has a day and night cycle so I found a tutorial and implemented a shader effect with only a basic understand of how it's working. Enough so that I've been able to accomplish what I've desired with darkness and lighting. This is a 2d game as well. Anyway here's my shader effect that I'm using:

```
texture lightMask;
sampler mainSampler : register(s0);
sampler lightSampler = sampler_state{Texture = lightMask;};

struct PixelShaderInput
{
    float4 TextureCoords: TEXCOORD0;
};

float4 PixelShaderFunction(PixelShaderInput input) : COLOR0
{
    float2 texCoord = input.TextureCoords;

    float4 mainColor = tex2D(mainSampler, texCoord);
    float4 lightColor = tex2D(lightSampler, texCoord);

    return mainColor * lightColor;
}

technique Technique1
{
    pass Pass1
    {
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}

```

And Implement like so:

```
drawMain();
drawLightMask();

ScreenManager.SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
lightingEffect.Parameters["lightMask"].SetValue(lightMask);
lightingEffect.CurrentTechnique.Passes[0].Apply();
ScreenManager.SpriteBatch.Draw(mainScene, Vector2.Zero, Color.White);
ScreenManager.SpriteBatch.End();

```

I didn't notice any problem at first on my 27" S-IPS 2560x1440 monitor. When I change primary monitors to my 1920x1080 LCD monitor the shaders don't appear to work the same. It doesn't have the soft gradient lighting from my lightmask. It's kind of difficult to describe. The outside edge of the lightmask isn't a fade into darkness. It's more of an abrupt change from being lighter to darker. I've tested on another computer and it's not working right on that other computer either. It has a 22" or so LCD monitor. Anyway I'm just confused as to why it's displaying different based on the monitor. I do scale but I start at 0.6f * hudScale so the lightmask is fairly large and starts even scaled down.

I really don't understand much about shaders so perhaps someone out there can help me understand why there is this difference of how the shader is displaying between monitors. My primary monitor is displaying it exactly how I like it, but more people have 1920x1080 LCD monitors than one like my 25560x1440 S-IPS LED so I want to to display the for all setups.

# Answer
> 2 votes
I suspect you're running into an issue with gamma conversion settings. If you're not familiar with this, check out the Gamma FAQ \- although you don't need to understand all the details. It's enough to know that the relationship between a pixel value and the intensity produced by the monitor is non-linear, and varies from monitor to monitor (and also depends on OS/driver settings, etc).

Since your light mask is a texture that you've presumably created in some paint program, I suspect what's going on is that the texture contains a subtle sharp edge - perhaps going from RGB = 0 to RGB = some small number, like 10 (let's say) - and this edge is invisible on your primary monitor because the way it displays intensities makes 10 almost as dark as 0. Therefore you wouldn't have noticed it when you painted the texture. However, when you take it to another monitor, RGB 10 (or whatever) is a good deal brighter than 0, so the edge becomes visible.

If that's the case, a simple solution is of course to fix the texture. :) If you turn up the brightness of it in your paint program (using an adjustment layer in Photoshop for instance) you should be able to see the edge.

Alternatively, you might consider using a mathematical function in the shader to generate the falloff, rather than using a texture. If you choose a function that goes smoothly to zero within the boundaries of the sprite, that should avoid any overly-sharp edge being visible on any monitor.

---
Tags: xna, c#, shaders
---


# Question
Title: Creating offline multiplayer Android games with Unity
Is it possible to create offline multiplayer Android games with Unity (played over bluetooth/ wi-fi)? If so, then I would like to create a 2 player game prototype, containing a single room (empty cube) with 2 cubes (3rd person controllers) - each controlled by one player. The cubes can be moved about as their owners (players) wish. Any movement made by any of the 2 players can be seen in realtime in the other player's display. How do I achieve this?

P.S. I know some basics of Unity. I have already created a small hack & slash game in Unity (PC-standalone). I am new to Unity Android, though.

# Answer
> 3 votes
Yes, it is possible to create offline multi-player games with Unity3D. You can achieve this most easily by using Unity's built in Master Server.

Unity3D Master Server

A good tutorial for learning how to use Unity's built in networking can be found here: M2H Networking Tutorial

# Answer
> 1 votes
If you go into Appstore, you can download the "Unity remote tester~", connect via bluetooth and play test it on your device :)

As for the tutorials, as @Xerosigma noted, the M2H NetworkTutorial is great, but you would like to learn how unity reacts with the mobile systems. For instance the standard terrain will not work on a IOS/Android, and so on.

If I am to recommend anything. Just read about creating any Mobile MMO/Multiplayer game. Here is a starter kit for a shooter.

http://forum.unity3d.com/threads/166531-Announce-Mobile-MMO-FPS-Multiplayer-Kit

---
Tags: android, unity, multiplayer
---