# Question
Title: Textureing subdivided Icosahedron in XNA, seam problem
\*****Look below for the updated source code\***

I have started to to make some different types of objects and create them by code in XNA. Right now I have finished the code for creating a Icosahedron. And works grate as it should. I have managed to get it textured by some tips from this page.

Like the guy in this thread I get a seam. Not sure how to solve it properly.

Here is my code for what sets up the resulting Vertices and Indices

*(since update this "IndexVertives" is not really what is used anymore. Check the "Init" in the update bellow)*

```
    private void IndexVertices(List<Vector3> originalVertices, out VertexPositionNormalTexture[] outVertices, out int[] outIndices)
    {
        Dictionary<Vector3, int> vertexIndices = new Dictionary<Vector3, int>();
        List<VertexPositionNormalTexture> vertices = new List<VertexPositionNormalTexture>();
        int indexCounter = 0;

        int runTime = 0;
        foreach (Vector3 position in originalVertices)
        {
            if (!vertexIndices.ContainsKey(position))
            {
                Vector3 normal = new Vector3(0, 0, 1);

                   Vector2 texCord = GetTextureCoord(position);

                vertices.Add(new VertexPositionNormalTexture() { Position = position, Normal = normal, TextureCoordinate = texCord });
                runTime++;

                vertexIndices.Add(position, indexCounter++);
            }
        }

        List<int> indices = new List<int>();
        foreach (Vector3 position in originalVertices)
        {
            indices.Add(vertexIndices[position]);
        }

        outVertices = CalculateNormals(vertices.ToArray(), indices.ToArray());
        outIndices = indices.ToArray();
    }

```

And here comes my version of the "GetTextureCoord" from the forum I mentioned earlier.

```
    private Vector2 GetTextureCoord(Vector3 normal)
    {
        float targetU;
        float targetV;

        float normalisedX = 0;
        float normalisedZ = -1;
        if (((normal.X * normal.X) + (normal.Z * normal.Z)) > 0)
        {
            normalisedX = (float)Math.Sqrt((normal.X * normal.X) / ((normal.X * normal.X) + (normal.Z * normal.Z)));
            if (normal.X < 0)
            {
                normalisedX = -normalisedX;
            }
            normalisedZ = (float)Math.Sqrt((normal.Z * normal.Z) / ((normal.X * normal.X) + (normal.Z * normal.Z)));
            if (normal.Z < 0)
            {
                normalisedZ = -normalisedZ;
            }
        }
        if (normalisedZ == 0)
        {
            targetU = (float)((normalisedX * Math.PI) / 2);
        }
        else
        {
            targetU = (float)Math.Atan(normalisedX / normalisedZ);
            if (normalisedZ < 0)
            {
                targetU += (float)Math.PI;
            }
        }

        if (targetU < 0)
        {
            targetU += (float)(2 * Math.PI);
        }

        targetU /= (float)(2 * Math.PI);
        targetV = (-normal.Y + 1) / 2;

        return new Vector2 { X = targetU, Y = targetV };
    }

```

In this forum thread There is apparently two ways it was managed to get solved. One way was to "*count the number of faces used for a given level of subdivision, and thus be able to tell when I was outputting a face if it lay on the seam*".

The other on was adding this to the "DrawTriangel" code.

```
point.Set (v1[0], v1[1], v1[2]);
GetTextureCoord (&point, &texU1, &texV);
point.Set (v2[0], v2[1], v2[2]);
GetTextureCoord (&point, &texU2, &texV);
point.Set (v3[0], v3[1], v3[2]);
GetTextureCoord (&point, &texU3, &texV);

if (texU2 - texU1 > 0.2 || texU3 - texU1 > 0.2){
    texAdd1 = 1;
}
if (texU1 - texU2 > 0.2 || texU3 - texU2 > 0.2){
    texAdd2 = 1;
}
if (texU1 - texU3 > 0.2 || texU2 - texU3 > 0.2){
    texAdd3 = 1;
}

```

And now to my question. Im not really sure how I could apply any of these ideas for solving this issue with the seam that appears.

So, anyone who have an idea how to solve this?

Not sure how I could convert and apply the code mentioned to my Vertices foreach-loop, or how to do this "counting" as mentioned.

**EDIT 2012-08-11**

OK, Iv updated my entire code to generate the subdivided Icosahedron as it was kind of complex before. It works like before with the seam.

So here it comes. should be easier to try out this code also.

```
public class Icosahedron2 : Component, I3DComponent
{
    #region   // I3DComponent values
    Vector3 position = Vector3.Zero;
    Matrix rotation = Matrix.Identity;
    Vector3 scale = new Vector3(1, 1, -1);
    BoundingBox boundingBox = new BoundingBox(new Vector3(-1), new Vector3(1));

    public Vector3 Position { get { return position; } set { position = value; } }
    public Vector3 EulerRotation
    {
        get { return MathUtil.MatrixToVector3(Rotation); }
        set { this.Rotation = MathUtil.Vector3ToMatrix(value); }
    }
    public Matrix Rotation { get { return rotation; } set { rotation = value; } }
    public Vector3 Scale { get { return scale; } set { scale = value; } }
    public BoundingBox BoundingBox { get { return boundingBox; } }
    #endregion

    // Effect
    BasicEffect basicEffect;

    // Terrain texture
    Texture2D terrainTexture;

    //Icosahedron variables
    private struct Triangle
    {
        public Vector3 v1;
        public Vector3 v2;
        public Vector3 v3;
        public bool OnSeam;
        public string vectorOnSeam;

        public override string ToString()
        {
            return "On seam:" + OnSeam.ToString() + " " + vectorOnSeam + ", " + v1.ToString() + ", " + v2.ToString() + ", " + v3.ToString();
        }

    }

    List<Triangle> BaseTrangleList = new List<Triangle>();
    List<Triangle> SubTringleList = new List<Triangle>();
    private float Radius;

    Dictionary<Vector3, int> vertexIndices = new Dictionary<Vector3, int>();
    List<VertexPositionNormalTexture> vertices = new List<VertexPositionNormalTexture>();
    VertexPositionNormalTexture[] renderVertecis;
    List<int> indices = new List<int>();
    int[] renderIndices;

    #region //Base Indices for Ichsahedron
    /// <summary>
    /// The indices of an icosahedron.
    /// </summary>
    static readonly int[] tindices =
    {
          1,4,0,     4,9,0,   4,5,9,    8,5,4,     1,8,4,
          1,10,8,   10,3,8,   8,3,5,    3,2,5,     3,7,2,
          3,10,7,   10,6,7,   6,11,7,   6,0,11,    6,1,0,
          10,1,6,   11,0,9,   2,11,9,   5,2,9,     11,2,7
    };
    #endregion

    #region //Base positions for Icosahedron
    /// <summary>
    /// The vertices of an icosahedron.
    /// </summary>
    Vector3[] vdata;

    float X_BASE = 0.525731112119133606f;
    float Z_BASE = 1.0f;

    private void SetBasePositions()
    {
        //  {-X_BASE,0.0,Z_BASE},{X_BASE,0.0,Z_BASE},{-X_BASE,0.0,-Z_BASE},{X_BASE,0.0,-Z_BASE},
        //{0.0,Z_BASE,X_BASE},{0.0,Z_BASE,-X_BASE},{0.0,-Z_BASE,X_BASE},{0.0,-Z_BASE,-X_BASE},
        //{Z_BASE,X_BASE,0.0},{-Z_BASE,X_BASE,0.0},{Z_BASE,-X_BASE,0.0},{-Z_BASE,-X_BASE,0.0}};

        vdata = new Vector3[]
        {

        Vector3.Normalize(new Vector3(-X_BASE, 0, Z_BASE)),
       Vector3.Normalize(new Vector3(X_BASE, 0, Z_BASE)),
       Vector3.Normalize(new Vector3(-X_BASE, 0, -Z_BASE)),
        Vector3.Normalize(new Vector3(X_BASE, 0, -Z_BASE)),

       Vector3.Normalize(new Vector3(0, Z_BASE, X_BASE)),
       Vector3.Normalize(new Vector3(0, Z_BASE, -X_BASE)),
       Vector3.Normalize(new Vector3(0, -Z_BASE, X_BASE)),
       Vector3.Normalize(new Vector3(0, -Z_BASE, -X_BASE)),

       Vector3.Normalize(new Vector3(Z_BASE, X_BASE, 0)),
       Vector3.Normalize(new Vector3(-Z_BASE, X_BASE, 0)),
       Vector3.Normalize(new Vector3(Z_BASE, -X_BASE, 0)),
       Vector3.Normalize(new Vector3(-Z_BASE, -X_BASE, 0))

        };
    }
    #endregion

    #region //Init(float radius, int subdivisions)
    private void Init(float radius, int subdivisions)
    {
        //Builds base triangles
        Radius = radius;
        SetBasePositions();
        for (int i = 0; i < tindices.Length; i += 3)
        {
            Triangle tri = new Triangle()
            {
                v1 = vdata[tindices[i]],
                v2 = vdata[tindices[i + 1]],
                v3 = vdata[tindices[i + 2]],
            };
          BaseTrangleList.Add(tri);
        }

        //Creates the subdevided triangles to make all of them
        foreach (Triangle triangle in BaseTrangleList)
        {
            Subdivide(triangle, subdivisions);
        }

        //checks if triangles are placed on seam
        CheckForSeamPlacement();

        //Creates verticis for all subdevided triangels
        int idCounter = 0;
        foreach(Triangle sub in SubTringleList)
        {
            if (!vertexIndices.ContainsKey(sub.v1))
            {
                Vector3 normal = new Vector3(0, 0, 1);
                Vector2 texCord = GetTextureCoord(sub.v1);
                vertices.Add(new VertexPositionNormalTexture() { Position = sub.v1, Normal = normal, TextureCoordinate = texCord });
                vertexIndices.Add(sub.v1, idCounter++);

                if (sub.vectorOnSeam.Contains("1"))
                {
                    //texCord.X = 1;
                    //Vector3 v12 = sub.v1;
                    //v12.X = 0.0000001f;
                    //vertices.Add(new VertexPositionNormalTexture() { Position = v12, Normal = normal, TextureCoordinate = texCord });
                    //vertexIndices.Add(v12, idCounter++);
                }
            }
            if (!vertexIndices.ContainsKey(sub.v2))
            {
                Vector3 normal = new Vector3(0, 0, 1);
                Vector2 texCord = GetTextureCoord(sub.v2);
                vertices.Add(new VertexPositionNormalTexture() { Position = sub.v2, Normal = normal, TextureCoordinate = texCord });
                vertexIndices.Add(sub.v2, idCounter++);
                if (sub.vectorOnSeam.Contains("2"))
                {
                    //texCord.X = 1;
                    //Vector3 v22 = sub.v2;
                    //v22.X = 0.0000001f;
                    //vertices.Add(new VertexPositionNormalTexture() { Position = v22, Normal = normal, TextureCoordinate = texCord });
                    //vertexIndices.Add(v22, idCounter++);
                }
            }
            if (!vertexIndices.ContainsKey(sub.v3))
            {
                Vector3 normal = new Vector3(0, 0, 1);
                Vector2 texCord = GetTextureCoord(sub.v3);
                vertices.Add(new VertexPositionNormalTexture() { Position = sub.v3, Normal = normal, TextureCoordinate = texCord });
                vertexIndices.Add(sub.v3, idCounter++);
                if (sub.vectorOnSeam.Contains("3"))
                {
                    //texCord.X = 1;
                    //Vector3 v22 = sub.v2;
                    //v22.X = 0.0000001f;
                    //vertices.Add(new VertexPositionNormalTexture() { Position = v22, Normal = normal, TextureCoordinate = texCord });
                    //vertexIndices.Add(v22, idCounter++);
                }
            }
        }

        foreach (Triangle pos in SubTringleList)
        {
            indices.Add(vertexIndices[pos.v1]);
            indices.Add(vertexIndices[pos.v2]);
            indices.Add(vertexIndices[pos.v3]);
        }

        renderIndices = indices.ToArray();

        renderVertecis = CalculateNormals(vertices.ToArray(), indices.ToArray());
        //renderVertecis = vertices.ToArray();
    }
    #endregion

    #region //CheckForSeamPlacement()
    /// <summary>
    /// Checks if any of the triangles are placed on the texture coord 0
    /// </summary>
    private void CheckForSeamPlacement()
    {
        List<Triangle> subSeamCheck = new List<Triangle>();
        foreach (Triangle sub in SubTringleList)
        {
            Triangle tri = sub;
            tri.vectorOnSeam = string.Empty;
            if (GetTextureCoord(tri.v1).X == 0)
            {
                tri.OnSeam = true;
                tri.vectorOnSeam += "1";
            }
            if (GetTextureCoord(tri.v2).X == 0)
            {
                tri.OnSeam = true;
                tri.vectorOnSeam += "2";
            }
            if (GetTextureCoord(tri.v3).X == 0)
            {
                tri.OnSeam = true;
                tri.vectorOnSeam += "3";
            }
            subSeamCheck.Add(tri);
        }
        SubTringleList = subSeamCheck;
    }
    #endregion

    //private bool FoundIndice(Vector3 pos)
    //{
    //    bool contains = false;
    //    foreach (Vector3 indi in vertexIndices)
    //    {
    //        if (indi == pos)
    //        {
    //            contains = true;
    //            break;
    //        }
    //    }
    //    return contains;
    //}

    #region //Vector2 GetTextureCoord(Vector3 normal)
    private Vector2 GetTextureCoord(Vector3 normal)
    {
        float targetU;
        float targetV;

        float normalisedX = 0;
        float normalisedZ = -1;
        if (((normal.X * normal.X) + (normal.Z * normal.Z)) > 0)
        {
            normalisedX = (float)Math.Sqrt((normal.X * normal.X) / ((normal.X * normal.X) + (normal.Z * normal.Z)));
            if (normal.X < 0)
            {
                normalisedX = -normalisedX;
            }
            normalisedZ = (float)Math.Sqrt((normal.Z * normal.Z) / ((normal.X * normal.X) + (normal.Z * normal.Z)));
            if (normal.Z < 0)
            {
                normalisedZ = -normalisedZ;
            }
        }
        if (normalisedZ == 0)
        {
            targetU = (float)((normalisedX * Math.PI) / 2);
        }
        else
        {
            targetU = (float)Math.Atan(normalisedX / normalisedZ);
            if (normalisedZ < 0)
            {
                targetU += (float)Math.PI;
            }
        }

        if (targetU < 0)
        {
            targetU += (float)(2 * Math.PI);
        }

        targetU /= (float)(2 * Math.PI);
        targetV = (-normal.Y + 1) / 2;

        return new Vector2 { X = targetU, Y = targetV };
    }
    #endregion

    #region //Subdivide(Triangle triangle, long subdiv)
    /// <summary>
    /// Devides the triangel according to the subdiv value
    /// </summary>
    /// <param name="triangle"></param>
    /// <param name="subdiv"></param>
    private void Subdivide(Triangle triangle, long subdiv)
    {
        Vector3 v12, v23, v31, v12_2, v23_2, v31_2;

        if (subdiv == 0)
        {
            SubTringleList.Add(triangle);
            return;
        }

        v12 = triangle.v1 + triangle.v2;
        v23 = triangle.v2 + triangle.v3;
        v31 = triangle.v3 + triangle.v1;

        v12_2 = Vector3.Multiply(Vector3.Normalize(v12),Radius);
        v23_2 = Vector3.Multiply(Vector3.Normalize(v23),Radius);
        v31_2 = Vector3.Multiply( Vector3.Normalize(v31),Radius);

        Triangle t1 = new Triangle { v1 = triangle.v1, v2 = v12_2, v3 = v31_2 };
        Triangle t2 = new Triangle { v1 = triangle.v2, v2 = v23_2, v3 = v12_2 };
        Triangle t3 = new Triangle { v1 = triangle.v3, v2 = v31_2, v3 = v23_2 };
        Triangle t4 = new Triangle { v1 = v12_2, v2 = v23_2, v3 = v31_2 };

        Subdivide( t1, subdiv - 1);
        Subdivide( t2, subdiv - 1);
        Subdivide( t3, subdiv - 1);
        Subdivide( t4, subdiv - 1);
    }
    #endregion

    #region //CalculateNormals()
    /// <summary>
    /// Calculates Noramals for vertices
    /// </summary>
    private static VertexPositionNormalTexture[] CalculateNormals(VertexPositionNormalTexture[] vertices, int[] indices)
    {

        for (int i = 0; i < vertices.Length; i++)
            vertices[i].Normal = new Vector3(0, 0, 0);

        for (int i = 0; i < indices.Length / 3; i++)
        {
            int index1 = indices[i * 3];
            int index2 = indices[i * 3 + 1];
            int index3 = indices[i * 3 + 2];

            Vector3 side1 = vertices[index1].Position - vertices[index3].Position;
            Vector3 side2 = vertices[index1].Position - vertices[index2].Position;
            Vector3 normal = Vector3.Cross(side1, side2);

            vertices[index1].Normal += normal;
            vertices[index2].Normal += normal;
            vertices[index3].Normal += normal;
        }

        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i].Normal.Normalize();
        }
        return vertices;
    }
    #endregion

    public Icosahedron2(float radius, int subdevisions)
        : base()
    {
        basicEffect = new BasicEffect(Engine.GraphicsDevice);
        SetupEffect();
        Radius = radius;
        Init(radius, subdevisions);
    }
    public Icosahedron2(float radius, int subdevisions, Texture2D Texture)
        : base()
    {
        basicEffect = new BasicEffect(Engine.GraphicsDevice);
        terrainTexture = Texture;
        SetupEffect();
        Radius = radius;
        Init(radius, subdevisions);
    }

    #region// Setup BasicEffect
    /// <summary>
    /// Setsup basic effect parameters
    /// </summary>
    private void SetupEffect()
    {
        basicEffect.Texture = terrainTexture;
        basicEffect.TextureEnabled = true;
        //basicEffect.VertexColorEnabled = false;
        //basicEffect.EnableDefaultLighting();
        //basicEffect.DirectionalLight0.Direction = new Vector3(1, -1, 1);
        //basicEffect.DirectionalLight0.Enabled = true;
        //basicEffect.AmbientLightColor = new Vector3(0.3f, 0.3f, 0.3f);
        //basicEffect.DirectionalLight1.Enabled = false;
        //basicEffect.DirectionalLight2.Enabled = false;
        basicEffect.SpecularColor = new Vector3(0, 0, 0);
    }
    #endregion

    #region //Draw
    /// <summary>
    /// Draw object
    /// </summary>
    public override void Draw()
    {
        // Look for a camera in the service container
        Camera camera = Engine.Services.GetService<Camera>();
        // Throw an exception if one isn't present
        if (camera == null)
        {
            throw new Exception("Camera not found in engine's"
            + "service container, cannot draw");
        }

        // Set effect values
        basicEffect.World = MathUtil.CreateWorldMatrix(position, rotation, scale);
        basicEffect.View = camera.View;
        basicEffect.Projection = camera.Projection;

        //RasterizerState rs = new RasterizerState();
        //rs.CullMode = CullMode.None;
        //rs.FillMode = FillMode.WireFrame;
        //Engine.GraphicsDevice.RasterizerState = rs;

        Engine.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;
        //Engine.GraphicsDevice.BlendState = BlendState.AlphaBlend;
        //Engine.GraphicsDevice.DepthStencilState = DepthStencilState.DepthRead;

        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            //VertexPositionNormalTexture
            pass.Apply();
            Engine.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, renderVertecis, 0, renderVertecis.Length, renderIndices, 0, renderIndices.Length / 3, VertexPositionNormalTexture.VertexDeclaration);
        }
    }
    #endregion
}

```

**Final update 2012-8-12**

Thanks to David Lively this problem has finally be solved. Using this code like this in the updated code will solve the problem.

```
 RepairTextureWrapSeam(vertices, indices);

 renderIndices = indices.ToArray();
 renderVertecis = CalculateNormals(vertices.ToArray(), indices.ToArray());

```

# Answer
> 4 votes
Here's a method I wrote about a year ago to fix this.

Essentially, it looks for triangles that have UV coordinates that appear in the wrong winding order, which should only happen when a face would span a texture edge. For instance, an edge `(v0,v1)` with UV coordinates `(0.99,0),(0.01,0)`. Your seam appears because the rasterizer doesn't realize that you only want the far right and left edge - it interpolates from `0.99` down to `0.01`, which causes your entire texture width to be squeezed into that face.

Call this method after you've completely generated your sphere. (Alternatively, you could examine the UV order as the sphere is generated, or even before subdivision, but that's another topic.)

This method tracks the number of changes that are made during the repair; the idea being that, if it's a LOT relative to the number of vertices in your model, something may be amiss.

I seem to recall writing this at about 4 AM before a presentation, so it's probably not the quickest or cleanest implementation, but the approach is sound and should work for any closed polyhedron.

```
    /// <summary>
    /// split vertices for faces that incorrectly span an edge of the texture
    /// </summary>
    /// <param name="vertices"></param>
    /// <param name="indices"></param>
    public static void RepairTextureWrapSeam(List<VertexPositionNormalTexture> vertices, List<int> indices)
    {
        var newIndices = new List<int>();

        var corrections = 0;

        /// whenever a vertex is split, add its original and new indices to the dictionary to avoid
        /// creating duplicates.
        var correctionList = new Dictionary<int, int>();

        for (var i = indices.Count - 3; i >= 0; i -= 3)
        {
            /// see if the texture coordinates appear in counter-clockwise order.
            /// If so, the triangle needs to be rectified.
            var v0 = new Vector3(vertices[indices[i + 0]].TextureCoordinate, 0);
            var v1 = new Vector3(vertices[indices[i + 1]].TextureCoordinate, 0);
            var v2 = new Vector3(vertices[indices[i + 2]].TextureCoordinate, 0);

            var cross = Vector3.Cross(v0 - v1, v2 - v1);

            if (cross.Z <= 0)
            {
                /// this should only happen if the face crosses a texture boundary

                var corrected = false;

                for (var j = i; j < i + 3; j++)
                {
                    var index = indices[j];

                    var vertex = vertices[index];
                    /// 0.9 UV fudge factor - should be able to get rid of this when I get more sleep
                    if (vertex.TextureCoordinate.X >= 0.9f)
                    {
                        /// need to correct this vertex.
                        if (correctionList.ContainsKey(index))
                            newIndices.Add(correctionList[index]);
                        else
                        {
                            var texCoord = vertex.TextureCoordinate;

                            texCoord.X -= 1;
                            vertex.TextureCoordinate = texCoord;
                            corrected = true;

                            vertices.Add(vertex);

                            var correctedVertexIndex = vertices.Count - 1;

                            correctionList.Add(index, correctedVertexIndex);

                            newIndices.Add(correctedVertexIndex);
                        }
                    }
                    else
                        newIndices.Add(index);

                }

                if (corrected)
                    corrections++;
            }
            else
                newIndices.AddRange(indices.GetRange(i, 3));
        }

        Debug.WriteLine("Corrected {0} of {1}", corrections, newIndices.Count / 3);

        indices.Clear();
        indices.AddRange(newIndices);
    }

```

# Answer
> 4 votes
To texture map a model you supply a 2D coordinate for each vertice, this coordinate is used to map the texture (2D) to the model (3D). This works fine for most models, but when your texturing a continous spherical object (such as a model of earth) you will at some point have a vertice where one of the coordinates is at the highest (X or Y value), and the next one is at its lowest. At this point the graphics card won't wrap around the texture the short way, instead it will go back over the visible texture, thus reflecting the texture and rendering the whole texture, causing a visible seam.

To fix this, as mentioned in the comments, you need to duplicate the vertices where the texture coordinate is at 0 (for one of the directions, X in this example), the duplicate vertice needs to have the texture coordinate set to 1, this allows the graphics card to understand that it should continue in a left to right direction in the texture, rather than going right to left.

# Answer
> 4 votes
I've been strugling with issue myself, and finally made it work. First of all, I learned that the octahedron should have the right orientation, because then you won't have to split any triangles. This is hard for me to explain, so here a picture for clarity:

In this picture, I've highlighted the vertices with red, where the texture U coordinate is 0. As you can see, (A) produces the zig-zag-like distortion, while (B) produces only vertical distortion. You want the orientation in (B), as this will save you some trouble. You can simply do this by modifying the starting configuration for the vertices of the octahedron you're subdiving.

My approach has been diffrent from yours, as I work with Points (Vector3's) and Triangles (collection of 3 indices), and then convert them to proper Index and Vertex objects once I'm done modifying them. This turned out to be usefull when correcting this issue.

Now, to get rid of the distorion follow theese steps:

1. Check each triangle if it is on the seam.

1a. Get each texture coord for the triangle.

1b. If one or two have their U coord = 0, it is on the seam

1c. If the remaining texcoords have U \> 0.5 (closer to 1 than 0) this triangle is also causing distortion.
2. If so, clone the vertices where texcoord.U = 0, and set the U value to 1.
3. Get the index of each cloned vertex
4. Alter the current triangle, to use theese indices instead.
5. Draw/Add the altered triangle

This approach will only work, if you have the right orintation of the octahderon as I mentioned earlier. I can't quite tell you how to implement this solution in your approach, but I hope this information can help you.

Edit: Btw, you can use this method for getting texture coordinates instead:

```
    private Vector2 MapUv(Vector3 p)
    {
        float u = 0.5f - ((float)Math.Atan2(p.Z, p.X) / MathHelper.TwoPi);
        float v = 0.5f - 2.0f * ((float)Math.Asin(p.Y) / MathHelper.TwoPi);

        return new Vector2(u, v);
    }

```

**Edit (2012-08-12)**

I've have cleaned and commented on my working solution - It's far from optimized at this point, but it gets the job done though.

It's quite a lot of code with the comments and all, so I've put it at http://pastebin.com/E6qG234u

---
Tags: xna, c#, 3d, 3d-meshes, geometry
---


# Question
Title: What is the difference between an impulse and a force related to a physics engine?
What is the difference between an application of an impulse and an application of a force in relation to a physics engine?

# Answer
> 31 votes
An impulse is applied instantly, so it does not depend on the time step. You would use an impulse when you want to give a fixed boost of speed to something, or the physical action happens too quickly (ex. bullets/gun ricochet, collisions, jumps, instant speed ups).

Meanwhile a force changes the speed directly proportional to the time step. You use it for things that have an over time effect (ex. gravity, long springs, air resistance).

Mathematically `impulse = force * time`; And for reference `impulse = mass * velocity_change`, `force = mass * acceleration`.

If you expand the first, you can check this:

* `impulse = force * time` -\>
* `impulse = mass * acceleration * time` and since `acceleration * time = velocity_change` -\>
* `impulse = mass * velocity_change`.

---
Tags: c++, 2d, physics
---


# Question
Title: Isometric drawing "Not Tile Stuff" on isometric map?
So I got my isometric renderer working, it can draw diamond or jagged maps...Then I want to move on...How do I draw characters/objects on it in a optimal way?

What Im doing now, as one can imagine, is traversing my grid(map) and drawing the tiles in a order so alpha blending works correctly.

So, anything I draw in this map must be drawed at the same time the map is being drawn, with sucks a lot, screws your very modular map drawer, because now everything on the game (but the HUD) must be included on the drawer..

I was thinking whats the best approach to do this, comparing the position of all objects(not tile stuff) on the grid against the current tile being draw seems stupid, would it be better to add an id ON the grid(map)? this also seems terrible, because objects can move freely, not per tile steps (it can occupies 2 tiles if its between them, etc.)

Dont know if matters, but my grid is 3D, so its not a plane with objects poping out, its a bunch of pilled cubes.

# Answer
Instead of having the map drawer traverse the grid, make it traverse every drawable object and make no distinction between tiles or whatever else you have on the screen. There's no need for the drawer to know about tiles, it should know only about sprites and their position on the screen. You can also add a Z value to your screen objects and have an ordered list based on that Z, so the drawer can just draw from the first to the last in that list and they will be in the right position in the screen.
> 3 votes

---
Tags: xna, rendering, maps, isometric, character
---


title: How do I solve my resolution problems?

text:
# Question
Title: How do I solve my resolution problems?
I am developing a game with XNA, and I am having trouble with resolutions. For now, I have only implemented the main menu, but I want to make a game that is independent of the resolution. As I am a beginner, I haven't taken into account the resolution, so far. When I changed the resolution, it gave me a real headache. The background image that I use has a 1920x1080 resolution, so it has an aspect ratio of 16:9. The initial resolution was 800x600, so the background image looks stretched. The same happens with resolutions with aspect ratio 4:3 (e.g. 640x480, 1024x768, etc.).

Before posting this question, I searched for information on the Internet. I found *"XNA 2D Independent Resolution Rendering"*, and other similar solutions. The solution offered seems perfect for me, at first, because I wasn't thinking of using two resolutions; one internal, for drawing, and one that corresponds to the size of the window. However, I have been observing some problems.

---

When I enable fullscreen mode, and its resolution is lower than the desktop resolution, the game doesn't stretch the resolution to fill the entire screen. This makes the game draw at the center of the screen, but with a black border on both sides of the screen.

---

The aspect ratio of my background image is 16:9, however, the resolutions that I am trying have an aspect ratio of 4:3. With the page solution, I have the same problem; the background image seems to be stretched. I researched the code, to find a solution, and changed the `RecreateScaleMatrix()` function to this:

```
private static void RecreateScaleMatrix()
{
    _dirtyMatrix = false;
    float aspect = 16.0f / 9.0f;
    _scaleMatrix =
        Matrix.CreateScale((float)_device.GraphicsDevice.Viewport.Width / _virtualWidth,
        (float)_device.GraphicsDevice.Viewport.Height / _virtualHeight, 1f) *
        Matrix.CreateScale(1, EngineManager.GameGraphicsDevice.Viewport.AspectRatio /
        aspect, 1) * Matrix.CreateTranslation(0, (_device.GraphicsDevice.Viewport.Height -
        (_device.GraphicsDevice.Viewport.Height / aspect)) / 4.0f, 0);
}

```

This seems to have solved the problem, but only on certain resolutions ,and further reducing the rectangle which show the final result.

---

I have been thinking about these problems all day, and I realized that without knowing the exact resolution of the image to draw, in advance (independent of aspect ratio), is almost impossible to draw an image clearly.

How do I solve my resolution problems?

# Answer
The most simple answer is what you've already found: draw everything internally to a `RenderTarget` with a fixed resolution and after that use the `RenderTarget` as a texture and draw it as large as possible. You should be able to fill the entire screen if the aspect ratio is the same. Simply use the `Spritebatch.Draw` overload that uses a destination rectangle. If you use an internal resolution with an aspect ratio of 16:9 then you should create a rectangle like this:

```
//If the internal resolution and target resolution are both 16:9
Rectangle dest = new Rectangle
    (
        0,
        0,
        graphics.ViewPort.Width,
        graphics.ViewPort.Height
    );

//If the internal resolution is 16:9 and target resolution is 4:3
int height = (int)(graphics.ViewPort.Width * (16.0/9.0));
Rectangle dest = new Rectangle
    (
        0,
        graphics.ViewPort.Height - (int)(height / 2.0),
        graphics.ViewPort.Width,
        height
    );

```

Another approach would be to make sure that all text and GUI elements are withing a safe in the render target that has a 4:3 aspect ratio and then simply discard the most left and right part on a 4:3 screen. (This might give players with a 16:9 aspect ratio an advantage since they will have a larger FOV).

**Tip:** if you are developing your game for the XBOX360 you can jus develop for one resoltion since the XBOX will do the up and down scaling automatically for you. You should use an internal resolution of 720P since this is the highest resolution that the XBOX upscaler/downscaler can scale down to old-TV resolution.

Edit:

See the comments: the general formula for the destination rectangle that works for all aspect ratios where width \>= height would be:

```
double aspectratio = ((double)graphics.ViewPort.Width / (double)graphics.Viewport.Height);
    int height = (int)(graphics.ViewPort.Width * aspectratio;
    Rectangle dest = new Rectangle
        (
            0,
            graphics.ViewPort.Height - (int)(height / 2.0),
            graphics.ViewPort.Width,
            height
        );

```
> 4 votes

---
Tags: xna, resolution
---


title: Tools for level (wireframe) design

text:
# Question
Title: Tools for level (wireframe) design
We are currently working on a 2D platform game, all lot of the game elements have been created and designed. But now it is time to design all the levels.

What I am wondering is: Are there any tools which simplify level design, we prefer designing in basic wireframes, so no actual graphics yet. It would also be neat if the tool would allow layering specific groups;

1. Background
2. Platforms
3. Enemies

I have thought of tools like Visio or Omnigraffle but these aren't specifically meant for game design.

# Answer
> 2 votes
How about Gleed2D? It's XNA centric but since it is a 2D editor and emits XML for the level source it would be fairly usable in other frameworks.

I myself have a custom level designer for my 2D platformer which started from the Farseer physics samples.

This has some good links to 2D level editors and overviews.

# Answer
> 0 votes
It's maybe not the best suited solution but you could use Inkscape, a free vector based graphics editor. It's output is svg, which is basically xml. You can make layers in inkscape and draw your parts in the specific layer. You only need to define a basic rule set, on how to create the levels and what tools can be used and then parse the created svg files according to this ruleset, to generate your level objects.

# Answer
> 0 votes
I think SketchUp would be a good idea.

1. It is 3D, which could be nice to leverage.
2. You can use an orthographic camera and snap to a top-down view to make things 2D.
3. It supports different rendering modes, including x-ray and wireframe.
4. It has groups and components.
5. It has layers and an outliner.
6. It has a Ruby scripting API. (So, you can write custom tools/exporters)
7. It's simple to learn, easy to use, and there is a large community.
8. It's free.

---
Tags: level-design
---


# Question
Title: XNA how to draw some sprites tiled/wrapped and others not?
I already have:

```
mySpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);

```

and take care to draw all my sprites in order.

I now want to draw some textures tiled. Do I have to create another SpriteBatch and call:

```
mySpriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.LinearWrap, DepthStencilState.Default, RasterizerState.CullNone);

```

To draw my tiled textures? But won't these tiled sprites be drawn on top the ones already drawn with the previous SpriteBatch?

**What I would really like is to be able to do is draw some sprites normally and some tiled using the same SpriteBatch then my ordering wont be messed up. Is this possible?** I tried:

GraphicsDevice.SamplerStates\[0\].AddressU = TextureAddressMode.Wrap; GraphicsDevice.SamplerStates\[0\].AddressV = TextureAddressMode.Wrap;

In my first and only SpriteBatch but got the InvalidOperationException:

> Cannot change read-only SamplerState. State objects become read-only the first time they are bound to a GraphicsDevice. To change property values, create a new SamplerState instance.

# Answer
**Here's the problems you are having:**

1. Sorting for sprite batches only applies within that batch. At `End`, everything in the batch gets drawn to screen and becomes pixels. The default depth state for `SpriteBatch` does not read the depth buffer.
2. State objects (eg: `SamplerState`) are read-only once they are used. In this case, you're accessing the state that the graphics device *is currently using*. You can create a new state of your own, if you like - or use different existing ones.

**Here's what you need to do:**

Fortunately you don't have to create a custom `SamplerState`, as you can just use the built-in `SamplerState.LinearWrap`. Pass it into `SpriteBatch.Begin` like so:

```
spriteBatch.Begin(SpriteSortMode.Deferred,
                  null, SamplerState.LinearWrap, null, null);

```

(Note the use of `Deferred` \- this is the default. You should only use `Immediate` if you actually need that behaviour, as it is much, much slower. Passing `null` in for state objects causes `SpriteBatch` to use the default state object for that state.)

Then it's a simple matter of tiling your sprites. The trick to do this with `SpriteBatch.Draw` is the source rectangle parameter. **You can specify a source rectangle that extends beyond the edge of your texture.** If, for example, you wanted to draw your sprite tiled 3 times horizontally and 2 times vertically, here's how:

```
spriteBatch.Draw(myTexture, myPosition,
                 new Rectangle(0, 0, myTexture.Width * 3, myTexture.Height * 2),
                 Color.White);

```

Then, to draw a non-tiled sprite, simply don't specify a source rectangle.

---

It is worth noting the reason for the existence of `TextureAddressMode.Clamp`: If you draw a tile with `Wrap`, and then position or scale your sprite it so that a pixel in the sprite's texture does not perfectly line up with a pixel on the screen, you will find that your sprite gets a fringe where blending is happening between two pixels on the opposite sides of the texture. `Clamp` prevents blending from doing this by extending the edge pixels of the texture out to infinity. To avoid this problem you must either have pixel-perfect sprite positioning, or ensure that your art assets look reasonable if it happens.

It's also worth noting that this wrapping technique precludes the use of texture atlases. So, if you have many different tile types, it can be better for performance to just draw the tile multiple times. (Details)
> 10 votes

---
Tags: xna, xna-4.0, spritebatch
---


# Question
Title: C++ Void and Constructor Method Problem with Loops
I am having a problem on the console game I am making. How can I decrease the health of the character or enemy with loopings? My code goes like this by the way for example:

```
class RPG_Scene_Battle {
public:
  RPG_Scene_Battle(float ini_health) : health (ini_health){};
  float getHealth()
  {
      return health;

      }
  void setHealth(float rpg_val){ health = rpg_val;};

private:
  float health;
};

float conductDamage(RPG_Scene_Battle rpg_tr, float damage) {
  rpg_tr.setHealth(rpg_tr.getHealth() - damage);
  return rpg_tr.getHealth();
}

```

how can I do a do while loop to decrease the player and enemy's hp without returning the method? because returning the method `conductDamage` under the do loop would return the same value and not decrease constantly.

# Answer
> 0 votes
The problem is that the `conductDamage` function uses a new copy of the `RPG_Scene_Battle` object on each invocation (the parameter is passed by value), you need to pass a reference to the object instead. Simplest way of doing this is to change the signature of the function to

```
float conductDamage(RPG_Scene_Battle &rpg_tr, float damage)

```

---
Tags: c++
---


# Question
Title: Costs for developing an Iphone physics game?
I recently made a game demo inspired by a wooden board game where you drop the ball trying to make a score, is fully playable so take a look (Works best on firefox): https://dl.dropbox.com/u/62131673/LuckyBall-Chrome/index.html

I want to build this game for the Iphone's App Store, add accelerometer features, menus, unlockable levels, best scores, etc. I'm a graphic designer so I prefer to keep working on the presentation (graphics, assets, sound, music) and leave the rest to the programmer.

I want to know how much this game would cost for a programmer to be developed, so I can make a video at kickstarter.com and sell the idea, with luck this game will see the light.

I don't want to open a debate on the subject, I just need advice on the costs so I can hire someone.

# Answer
For a programmer to make a time estimation you would need to have a requirements specification. My advice is to make one of these and ask different programmers what they would charge to get it done. A junior developer might need more hours but will cost less per hour and vice versa for a senior one.

Another route which may suit well for you is to specify functionality for different iterations which you could then present as options on the kickstarter. This will also help you to determine high priority tasks.

I wouldn't venture a guess at total hours or cost with only the information given.

The game looks fun, good luck with the project!
> 1 votes

# Answer
the costs would mainly be with the iOS developer license which is $99/year and the an apple computer to use xCode. you can use 3rd party applications but xCode is the apple approved coding SDK.
> 0 votes

---
Tags: physics, iphone, costs
---


title: Java2D Game Flickering

text:
# Question
Title: Java2D Game Flickering
I'm in the process of trying to get familiar with making games in Java, using the Swing library.

Coding my Snake game however, I've got to a point where the game is flickering/ghosting and I haven't a clue why.

An example of the flickering can be seen on this short youtube video: http://www.youtube.com/watch?v=QP1IcZ5TRoY

I dread to post too much code here as it won't help anyone, but for glancers, I'll post some facts.

* Painting on a JComponent
* I do call super.paintComponent(g) at the start of my overrriden paintComponent method
* I've set setDoubleBuffered(boolean) to true.
* Although unsure of its necessity, I've invoked createBufferStrategy(2) on my JFrame
* My "game loop" is based on a swing.Timer calling repaint every 17ms, but tried, 30fps
* Snake piece moves at 25 pixel paces (or relative to world size).

This is how I draw each tile:

```
    for (int i = 0; i < gamePieces.length; i++) {
        int x = i % ROW_COL_SIZE;
        int y = i / ROW_COL_SIZE;

        if (gamePieces[i].equals(Tile.EMPTY)) {
            continue;

        } else {
            final SnakeGraphics gfx = gamePieces[i].getGraphic();
            gfx.draw(g2d, x, y, direction);
        }
    }

```

This is what is called on repaint:

```
public void render(Graphics2D g2d) {
    Direction dir = keyboard.getDirection();
    snake.setDirection(dir);
    snake.move();
    gameWorld.draw(g2d, dir);

}

```

and finally, how the snake moves:

```
public boolean move() {
    Point snakeHead = snake.getFirst();
    int x = snakeHead.x;
    int y = snakeHead.y;

    boolean success = validateStep(snakeHead); //boundary control + move

    if (success) {
        gameWorld.setTile(x, y, Tile.EMPTY);
        gameWorld.setTile(snakeHead.x, snakeHead.y, Tile.SNAKE_HEAD);
    }
    return success;

}

```

where gameWorld has all the tile information, i.e. what tiles get drawn and where, and Snake is just current position of the head thus far.

Apologies for the code-drop, but its all that I can determine to be relevant.

# Answer
I'm not experienced enough to say why exactly your game is flickering but I suspect it is because you use Swing. Swing is a good tool to develop 'regular' software but not for creating games / graphical software.

I did some research on this a while ago. Sadly I haven't taken good care of my documentation and lost some valuable links on the subject. However what you are looking for is not event-based rendering (like swing) but **active rendering**.

You should do your own research and determine what makes sense to you. Here are two links that may get you started: java games active rendering and Double Buffering and Active Rendering in Java with Swing Integration.

This is how I do it in my code:

At inistialisation:

```
        // Create game screen
        window = new JFrame("GameTitle"); // Create a new JFrame window
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set close operation
        window.setIgnoreRepaint(true); // Make active rendering possible
        window.setResizable(false); // Disable window resize

        // Create GUI, add to the screen
        Canvas screen = new GameScreen(); // Create canvas
        screen.setPreferredSize(new Dimension(800, 800)); // Set size
        window.add(screen); // Add to the window
        window.pack(); // Pack the window to fit the canvas set size
        window.setVisible(true); // Set visible

        // Create BufferStrategy object
        screen.createBufferStrategy(2); // Double buffer

```

Rendering inside the game loop:

```
        // Get buffer
        BufferStrategy buffer = screen.getBufferStrategy();

        // Get context from the JPanel we are going to draw to
        Graphics g = buffer.getDrawGraphics();

        // Start with clearing the drawing surface
        g.setColor(Color.MAGENTA);
        g.fillRect(0, 0, screen.getWidth(), screen.getHeight());
        g.dispose();

        // Call render processes (NOTE: this is my own render architecture)
        renderImage.run(entityManager, entityManager.getGroup("RENDERABLE"));

        // After we draw everything to the back buffer, we show that buffer
        buffer.show();

```
> 1 votes

---
Tags: 2d, java, performance, game-loop
---


title: global transform to local transform?

text:
# Question
Title: global transform to local transform?
If an object is attached to another one and you need to set its position, rotation and scale in global space, what do you do to get the local versions of these values, knowing the same values for the "parent" object?

# Answer
> 6 votes
You will want to store translation, rotation, and scale independently to make this easier (and in various cases, faster), but matrix decomposition will work.

The method for each of the three parameters is different but extremely easy.

**First, let's look at what you already know: how to get the world position from the child's local position and its parent's world position.**

For translation, simply add the parent's translation from the child's. If the parent is at (10,2,7) and the child's local translation is (1,-3,4), then the child's world position is (10+1,2-3,7+4) = (11,-1,11).

For rotation, apply the parent's rotation to the child's. If you're using a simplified quaternion class, this would mean simply multiplying the parent's rotation against the child, probably using an overloaded operator, e.g. world = parent.otation * child.rotation. Note that that is not the "proper" notation for quaternions, but it's how they're generally implemented in C++/C#/Java math libraries.

For scale, multiply the components of the parent against the child's. If the parent is (2,2,2) and the child is (0.5,1,2), then the world scale is (2\*0.5,2\*1,2\*2) = (1,2,4).

**To go the other way, simply do the complementary operations.**

To get the local translation, subtract the parent's world translation from the child's world translation. Using the same sample numbers from before: (11-10,-1-2,11-4) = (1,-3,7).

To get the local rotation, you'll want to multiply the child's world rotation by the parent's conjugate. The conjugate is simply the original quaternion with the vector parts negated, e.g. (-x,-y,-z,w).

To get the local scale, multiply the child's world scale with the reciprocal of the parent's world scale. With the previous example numbers, the parent had a uniform scale of 2, so its reciprocal would be a uniform 0.5: (1\*0.5, 2\*0.5, 4\*0.5) = (0.5,1,2).

---
Tags: 3d, mathematics, graphics, graphics-programming, spaces
---


# Question
Title: How do I extract a translation vector from a dual quaternion?
I'm trying to do some things with rigid body dynamics using dual quaternions (these are not the same thing as normal quaternions!) and I'm so close to getting things to work. The problem I'm having is extracting the translation vector from a dual quaternion. After looking some things up I found that if I have an array representing a dual quaternion like this one:

```
    JOINT[0,0]
    JOINT[0,1]
    JOINT[0,2]
    ...
    JOINT[0,7]

```

Then the translation vector part is given by 2\*(dual)'real where (dual)' is the conjugate quaternion of the dual part of the dual quaternion. This is what it looks like all typed out:

```
   x = 2*(-JOINT[0,4]*JOINT[0,1] + JOINT[0,5]*JOINT[0,0] - JOINT[0,6]*JOINT[0,3] + JOINT[0,7]*JOINT[0,2]);
   y = 2*(-JOINT[0,4]*JOINT[0,2] + JOINT[0,5]*JOINT[0,3] + JOINT[0,6]*JOINT[0,0] - JOINT[0,7]*JOINT[0,1]);
   z = 2*(-JOINT[0,4]*JOINT[0,3] - JOINT[0,5]*JOINT[0,2] + JOINT[0,6]*JOINT[0,1] + JOINT[0,7]*JOINT[0,0]);

```

However this isn't quite right. If I have an object not located at the origin it will rotate fine on the x and z axes but will freak out if I try to rotate it on the y axis. And if I rotate an object and then move it it will not move correctly. Anyways after a bunch of trouble shooting I'm pretty sure I am not extracting the translation portion of the dual quaternion correctly so I was hoping someone could tell me what I'm doing wrong.

@Christian Rau Thanks. You're right it was 2\*d\*r'. I don't suppose that you also know how to combine dual quaternions do you? I've tried multiplying two together (using the convention Q1\*Q2 = r1\*r1 + e(r1\*d2 + r2\*d1) where r is the real part and d is the dual part). I should probably explain that what I'm trying to do is combine a dual quaternion that describes and object's current position and orientation with one that describes it's change in position and orientation in order to find a dual quaternion that describes it's position and orientation after the change. However right now I can't get it to come up with the correct translation after multiplying the two together (I've tried both orders, Q1\*Q2 and Q2\*Q1).

@Christian Rau I meant to say Q1\*Q2 = r1\*r1 + e(r1\*d2 + d1\*r2) which is how I've been multiplying them together so far. The object that I'm displacing is sort of behaving correctly. It rotates relative to its own center of mass but as it rotates the axis of rotation changes. For instance if I rotate it on its z axis its x and y axes will rotate with it. I can get it to move only relative to its own axes. So it will move along its x axis If I want it to but if its x axis is no longer parallel to the global x axis it isn't doing much for me.

# Answer
> 2 votes
According to this paper about dual quaternion skinning, the translation vector corresponding to a unit dual quaternion is extracted as `2*dual*(real)'` rather than your `2*(dual)'*real`. I can confirm this after applying dual quaternion skinning in practice.

Now there may be different dual quaternion conventions (not sure about that), but it is worth a try. So just try to switch the quaternion conjugation from `dual` to `real`.

**EDIT**: You also seem to have an error in your dual quaternion multiplication code. You write that `Q1*Q2 = r1*r2 + e(r1*d2 + r2*d1)`, but this is wrong, since quaternion multiplication is non commutative and when multiplying Q1 and Q2, the 1-parts always have to be on the left and the 2-parts on the right. So it should actually be

```
Q1*Q2 = r1*r2 + e(r1*d2 + d1*r2)        (the last product has switched)

```

This makes no difference when working with simple dual numbers, but it matters the moment the individual elements (quaternions in this case) don't commute.

And by the way, since the dual quaternion transformation is theoretically applied to a point `v` as `QvQ'*`, two quaternions `Q1` and `Q2` should be multiplied in the order `Q2 * Q1` to get a transformation that first transforms by `Q1` and then by `Q2`.

# Answer
> -2 votes
For a noobs intro with source code on getting started with dual-quaternions, I'd take a look at this paper:

A Beginners Guide to Dual-Quaternions : What They Are, How They Work, and How to Use Them for 3D Character Hierarchies

Link: http://wscg.zcu.cz/wscg2012/short/A29-full.pdf

---
Tags: quaternion
---


# Question
Title: How do I correctly use dual quaternions for rotation and translation of an object?
Up until now I've handled a given object's rotation and translation separately using normal quaternions for rotation and vectors for translation. However I'd like to use dual quaternions to handle both an object's translation and rotation as I plan on using them for rigid body dynamics later. Basically I want it so I can have an object with an initial dual quaternion, multiply this dual by a second dual quaternion that describes the change in its displacement and end up with a third dual quaternion that describes its final position after the change is applied. I want a given object (I'll use a sphere as an example) to rotate locally around it's own center of mass but to move globally. Here's a video of the type of motion I'm looking for that apparently was accomplished using dual quaternions:

http://www.youtube.com/watch?v=k9I7Bbj02O8

Unfortunately the link to this examples source code doesn't load. Now I've tried getting this to work several times however the object I'm displacing (again a sphere) will either move globally but won't rotate locally or will rotate locally but will not move globally (its movement is based on how it is rotated). Basically this sums up what I'm doing:

1) At the start of the program I have an object with an initial dual quaternion describing its position and rotation (I'll call this quaternion Q1).

2) I change the object's rotational and or translational velocity. From this I calculate a second quaternion, Q2, which describes its change in rotation and acceleration.

3) I then multiply the two quaternions together (I've tried both orders of multiplication at this point but I believe the correct order is supposed to be Q2\*Q1). The formula I'm using to multiply them together is Q1\*Q2 = r1\*r2 + e(r1\*d2 + d1\*r2).

4) At this point I have a third dual quaternion that should describe the object's new location and orientation. The real part of the dual is a quaternion describing its orientation and the dual part can be converted to a translation vector using the formula t = 2\*dual\*(real') where real' is the conjugate of the real part of the third dual quaternion.

However this method isn't producing the results I want. The results I'm getting are predictable they just aren't the type I'm looking for, that is local rotation but global translation. Could someone please tell me the correct method of doing this?

# Answer
Well in case you are still interest, if you want to get started with dual-quaternion - just the basic transforming - back and forth (i.e., rigid transformations) - you might want to have a looksy at a beginners paper on the subject

A Beginners Guide to Dual-Quaternions : What They Are, How They Work, and How to Use Them for 3D Character Hierarchies

Link: http://wscg.zcu.cz/wscg2012/short/A29-full.pdf

Chow for now,

Simons
> 3 votes

# Answer
You can find the web page in the internet archive.

http://wayback.archive.org/web/\*/http://quaternion.110mb.com/

But sadly, it is not very helpful.

Please have a look at the following scientific paper. http://www.scss.tcd.ie/publications/tech-reports/reports.06/TCD-CS-2006-46.pdf It explains in detail, what you have to do.
> 1 votes

---
Tags: quaternion
---


# Question
Title: Handling movement in an Entity Component System
I'm working on a 2d RPG game in C# using an Entity-Component-System architecture, and I'm currently working on movement. Right now, I'm wondering how to organise the code so it looks a bit more.. pretty, or dignified, than it is. Currently, I have four components:

**VelocityComponent** \- Contains the speed (velocity) of an Entity. The behaviour currently is that if an Entity does not contain a VelocityComponent, then we continue onto the next Entity, because we cannot move if we haven't a velocity.

**TransformComponent** \- Contains the Width, Height, X and Y fields for the Entity. Basically, the position. Similar to VelocityComponent, if an Entity does not have a TransformComponent, then the GPSSystem just continues the next iteration, because we cannot move anywhere if we don't have a position.

**MovementComponent** \- Contains a pair of co-ordinates for use as a destination position, and a boolean indicating if the Entity is currently moving.

**MoveFromKeyboardComponent** \- Signals whether or not a key is pressed so that the Entity that this Component is attached to should move or not.

The update loop currently goes that the GPSSystem collects a list of **all** entities (by accessing the EntityManager. The EntityManager simply contains a key-value pairing of Guid to Entity of all active entities. All systems have access to it), then iterates over the whole lot.. It'd be better if I just posted the code;

```
    /// <summary>
    /// Update the GPS System.
    /// </summary>
    /// <param name="gameTime"></param>
    public override void Update(GameTime gameTime)
    {
        // Handle the movement.
        foreach (Entity entity in entityManager.GetEntities())
        {
            VelocityComponent velocity = (VelocityComponent)entity.GetComponent("Velocity");
            MovementComponent movement = (MovementComponent)entity.GetComponent("Movement");
            TransformComponent transform = (TransformComponent)entity.GetComponent("Transform");
            MovementFromKeyboardComponent movementFromKeyboard =
                (MovementFromKeyboardComponent)entity.GetComponent("MovementFromKeyboard");

            // can't do any movement manipulation without a transform (position) component.
            if (transform == null || velocity == null)
                continue;
        }

        base.Update(gameTime);
    }

```

However, I am unsure of how to proceed after this point. I just don't know how to manage the movement. I am aiming to have a movement style **similar** to Pokémon, where all Entities move one square (16 x 16) at a time and have smooth movement across those tiles, however the player can hold down a button and keep moving square after square, and when he releases that key, he stops moving (and snaps to the nearest tile if he is in the middle of two).

So, on to the question: Am I going about this correctly? Have I got too many (or too few) components for movement? And lastly, how would I manage the fact that an Entity may have a **MovementComponent** and a **MoveFromKeyboardComponent**? I'm just confused I suppose. I am not looking for the code for that, I am just wondering whether I am going about this correctly? This is my first whack at an entity component system, you see.

Best regards.

EDIT 1: I should add I have now changed the structure of the System class, such that it now has a ComponentAdded and ComponentRemoved method; that is, we no longer iterate over every Entity in existence every Update(), instead we store the entities that have components we want to listen to in a data structure in the class. My question remains the same, though.

# Answer
> 6 votes
If your design works with respect to your constraints, then, in some sense, it is correct. The following is how I would approach things, just in case you find it useful:

I would replace the VelocityComponent with a PhysicsComponent.

I like the idea that an entity is similar to a "thing" in your game, implying all entities, whether renderable or not, have a transform. With this in mind, I would not use a TransformComponent and instead have the transform as a field in Entity (or a subclass).

I would include the position, rotation, and scaling in the transform. I would not include the width and the height. If the width and height variables are for a bounding box, I would move them to a ColliderComponent.

I would break apart the MovementComponent. I would put the state code (i.e. the boolean indicating motion) in a StateComponent, where the StateComponent would be the hub for all information regarding the object's state. I would move the target information into a ControllerComponent.

I'm not sure what the exact purpose of signaling from MoveFromKeyboardComponent is. I would merge this component into ControllerComponent and have ControllerComponent drive the game object (by using the interface of PhysicsComponent to add forces/change velocity and by using the interface of StateComponent to know when to do what).

# Answer
> 1 votes
In my game engine I have an entity manager to keep track of entities and their components and I have a list of "processes" to act upon these components. Those processes take care of very elemental tasks.

Here is an example on the processes that would be called upon in one update call inside the game loop (em = entity manager):

```
    // Call processes
    accelerate.run(em, em.getGroup("ACCEL"));
    move.run(em, em.getGroup("MOVABLE"));
    collide.run(em, em.getGroup("COLLIDABLE"));
    resolveCollision.run(em, em.getEntitiesWithComponent(CollisionResult.class));
    render.run(em);

```

Now what happens is that I poll key input in *accelerate* and change the acceleration component of those entities (in this case the player). Then in *move* I move all objects according to their acceleration component.

Method run() inside *accelerate*:

```
    public void run(EntityManager entityManager, List<Integer> group) {
            for(Integer e : group) {
                // Get components
                Accel accel = entityManager.getComponent(e, Accel.class); // Used to control char movement
                Velocity vel = entityManager.getComponent(e, Velocity.class); // Used to control char movement

                // Update components
                // By default no acceleration
                vel.setDx(0);
                vel.setDy(0);

                if(inputHandler.keyActive(KeyEvent.VK_RIGHT)) { vel.setDx(vel.getDx() + accel.getAccel() * loop.getDt()); } // Accelerate char right
                if(inputHandler.keyActive(KeyEvent.VK_LEFT)) { vel.setDx(vel.getDx() - accel.getAccel() * loop.getDt()); } // Accelerate char left
                if(inputHandler.keyActive(KeyEvent.VK_UP)) { vel.setDy(vel.getDy() - accel.getAccel() * loop.getDt()); } // Accelerate char up
                if(inputHandler.keyActive(KeyEvent.VK_DOWN)) { vel.setDy(vel.getDy() + accel.getAccel() * loop.getDt()); } // Accelerate char down
            }
        }

```

When I want to move an entity I simply update the data in it's acceleration component.

Method run() inside *move*:

```
public void run(EntityManager entityManager, List<Integer> group) {
        // Loop through the entities
        for(Integer e : group) {
            Position pos = entityManager.getComponent(e, Position.class);
            Velocity vel = entityManager.getComponent(e, Velocity.class);

            // Update the entity components with their new position
            pos.setX(pos.getX() + vel.getDx());
            pos.setY(pos.getY() + vel.getDy());
        }
    }

```

Now the main difference I think between your implementation and mine is that instead of a specific component like `MoveFromKeyboardComponent`, I have specified groups of entities to update. I have processes that act upon groups of components. I have entities that I can add to as many groups as I want. I have fewer components and more processes.

# Answer
> 0 votes
I think there is something wrong in how you handle systems and entity fetching.

Your `EntityManager`/`Scene` shouldn't have a dictionary of all entity GUIDS, but rather, an dictionary-of-arrays that looks something like this:

```
entities =
{
    "Position": [c_Position, c_Position, "nothing"],
    "Movement": [c_Movement, "nothing", "nothing"],
    "Sprite": [c_Sprite, c_Sprite, "nothing"],
    "Input": [c_Input, "nothing", "nothing"],
}

```

As you can see, there are 4 *types* of components here. `c_Position` is an instance of the position component, and is just a normal vector. `c_Movement` is too, just a vector. If you want something to stop, then just set its movement vector to `{x: 0, y: 0}`, or delete it.

All systems would now have a neat way of requesting entities that interest them: `entities["nameOfComp"]`.

As for the input, that could be a system that has access to hardware stuff, and it is the one that actually knows the state. Then, it iterates over `entities["Input"]` and changes their movement components accordingly.

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


# Question
Title: How do we adapt our game to work over a network?
A friend of mine has made a Java version of a popular board game in Java, and has it working for multiplayer on one PC with different turns for each player. He's mentioned he wants it to eventually run from a webserver and people around the world can play the game together, but **he's dismissed this as impossible** (translated: Too hard to be worthwhile).

I'd like to make this happen for him, and I'm wondering:

* Do we need to completely rebuild or can we just adapt the existing code, for the game to work across a network?
* What are the advantages of a GWT based browser *game*, compared to a swing based client side game that updates to a server?

What is the common practice here, for going from one instance on one PC to multiple instances across several networked PCs?

### Edit:

The game code is very well broke and down and generalised; game logic and display are completely seperate. The main GUI is a scroll pane with a dungeon, squares are coloured for monsters, players, doors, floors etc, and are just JButtons essentially. Players have turns and then the monsters have a turn. It's very simple in essence.

# Answer
I know nothing of your game design, but I can say that attempting to develop a game in GWT probably isn't the best path to take. A team and I created a Words with Friends clone in GWT, and while we did get it fully working, we were very limited by what we could do graphically within the GWT framework. We also used Google App Engine as the server solution, and outside of using their great, but expensive, Channel API to update data between client and server in near-real-time, we had to just continuously poll the server, which wasn't ideal. This is just one issue you'll have to face when dealing with browser limitations. So, I would say there really is no advantage of using GWT alone, if due to the graphics limitations alone.

I'm not sure why your friend thinks "it's impossible", and it would be helpful to have more details on that, but I would have your friend take a look at PlayN. From the PlayN site:

> PlayN is an open-source cross-platform abstraction layer that uses the GWT compiler to take one code base written in Java and compile it into targets that run it as HTML5, Flash, Java, or as a native Android application.

It's hard to say the level of work involved without knowing more about your friends code base other then it's a Swing application, but he could port to PlayN, which I'd imagine would allow him to keep a majority of his game logic code. Regardless of porting or not, he would still need to implement networking capabilities in order to make the game multiplayer, both client and server side, "tack on" as you put it. What is impossible is to tell you if that would relatively be a nightmare or not without knowing about how he implemented his game in Swing.
> 2 votes

# Answer
The changes to the game logic to support networked play ought to be fairly minor. Essentially, the UI generates events which happen to be transmitted over a network. As long as all the events are pushed through a knothole somewhere, turning that into a networked version is relatively simple.

Developing the network infrastructure itself is difficult, because you have to deal with player disconnection and reconnection, simultaneous setup, and keeping all the players in synch. It's also probably unnecessary to do it yourself, as several good frameworks exist. (Try Jogre for example).

The hardest thing is developing an audience for the proposed web site, as it's not something you can do by just increasing your effort. Getting to the point where 4 players are routinely available to start a game is hard.
> 0 votes

---
Tags: java, multiplayer, online
---


# Question
Title: How is the Call of Duty checkpoint system implemented?
Does anybody know how it is implemented or has any advice how to do it?

I'm especially interested in how to avoid that a player dies right after a checkpoint. How does the game evaluate when it's save to do one. Of course there seem to be "simple" triggers based on passing through a position in the map or achieving certain objectives, but I'm pretty sure they avoid that the game saves while a bullet is in flight killing you.

I have the feeling that the game shows you something slightly different on every reload, like if it would save the game at one point and maybe do a little replay. If it reloads and you die quickly, the next reload will be slightly different, I feel.

Could it be that once a trigger for a checkpoint is passed, the game saves it's whole state to a new file. Then it waits for maybe 2s whether you die. Only if you don't die it saves the game. Is that all?

Maybe it even freezes it's random number generator and stores the next player actions, too. So when the checkpoint loads, it can fast forward a little bit and a different amount of time each load?

# Answer
Here are some possible ways to do handle this, which can be combined:

1. When loading a save game, adjust the game state to make the save point safe for the player for at least a few seconds. This has the downside that players can rush forward to a dangerous checkpoint, and know that even if they die after getting there the reload will fix it.
2. Skip auto saving when it's not a good place to load back into (e.g. if any enemy is in range and in line of sight). If you're too conservative with the tests the game may never save.
3. Let the player decide when to save. The downside here is that if the player forgets to save then they could lose lots of progress.
4. Let the player handle bad saves by selecting an older save to load.
> 4 votes

---
Tags: savegame
---


# Question
Title: Finding the normal from one 3d vector/line to any point on another 3d vector/line
Say I have two 3d vectors, `v1` and `v2` (you can consider them both lines if you like). I'm trying to figure out a normal for `v1` so that it intersects along any point of `v2`.

I keep drawing blanks on this one. It's easy enough to find a vector that points from `v1` to `v2` (just do `v2 - v1`), but that result isn't always perpendicular to `v1`.

How would you go about making that result perpendicular to `v1`?

# Answer
You can use scalar projection, i.e. the dot product, to do that.

You want to project v2 onto v1, so normalize v1 to length 1, then take the dot product: `float projection = dot(v2, normalize(v1));`

This tells you how far you have to go in the direction of v1 until you are perpendicular to the end of v2, so `float scalar = projection / length(v1);` tells you where on v1 that point is.

so `scalar * v1` gets you to that point, and `v2 - scalar*v1` would be the perpendicular vector from that point on v1 to v2.
> 2 votes

---
Tags: linear-algebra
---


title: Kinetic scrolling in AS3

text:
# Question
Title: Kinetic scrolling in AS3
I have a container movieclip that contains my "game" and I would like to be able to drag the "camera" (i.e. the container clip) around, but I need it to have kinetic movement, i.e. feel more like native dragging and scrolling on an iOS device.

I can't seem to find anything that deals with this properly and in the manner that I am looking for, and I also would prefer to stay away from using any 3rd party packages if there are licenses involved. This is for personal side projects that may or may not see a form of commercial release, so I would rather a) learn how to code this myself and b) not have to rely and pay for third party libraries.

Any help would be greatly appreciated.

Thanks!

# Answer
> 1 votes
To get a feeling of inertia you could average the velocities of the last few frames of dragging, and then set the speed of the camera to that when the user lets go.

Something like this:

```
static const BUFFER_LENGTH:int = 3;
static const FRICTION:Number = 0.95;

var dxBuffer:Vector.<Number>;
var dyBuffer:Vector.<Number>;

var lastX:Number;
var lastY:Number;

public function startDrag(x:Number, y:Number) {
    dxBuffer = new Vector.<Number>();
    dyBuffer = new Vector.<Number>();
    for (var i:int = 0; i < BUFFER_LENGTH; i++) {
        dxBuffer.push(0);
        dyBuffer.push(0);
    }
    lastX = x;
    lastY = y;
    camera.velocityX = 0;
    camera.velocityY = 0;
}

public function updateDrag(x:Number, y:Number) {
    // Discard the oldest velocity and buffer the newest
    dxBuffer.shift();
    dyBuffer.shift();

    dxBuffer.push(lastX-x);
    dyBuffer.push(lastY-y);

    camera.x += lastX - x;
    camera.y += lastY - y;

    lastX = x;
    lastY = y;
}

public function releaseDrag() {
    // Set camera velocity to average buffer value
    var avgdx:Number = 0;
    var avgdy:Number = 0;

    for each (var dx : dxBuffer) {avgdx += dx}
    for each (var dy : dyBuffer) {avgdy += dy}

    avgdx /= BUFFER_LENGTH;
    avgdy /= BUFFER_LENGTH;

    camera.velocityX = avgdx;
    camera.velocityY = avgdy;
}

public function updateCamera {
    // Update camera, to be called on each frame
    camera.x += camera.velocityX;
    camera.y += camera.velocityY;

    camera.velocityX *= FRICTION;
    camera.velocityY *= FRICTION;
}

```

Then to get a nice smooth slow down you can just multiply the velocity by a friction constant, 0.95 or so. You might want to increase the friction at very low speeds to get it to rest quicker.

---
Tags: ios, actionscript-3, ipad
---


# Question
Title: 2D mouse coordinates from 3d object projection
Not entirely certain of the nomenclature here -- basically, after placing a model in world coordinates and setting up a 3D camera to look at it the model has been projected onto the screen in a 2D fashion.

What I'd like to do is determine if the mouse is inside the projected view of the model.

Is there a way to "unproject" in the XNA framework? Or what is this process called as, so that I can better search for it?

# Answer
I can suggest a method i use

First of all, you must create a ray that represents your mouse position in 3d space

```
vector3 near = new vector3(mouse.x,mouse.y,0);
vector3 far = new vector3(mouse.x,moue.y,1);

near GraphicsDevive.Viewport.Unproject(near,view,projection,world);
near GraphicsDevive.Viewport.Unproject(far,view,projection,world);

```

matrix world must be inverse of your models world matrix.

```
vector3 direction = far - near;
Ray ray = (near,direction);

```

the test this ray for collision with models bounding sphere.

I demand excude for this arbitrary answer that can't be pasted in your project, but im little bit lazy to consult references.

UPDATE. http://xbox.create.msdn.com/en-US/education/catalog/sample/picking\_triangle Here is an accurate example of model picking. It is more accurate than mine, but it involves ModelProcessor modifying.
> 1 votes

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


title: How to attach two XNA models together?

text:
# Question
Title: How to attach two XNA models together?
I go back on unsolved question I asked about attaching two models together, could you give me some help on this ?

For example, If I want to attach together Model1 (= Main model) & Model2 ? I have to get the transformation matrix of Model1 and after get the Bone index on Model1 where I want to attach Model2 and then apply some transformation to attach Model2 to Model1

I wrote some code below about this, but It does not work at all !! (6th line of my code seems to be wrong !?)

```
Model1TransfoMatrix=New Matrix[Model1.Bones.Count];

Index=Model1.bone[x].Index;

foreach (ModelMesh mesh in Model2.Meshes)
{
  foreach(BasicEffect effect in mesh.effects)
  {
     matrix model2Transform = Matrix.CreateScale(0.1.0f)*Matrix.CreateFromYawPitchRoll(x,y,z);

     effect.World= model2Transform *Model1TransfoMatrix[Index];
     effect.view = camera.View;
     effect.Projection= camera.Projection;
   }
   mesh.draw();
}

```

# Answer
Your question is quite abstract.

I would suggest 2 methods.

1. using 3d redactor such as 3dmax or blender or whatever.
2. Draw second model using a SINGLE BONE absolute transform from model1.

It should look like:

```
Matrix[] Model1TransfoMatrix;
model1.CopyAbsoluteBoneTransformsTo(Model1TransfoMatrix);
foreach (ModelMesh mesh in Model2.Meshes)
{
  foreach(BasicEffect effect in mesh.effects)
  {
     matrix model2Transform = Matrix.CreateScale(0.1.0f)*Matrix.CreateFromYawPitchRoll(x,y,z);

     effect.World= model2Transform *Model1TransfoMatrix[0]; //root bone index
     effect.view = camera.View;
     effect.Projection= camera.Projection;
   }
   mesh.draw();
 }

```
> 1 votes

---
Tags: xna, 3d, xna-4.0
---


# Question
Title: OpenGL are strips/fans faster for rendering or just data bandwidth
When we send data for drawing we can mark it as TRIANGLE\_STRIP or TRIANGLE\_FAN to reduce the number of vertices we have to specify. Now, does this actually improve the rendering speed on the graphics card, or does it merely reduce the amount of data that has to be sent to the card?

I'm using a very simple model. To construct it correctly I need multiple calls to glDrawArrays using TRIANGLE\_STRIP. If I switch to using just GL\_TRIANGLES I could have just one call to glDrawArrays. Is this type of apporach useful, or is the overhead of an the call to glDrawArrays low enouhg that it won't make a difference.

I will profile, but since I have only one card I don't know if my result will be indicative of the general case. (NOTE: I need to be ES2 compliant, so some of my options are limited).

# Answer
A single call to glDrawElements with GL\_TRIANGLES should be the most optimal in the general case - have a read of https://web.archive.org/web/20130328101248/http://home.comcast.net/~tom\_forsyth/blog.wiki.html#Strippers \- strips are basically obsolete and have been for over a decade.
> 3 votes

# Answer
In general, you should not be using glDraw**Arrays** at all. If your model has repeated vertices, you'll get a lot more bang for your buck performance-wise from an index list. There, optimized strips or even triangles will be able to use the pre and post-T&L vertex caches. This means less memory fetching and less vertex shader execution.
> 4 votes

# Answer
A) If your model is simple then you most probably won't need to optimize at all (what's your specs in polycount, target machine etc. ?)

B) If the vertices in your model isn't changing (for example: a lamp post, a landscape, a human character in its bind-pose that the vertex shader will animate), use a VBO

VBO:s are very very fast as you just send your vertex data once at "level-startup".
> 2 votes

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


# Question
Title: How do I prevent dynamic GUI elements from overlapping in Unity?
I'm working on a birds-eye-view for our Unity3D game world, where each point of interest has a label hovering above it. The problem is that sometimes they overlap, although there is more than enough space on the screen for them to co-exist.

Can anybody think of a better way to separate them than checking every texture with every other texture and moving them away from each other?

# Answer
I managed to do it this way:

* Put all gui elements in a list.
* sort them from bottom to top on their Y coordinate
* loop through them in this order, if one collides with a previous one, move it up as much as necessary and go to the next.

this way you'll get a neat stack of GUI-labels (names of game objects in my case) and they'll never overlap.
> 3 votes

---
Tags: unity, gui
---


title: C# XNA Is key toggled?

text:
# Question
Title: C# XNA Is key toggled?
I've got a question about toggling keys. How do You check if the key is toggled?

Here's my quick and easy code:

```
    public class KeyToggle
    {
        private bool isEnabled = false;
        private Keys key = Keys.None;

        public KeyToggle(Keys key)
        {
            this.key = key;
        }

        public bool IsEnabled()
        {
            if (keyboardState.IsKeyUp(key) && previousKeyboardState.IsKeyDown(key))
                isEnabled = !isEnabled;

            return isEnabled;
        }
    }

    private KeyToggle keyToggleF12 = new KeyToggle(Keys.F12);

    protected override void Update(GameTime gameTime)
    {
        if (keyToggleF12.IsEnabled())
            Method();
    }

```

Do You have any better idea for checking if the key is toggled?

EDIT: I didin't mean if the key is clicked (aka current up, previous down). Toggled key is like CapsLock, You press it once and it's enabled, press it once more and it's disabled. I've updated my code a little bit:

```
    private List<KeyToggle> keyToggleList = new List<KeyToggle>();

    protected override void Update(GameTime gameTime)
    {
        if (IsKeyToggled(Keys.F12))
            Method();
    }

    public static bool IsKeyToggled(Keys key)
    {
        if (ReferenceEquals(keyToggleList.Find(x => x.Key == key), null))
            keyToggleList.Add(new KeyToggle(key));

        return keyToggleList.Find(x => x.Key == key).IsEnabled();
    }

```

# Answer
```
 keyboardState = Keyboard.GetState();

 if (!oldKeyBoardState.IsKeyDown(Keys.F12) && keyboardState.IsKeyDown(Keys.F12))
 {
     //Do Stuff
 }
 oldKeyBoardState = keyboardState;

```

Using 2 keyboard states is the best way in my mind, and I would say you are correct.

I wouldn't even use a class, I would just make a method and call it `IsToggled(Keys.F12);`

and check each key with that

```
bool IsToggled(Keys key)
{
   if (!oldKeyBoardState.IsKeyDown(key) && keyboardState.IsKeyDown(key))
      return true;
   else
      return false;
}

```

As suggested, There is a page on MSDN.

EDIT: I see you have another definition of "Toggled". I suggest you make a dictionary of bools or something, and do `Keys[key] =! Keys[key];` after you check if its been pressed.
> 5 votes

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


# Question
Title: Is there any option other than Component Based for game architecture?
Having read a lot recently on Component Based systems (for games), i find it hard to go back to my earlier state of mind.

If static object hierarchies fail to model "objects with a dynamic set of properties" then:

1. Why are they even used for in the first place? (in game dev and software engineering in general).
2. Is there any other option other than going Component Based to realize a more dynamic and flexible object model ?

# Answer
* Not everything has a dynamic set of properties. In fact, much of software engineering is about trying to pin down a precise and static specification of something.
* Static hierarchies are easier to reason about because they're broadly fixed in the code. Components can lead to an explosion of possible permutations - great if you need that flexibility, but difficult for someone to understand later.
* Components are not always a simple way to think about something. Often you're more interested in the whole than the parts, and the parts only become clear later. It's very hard to start out with a component based system for this reason.
* Nobody knows the best way of doing components yet. You can see this from the mountains of questions here asking about how to implement some aspect or other. The more traditional approaches are fairly unambiguous and straightforward by comparison.
* Components are really just another way of structuring code to do the same things that have always been done. If you wanted to be able to swap out some similar parts, you always had polymorphism for that. Design patterns like State and Strategy were facilitating components long ago. So you don't need to throw out all the old ways of working to enjoy most of the benefits.
* The choice was never between 'static object hierarchies' and 'component based systems' - people were writing software and games before inheritance was commonly used. You can approach shared functionality in many other ways, perhaps just by setting a flag that tells the system whether to call a certain function or not. Ultimately they're all just different routes to the same goal - different objects have different bits of data that require different functions to be called on them, and how you arrange that information has always been down to a combination of personal choice and the features of the language you use.
> 11 votes

# Answer
Well, definitely.

You don't have to go to extremes, like adam, who suggests that you should make your games more like databases and use declarative programming.

You could combine the approaches, for example, not having an entity manager but specific lists for various types of objects. Component based design is really useful when you end up with a monolithic class that defies the single responsibility principle.

Generally, in simpler games, or games where performance is needed, you might not want to use entity systems (but the performance greatly depends on the implementation).

As for why inheritance is used in game development, well, it was already there and natively supported, everyone else is using it, and it's simply intuitive. And seriously, if you plan ahead and use at least some component based design elements, you'll be fine with a classic implementation of a game.
> 1 votes

---
Tags: architecture, component-based, objects
---


# Question
Title: Should a 4x game use one class per planet type?
I'm try to make a small 4x game for my own educational purposes.

Currently I have interfaces like `IStarSystem` which contains a list of `IPlanet`s. My next step was to make classes implementing those interfaces. Is it better to make classes like `BarrenPlanet`, `GasPlanet`, et cetera or is it better to make a single `Planet` class and define the different types in a XML file?

# Answer
In general, it will be better for you to take an approach that doesn't senseless create complex inheritance hierarchies. It does not sound, from the limited information you've provided, that barren versus gaseous versus normal (et cetera) planets different so significantly that they warrant their own unique types. It sounds like these are all properties of a single `Planet` class.

Consequently, you should go with your second approach and create a single `Planet` class that can be configured by way of its properties (which you can load, as you noted, from XML or some other data store).

Because there is no *need* for unique types per planet type, this approach will be much more maintainable if only by virtue of having fewer types and thus less code to maintain.
> 7 votes

# Answer
Thanks to this question, I now know what 4x stands for, so thanks :)

Anyhow, I would say no, but it depends.

I think a classic example of classes is cars. Cars have several properties (color, make, model, weight, whatever suits you...) and several methods - say, gas, break.

Now, in the programming representation, if you were to, say, create a bunch of cars that share a certain set of properties and don't add more, then you would stick to a single class. For example, if cars had only a color and no other properties unique to each, then you would want one class. But if a specific car has special properties/behaviors - let's say, some cars can transform into some flying thing and some cannot. Flying objects will have different properties then the normal one, and so a new derived class is appropriate.

IF you think about inheritance, the general concept is, the base class is what they all have in common. Derived classes each need to differ in some respect.

So consider your planets. If each planet has, say, only a texture, position, rotationSpeed, and nothing else - then you can just craft different planets (like different colored cars) from this one class. On the other hand, if planets have special properties or methods, then you could make special classes for each planet, though they should still have SOMETHING in common and thus inherit from a Planet class. For example, if the gas planet can explode, dissapear, or has new fields (say, something about the atmosphere), then you can make a specific class for it, assuming a BarrenPlanet cannot do the same things.

In conclusion, it depends, but from what I can gather you could get by with a single Planet class (choose based on your circumstance, though), and as Josh said, needlessly adding a bunch of specific Classes with the inheritance will just make it confusing.
> 0 votes

---
Tags: 2d, architecture, maps
---


# Question
Title: How to rotate an object towards the walking direction?
I'm working on a game where you move a object on a game surface of cells, every time you move this object it steps to a cell, up, down, left or to the right. I have been trying to find out a way to rotate the object soo it is facing the moving direction. The rotation should be 90 degrees. It's one thing if the object is going from Up to Left and then rotate it 90 degrees, but what if object is going from Up to Down, then it need to rotate 180 degrees. I need some help with this issue to solve this in a simple and good way? Thanks!

This is the code for moving upwards and the other moving directions are similar. I'm using a short delay, so that the player can't move to fast on the game surface.

```
    // Upp
    public void Up()
    {
        if (milliSeconds1 >= walkingTimer)
        {
            Position = new Vector2(Position.X, Position.Y - walkingSpeed);
            milliSeconds1 = 0;
        }
    }

```

And in the Update:

```
Position = Position + Direction * 1;

```

EDIT: I solved this by myself! I just used radian values for each directions! :)

# Answer
It seems you already solved this, but I figured I could try to provide some info in the case it breaks, or potentially another way to do it.

Anyhow, your cell/grid approach sounds to me like what most RPGS would use (generally with the 3/4 view). In such games, your character can face four directions, where you face in the direction you moved last. If this IS the case, skip to the next paragraph. Otherwise, if you are making some sort of smooth rotation (i.e instead of a solid facing, the character/token/whatever\_moves smoothly turns ver several render frames), then what you can ideally do is, find the difference between the DESIRED angle (should be one of four for the cardinal directions) in terms of what you would need to incriment to go closer to said angle, and incriment a small portion of it. I still don't get how the formula works, but I beleive:

return ((((argument0 - argument1) mod 360) + 540) mod 360) - 180;

* will find the difference needed in terms of your current direction (arg0) to the desired (arg1). I have never done such smooth turning myself, though, so sorry if that is incorrect.

On the other hand, if you simply want to face the direction you move in, this is actually quite simple. My first recomendation would be to, if you don't already have something of this sort, have a function like move(direction), if your language supports enums, a direction enum would be useful here. (is this C#?) Inside that, you do a case statement (easy with only four cases). For reference, angles generally have RIGHT = 0, UP = 90, LEFT = 180, DOWN = 270 -hence, 360 = 0; Thus, you can, when moving said direction, rotate your (sprite?) character by the constant angle defined by that direction (as in, an absolute setting: calculating relative is a bit more tricky, but still pretty simple). Here is how I picture it:

```
void move(Direction direction)
{
    switch (direction)
    {
        case RIGHT:
            (set rotation/direction of character/sprite to 0)
            (other stuffs, like updating grid array to movement)
        break;
        case DOWN:
            (same as above but now it is 270)
        break;
        ...
    }
}
//UP = 90, LEFT = 180

```

Note that in general, 0 degrees is right, and it goes 360 degrees COUNTERclockwise. However, these may depend on what you are using (I know an external library which seems to rotate clockwise, which in theory is more natural but conflicts with the more general view, so you will have to figure this out yourself). Also, in the case you just want a different sprite for each facing direction, then you can simply set the sprite by case, for example, in RIGHT case you can do sprite = RIGHT\_SPRITE, etcetra.

Hopefully this will be useful, sorry if it isn't.
> 1 votes

---
Tags: xna
---


# Question
Title: Microsoft OpenGL layer via software emulation - docs
I would like to know about the main specs about this layer that renders OpenGL through software emulation.

What are the supported extensions and what is the OpenGL version supported? Fixed or programmable pipeline?

# Answer
Going by the header file (mine is in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Include\gl) it's OpenGL 1.1 with the GL\_EXT\_vertex\_array, GL\_EXT\_bgra, GL\_EXT\_paletted\_texture, GL\_WIN\_swap\_hint and GL\_WIN\_draw\_range\_elements extensions. That means fixed pipeline only and lot of modern functionality you might take for granted missing.

I'd strongly advise that you not even *think* of using this. It's a pure software implementation, and not a very good one at that - see: http://www.azillionmonkeys.com/windoze/OpenGLvsDirect3D.html, search for "CosmoGL" - so you can expect performance in the order of less than 1 fps. Yes, that's less than one frame per second (your graphics hardware plays a far more prominent role than some people seem to think).

If you really must use a software implementation Mesa 3D may be a better option: http://www.mesa3d.org/. As a software implementation it's still going to give you low-single-digit framerates, but at least you'll get support for more modern features (up to GL3.0 with more recent releases).
> 2 votes

---
Tags: opengl, microsoft
---


# Question
Title: How can I implement 3D textures using webgl?
I went through the google I/O video but did not get exactly how to do it. If somebody could point me to a simple 3D texture implementation using webgl, it would be helpful.

i basically have a volume, a cube, i want to fill it up with pixel data, which comes from a stack of images along the x-y axis. How do i do that?

# Answer
Here's the GLSL function slightly fixed from the Google I/O talk

```
  #define FILTER_LUT true

  vec4 sampleAs3DTexture(sampler2D tex, vec3 texCoord, float size) {
    float sliceSize = 1.0 / size;                  // space of 1 slice
    float slicePixelSize = sliceSize / size;       // space of 1 pixel
    float width = size - 1.0;
    float sliceInnerSize = slicePixelSize * width; // space of size pixels
    float zSlice0 = floor( texCoord.z * width);
    float zSlice1 = min( zSlice0 + 1.0, width);
    float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
    float yRange = (texCoord.y * width + 0.5) / size;
    float s0 = xOffset + (zSlice0 * sliceSize);

    #ifdef FILTER_LUT

      float s1 = xOffset + (zSlice1 * sliceSize);
      vec4 slice0Color = texture2D(tex, vec2(s0, yRange));
      vec4 slice1Color = texture2D(tex, vec2(s1, yRange));
      float zOffset = mod(texCoord.z * width, 1.0);
      return mix(slice0Color, slice1Color, zOffset);

    #else

      return texture2D(tex, vec2( s0, yRange));

    #endif
  }

```

The talk's code is hosted here.

If you want a 8x8x8 3D texture you'd make 64x8 texture and put each slice of the cube across the texture

```
[slice0][slice1][slice2]....[slice7]

```

Then make a sampler2D uniform in your shader and call

```
sampleAs3DTexture(yourSampler, your3DTexCoord, size)

```

where `size` the size of your cube (in the example size = 8)

NOTE: WebGL2 has built in support for 3D textures
> 5 votes

---
Tags: 3d, textures, webgl
---


# Question
Title: Random position of object in foreach loop
i need help with some "scary" thing. I'm creating some objects in foreach loop. Each object has implemented in Update function random change of position.
But while i'm creating this objects in foreach loop, each object gets the same random position, and i don't know why. Please help me.
For better explanation:

```
List<Object> objects;

```

in initialization:

```
objects = new List<Object>();
objects.Add(new Object());
objects.Add(new Object());
objects.Add(new Object());

```

and Update and Draw function:

```
foreach(var obj in objects)
    obj.Update(); // obj.Draw();

```

in Object Update function:

```
Position.X = rand.Next(width);
Position.Y = rand.Next(height);

```

The problem comming in launched game, where I can see only one object, instead of three. All that objects has same position, so they are covered by each other.

# Answer
I'm guessing each object has its own `System.Random` object initialized with the same seed? Try making it static for now and see if that fixes the problem.

Note: `System.Random` is not thread-safe, see: Getting random numbers in a thread-safe way for a solution, should you need it.
> 2 votes

# Answer
Look at this page.

According to the example in the "remarks" section, seperate instances of the class Random result in the same values when Random.Next() is called.

According to the documentation, you can solve this by having just one Random class and calling Next() when you need a random number. So the object classes in your code shouldn't have their own Random.

You can modify Update() to solve this:

```
public void Update(Random rnd) {

Position.X = rnd.Next(width);
Position.Y = rnd.Next(height);
}

```

and call Update like this:

```
Random rand=new Random();

foreach(var obj in objects)
obj.Update(rand);

```
> 1 votes

---
Tags: xna, c#, windows-phone-7
---