# Question
Title: Keeping track of focused widget in GUI tree
I'm designing a GUI framework based on trees of widgets. Widgets are general control and container structures that are everything from panels to buttons to file dialogs. Widgets have an array of child widgets; a button contains a label and maybe an icon. Widgets are fed input events where the widget first does its own logic with the event then passes it on to its children. The application feeds input events to a single root widget, which can be anything from a single button in the middle of the screen to a full control window.

I need a way to handle which widget(s) receives keyboard events. I've decided that one of the widgets in a given widget tree would be the focused widget. Widgets would have a *gainFocus* method and a *loseFocus* method, which would be used in response to mouse click events or manually by the application. It's unlikely I'll implement tabbing. When one widget gains focus, any existing focused widget would naturally lose focus.

I still want each ancestor of the focused widget to see a given keyboard event in turn before it's given to the focused widget itself. So if I have a panel with a text box in it, the panel would see the event before the text box does. Therefore I really need to keep track of the chain of widgets from the root widget to the focused widget. I also need to maintain data integrity when I change focus so that all widgets in a tree can correctly tell whether or not they're the focused widget or an ancestor of the focused widget.

I've so far come up with giving widgets a *hasFocus* boolean and a *focusedChildIndex* integer. *hasFocus* would be set to true when the widget has focus. *focusedChildIndex* would be set to the index of the focused child in its child array, which could be the focused widget itself or the next widget in the chain leading to the focused widget, or -1 to indicate that there's no focused child. Setting these variables when one widget in the tree gets its *gainFocus* or *loseFocus* method invoked is something I'm stumped on though.

**Edit**

So we're clear, this is what I think my widget class will be like:

```
class Widget
    private Widget parent
    private Array<Widget> children

    // Methods for getters, adding widgets to widget trees, etc.
    ...

    public void mouseClick(int x, int y)
        doMouseClickEvent(x, y)
        for c in children
            c.mouseClick(int x, int y)

```

As you can see in `mouseClick` the widget sees the event before its children does. I want keyboard inputs to work the same way, except this time I want to only have a single chain from the root to the focused widget to see the event. Plus I need to make sure that when one widget gains focus the currently focused widget in the tree loses focus.

# Answer
I believe I've come up with a solution.

As I said earlier, I can use a `hasFocus` boolean to designate the actual focused widget and a `focusedChildIndex` to indicate which child widget leads to the focused widget.

```
class Widget
    private Widget parent
    private Array<Widget> children

    // True if this is the focused widget
    private bool hasFocus
    // Index of child that leads to the focused widget
    private int focusedChildIndex

    new()
        ...

        hasFocus = false
        focusedChildIndex = -1

    // Returns -1 if not an immediate child
    public int getIndexOfChild(Widget child)
        int index = -1
        for int i = 0, children.size() - 1
            if children[i] == child
                index = i
                break
        return index

    // Root of tree this widget is in, or widget itself if it is the root
    public Widget getRoot()
        Widget result = this
        Widget p = parent

        while p != null
            result = p
            p = p.getParent()

        return result

    public bool hasFocus()
        return hasFocus

    public int getFocusedChildIndex()
        return focusedChildIndex

    public void gainFocus()
        if not hasFocus
            getRoot().loseFocus()

            hasFocus = true
            onGainFocus()

            if parent != null
                parent.focusOnChild(this)

    // Used by gainFocus
    public void focusOnChild(Widget child)
        // This method can be run if
        //   - The widget is not already focused on a child
        //   - The given child is actually a child of this widget
        //   - The child is either the focused widget or has a focused child
        int index = getIndexOfChild(child)
        if (focusedChildIndex == -1) and (index > -1)
          and (child.hasFocus()
          or (child.getFocusedChildIndex() > -1))
            focusedChildIndex = index
            if parent != null
                parent.focusOnChild(this)

    public void loseFocus()
        if (parent != null) and (parent.getFocusedChildIndex() > -1)
            parent.loseFocus()
        else
            if hasFocus
                hasFocus = false
                onLoseFocus()

            if focusedChildIndex > -1
                int oldIndex = focusedChildIndex
                focusedChildIndex = -1
                children[oldIndex].loseFocus()

    protected virtual void onGainFocus()
    protected virtual void onLoseFocus()

```
> 0 votes

# Answer
I'm pretty sure all the widgets have parent in their information (except the root widget of course). So you can go back all the way up to the root whenever a key is pressed and pass events to all of them. I'm not really sure if you are found of static fields/methods but it can easily be implemented using those.

```
class widget
{
    public widget parent; // a referece to it's parent
    public static widget focusedWidget;
    public static void keypress(Key  k)
    {
        stack <widget> widgets;
        widgets.push(focusedWidget);
        while(widgest.Top.parent != null)   // first create a list of all widgets in the way back to root
            widgets.push(widgest.Top.parent);

        while(widgets.count != 0)           // then calling all widgets in that list starting from root
        {
            widgets.Top.OnKeyPress(k);
            widgets.pop();
        }
    }

}

```

also you can completely change how you look at the problem and add a focused widget to all your widgets. This way you'll have a little bit advantage of remembering which widgets had focus when user was working with another widget (maybe doing something in another window). but keeping track of is focused get's a little bit harder.

```
class widget
{
    public widget parent; // a referece to it's parent
    public widget focusedWidget;
    public void OnKeyPress(Key  k)
    {
        // do something here
        focusedWidget.ObKeyPress(k);
    }
    public bool hasFocus{
        get
        {
            if(parent == null || parent.hasFocus)
                return parent.focusedWidget == this;
        }
    }
}

```
> 2 votes

# Answer
What you're talking about here is an event-driven system. This is what most GUI systems use. It's always good to steal from the masters so, let's take a look at Flash's event driven system.

In this diagram, the user clicks on the red box. An click event is generated with the red box as target. As the event travels from the stage down to the box, every attached listener is called, which can stop the event from travelling further.

For instance, if the user clicks on the red box, but the root element has focus then the root element can stop the event from travelling futher.

Once the event reaches its target in the capturing phase, an optional bubbling phase occurs. Here, the event travels from the target element back up to the root. This is useful to for instance tell a parent element that a child element should have focus.

The event takes the following path:

So how would you implement this in C++? Well, take a look at the excellent libRocket. They have implemented an event-driven GUI system in C++. The gist of it is that an event should be an actual object and that you can attach event listeners to widgets. The event object keeps track of what phase it is in and what its target is. The widgets can listen to certain events and stop the event from progressing further.

The code for libRocket is well documented, I'd suggest taking a look at it for ideas.

*Images were taken from Introduction to event handling in ActionScript 3.0.*
> 1 votes

---
Tags: gui
---


# Question
Title: Implementing a multishot powerup for a top down shooter
I have a top down shooter wherein I generate a projectile on each mouse click at the player's position and translate it in a straight line until it reaches the edge of the screen.

I also have powerups that enhance the player's current weapon by giving a multishot for a certain time span. Here's my problem. I'm not sure of how to place the projectiles relative to the player so that they are offset to the "left" and the "right" instead of directly on the player's position.

In order words, I will need to:

```
Vector2 playerPosition = playerOne.Position;
Vector2 projectileOnePosition = playerPosition + offsetVector;
Vector2 projectileTwoPosition = playerPosition - offsetVector;

```

I'm having trouble calculating the offset vector because I need to take the current rotation of the player in to account as well.

TL;DR: How do I find a point relative to the player's current position taking rotation of the current player in to account? My theory is that it involves calculating a circle around the player with a specific radius that determines the distance away from the player and placing the points somewhere on that circle.

I can draw a picture if necessary. Right now I'm on my laptop so it isn't draw-friendly.

# Answer
If you want something like this, this is the way to achieve it:

```
// you should probably put this somewhere near the initialization code;
// no point in assigning it every frame:
float distance = 10.0; // how much our projectiles will be distant from the ship
// if your ship's rotation is stored in playerOne.Rotation and expressed in radians:
projectileOnePosition.X = playerPosition.X + Math.cos(playerOne.Rotation + Math.PI/12) * distance;
projectileOnePosition.Y = playerPosition.Y + Math.sin(playerOne.Rotation + Math.PI/12) * distance;
// for projectileTwo, substract ninety degrees, i.e. + Math.PI/12
// also, it is a good idea to keep PI/12 precalculated as constant
// PI/12 is 15 degrees. so we're setting th origins of the bullets on a circle
// which radius is *distance* (here it is 10, you should adjust to your values)
// and they are shifted by 15 degrees 'left' and 'right' relative to ship's
// rotation

```

If you are using degrees for rotation (I am not familiar with XNA enough, but this is basic stuff), you can convert them using simple formula Radians = Math.PI * Degrees / 180.0

Oh, and here is the source code for the swf
> 1 votes

# Answer
If you are looking to have a hotspot for each shot I would do something like this. This uses the hotspot (10, 0) in the example. I would not initialize `projectileHotspot` every game loop, this is just for the example.

```
Vector2 projectileHotspot = new Vector2(10, 0);

projectilePosition.X = player.Position.X + (Math.Cos(player.Rotation) * projectileHotspot.X);
projectilePosition.Y = player.Position.Y + (Math.Cos(player.Rotation) * projectileHotspot.Y);

```

Note that `player.Rotation` is assumed to be in Radians. `MathHelper.ToRadians(deg)` is a simple way to convert between radians, degrees, vice versa.

I created a simple image to help understand my perception of your question. The coordinates are not to scale but you should get the idea.
> 1 votes

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


# Question
Title: What algorithms exist for generating collision geometry from an image?
I am currently working on a game using SFML and Box2D. I am interested in generating collision geometry from the sprite data that I load into SFML. So, for example, an algorithm that would do this would take an image and find the edges (for example where the alpha area starts) and then generating a polygon that fits to those edges.

Can I be pointed to any resources that describe an algorithm to do this?

# Answer
The topic you’re touching on here is what is known broadly as “Feature Detection” and more specifically as “Edge Detection” (finding the edges in an image) and “Vectorization” (finding the edges in an image and generating an estimation of that image in terms of curve/poly data).

A couple common algorithms for vectorization are Sobel Edge Detection and Canny Edge Detection. Without some background in signal processing, implementing these on your own is going to take some work. Defining bounding data is usually something that is just done by hand, and most sprite based games use bounding boxes or bounding circles to simplify things.

If you’re really interested in polygon based collisions, and if generating the poly data in an external application to be loaded into your project would work I have another option that would work given that you indicated you would like the base the bounding on the edges of the alpha layer/mask. There is an open source application Potrace which performs vectorization of bitmap images. It also has an option which turns off all smoothing so that the generated vectorization is polygonal only (no curves) which is what you’ll want for doing collisions. It’s a command line application, so you could write a small program/script that extracts the alpha layer of the images (or loads the alpha masks - I'm not sure if you’re using masks or loading graphics with alpha layers) and runs them through Potrace. One of the output formats is DXF which is Well Documented and human readable format. It’s quite easy to work with and parse and you should be able to convert it to whatever format you want to store the vector data in.

***@ xuincherguixe:***

If you mean the process of edge detection itself, then yes, this would introduce a lot of extra computations; signal processing is always computationally expensive. But given the trivial size of polygon data, a development tool (the use of Potrace and some scripts as I described) could be used to generate the poly data to be loaded into the application at run-time along with the graphics.

If you mean extra collision computations due to the high poly count a tool like Potrace would generate, that could also be an issue, Potrace configuration and perhaps some additional form of polygon reduction might be required to get the bounding polygons to a reasonable number. Ultimately unless there is an **extremely** large number of sprites, or some form of procedural generation going on, just defining the polygons manually and/or just using bounding boxes/circles is probably the more straight forward (if less interesting) method.
> 3 votes

---
Tags: collision-detection, box2d, image
---


title: X and Y value to Vector2

text:
# Question
Title: X and Y value to Vector2
In the first code I get a Vector2 random position and create an object with that, but in the second code I want to use the same constructor to create an object, but I want to pass a X and Y value to the constructor, that expects a Vector2 value.

```
Vector2 newPosition = NewRandomPosition;
listTools.Add(new Tool(content, tools[i], newPosition));

```

I thought I could do something like this, but it didn't work!

```
int x = 30, y = 22;
listJunk.Add(new Junk(content, "junk", (x,y)));

```

Is there another way to do this? Thanks!

# Answer
> 3 votes
You need to create a `Vector2` from the `x` and `y` values before using it. For example:

```
listJunk.Add(new Junk(content, "junk", new Vector2(x,y)));

```

# Answer
> 3 votes
Use a Vector2 object like this:

```
listJunk.Add(new Junk(content, "junk", new Vector2(x,y)));

```

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


# Question
Title: Determining my playable area/field of view
Contrary to what I found searching for the answer, I'm not trying to see whether a character is in view of another character. What I need to find out is the size of the field of view. This is because I'm using Mercury Particle Engine in a 3D space, and while MPE emitters take parameters ranging from (0,0) being the upper left corner of the screen to (graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight) being the lower right corner of the screen, the positioning of enemy ships use Vector3 values, where (0,0,0) would be the exact center of the screen. Since my ships don't move along the Z axis, this isn't a problem. What is a problem, however, is translating their coordinates in 3D space to the correct particle emitter positions when I need to show them exploding. This is what I'm currently using to create the perspective field of view:

```
projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
  MathHelper.ToRadians(45.0f),
  GraphicsDevice.DisplayMode.AspectRatio,
  1250.0f,
  1450.0f);

```

And this is how I'm attempting to obtain the X and Y values for the particle emitter from the enemy ship position (however, the positions are not quite right with my math because I have the wrong constants):

```
x = ((float)graphics.PreferredBackBufferWidth/2) + (((float)graphics.PreferredBackBufferWidth/1700) * enemy[i].position.X);

y = ((float)graphics.PreferredBackBufferHeight / 2) + (((float)graphics.PreferredBackBufferHeight / 1100) * enemy[i].position.Y);

```

That being said, how do I calculate the proper constants from the information on hand?

# Answer
> 0 votes
I ended up just using trial and error to get the right constant values.

# Answer
> 0 votes
Couldn't you just project the positions with your matrix?

i.e.

```
Vector4 v4 = new Vector4(enemy[i].position, 1);
Vector4 tmp = new Vector4();

tmp = Vector4.Transform(v4, projection); // x,y in range [-1,1]
float x = (tmp.X+1)/2;
float y = (tmp.Y+1)/2;

```

---
Tags: xna, mathematics, camera
---


# Question
Title: Checking collision in an array - is there a better way?
MSDN suggested this, but I'm worried about it slowing down the game when there are a lot of objects to check:

```
for (int i = 0; i < enemy.Length; i++)
{
   if (enemy[i].isActive)
   {
      BoundingSphere enemySphere =
         new BoundingSphere(enemy[i].position,
         enemy[i].Model.Meshes[0].BoundingSphere.Radius *
         enemy[i].modelBoundingConstant);
      for (int j = 0; j < bulletList.Length; j++)
      {
          if (bulletList[j].isActive)
          {
             BoundingSphere bulletSphere = new BoundingSphere(
                bulletList[j].position,
                bulletModel.Meshes[0].BoundingSphere.Radius);
             if (enemySphere.Intersects(bulletSphere))
             {
                enemy[i].health -= 10;
                bulletList[j].isActive = false;

                break; //no need to check other bullets
             }
          }
       }
   }
}

```

Nested looping like this just doesn't seem like the most efficient way to check if a bullet connects with an enemy. Is there a better way?

# Answer
> 3 votes
My first suggestion is that you begin with the approach that you have posted, because it *might be fast enough*, and it's trivial to implement. Then if you identify a problem, move over to a more complex solution

The simple approach suggested by MSDN is is basically just linearly iterating over every bullet and enemy, and checking every possible combination once:

```
foreach(var enemy in enemies)
    foreach(var bullet in bullets)
        CheckCollision(enemy, bullet);

```

If it turns out that you have too many bullets and enemies that it will slowdown, there are certainly many ways to do it more efficiently. These techniques usually require you to implement a **space partitioning** data structure, such as a quadtree, octree, or even a simple grid.

I've talked about space partitioning data structures in a few answers before, so I'll link the two most relevant ones:

# Answer
> 3 votes
Plants vs Zombies just uses the N^2 algorithm, and they get quite a lot on the screen (on cell phones too...), so you are probably fine with just iterating. The absolute fastest would be using sweep and prune. The bullet physics library has a good implementation for reference. This is a good algorithm to just have in your toolbox if you make a lot of games.

---
Tags: xna, collision-detection, efficiency
---


# Question
Title: 3d world vertex translation to go to 2d screen coords
My technical english is a little rusty so to avoid misunderstands please be patient with me :)
I will try to be brief and clear

Situation:
\- I have a 2d sprite character on the screen
\- I've just start learning how to draw 3d primitives and work with the cameras
\- I'm working on a 2d isometric environment
\- I made a 3d isometric triangle which I want to center in character
\- I'm trying to do something similar to a flashlight

Problem:
\- The triangle is not centered on character (probably because of the scales between 2d and 3d workspace)
-the triangle speed does not match the character speed.

Code:

player vision

```
        playerVision = new VertexPositionColor[3];

        playerVision[0].Position = new Vector3(-15f, -30f, 0f);
        playerVision[0].Color = Color.Transparent;
        playerVision[1].Position = new Vector3(0f, 0f, 0f);
        playerVision[1].Color = new Color(70, 102, 25, 20);
        playerVision[2].Position = new Vector3(15f, -30f, 0f);
        playerVision[2].Color = Color.Transparent;

```

-

```
private void SetUpCamera()
{
    // isometric angle is 35º , for 50y = -107z
    viewMatrix = Matrix.CreateLookAt(new Vector3(0, -107, 50), new Vector3(0, 0, 0), new Vector3(0, 1, 0));

    // TODO: use viewport for whole window or just the draw area ?
    projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GameInterface.vpWholeWindow.AspectRatio, 1.0f, 300.0f);
}

private void drawPlayerVision(GameTime gameTime, SpriteBatch spriteBatch, Vector2 playerDrawPos)
{
    // 50 is related with the camera position in the axis
    // TODO: this probably is incorrect since it should be a module of the distance? btw points
    Vector2 playerPos = playerDrawPos / 50;

    effect.CurrentTechnique = effect.Techniques["ColoredNoShading"];

    effect.Parameters["xView"].SetValue(viewMatrix);
    effect.Parameters["xProjection"].SetValue(projectionMatrix);

    // rotating like a radar
    Matrix worldMatrix = Matrix.CreateRotationZ(3 * visionAngle);

    // moving to the character
    worldMatrix *= Matrix.CreateTranslation(new Vector3(playerPos.X, playerPos.Y, 0));

    effect.Parameters["xWorld"].SetValue(worldMatrix);
    //effect.Parameters["xWorld"].SetValue(Matrix.Identity);

    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
    {
         pass.Apply();
         Game.GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleList, playerVision, 0, 1, VertexPositionColor.VertexDeclaration);
    }
}

```

if you need more details please ask me I've been trying to figure out all by myself so its a little hard for me :)

Thank you for your assistance

# Answer
> 0 votes
I found that the issue was related with the usage of viewports. When defining viewports for 3d we need to define 2 extra props minDepth and maxDepth.

If we forget to define these two... the viewport is still valid for 2d but using unproject in 3d will return the NaN issue

---
Tags: xna, c#, 3d, camera, matrix
---


title: Overlapping vertices on sphere?

text:
# Question
Title: Overlapping vertices on sphere?
Iv started up doing some programming in XNA as Iv been doing C# for several years and would like to start do some 3D work with C# and XNA framework.

Right now Im trying to build a sphere by code. It renders fine, but as soon as I apply some light it looks like it it is drawn twise with and without normals for shading. It gets very flickery, between light-shaded and unshaded.

```
    basicEffect.EnableDefaultLighting();
    basicEffect.DirectionalLight0.Direction = new Vector3(1, -1, 1);
    basicEffect.DirectionalLight0.Enabled = true;

```

The code for generating the shpere data looks like this.

```
    public class Sphere : Component, I3DComponent
{
    float spehereRes = 10.0f;

    // 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; } }

    // Effect
    BasicEffect basicEffect;

    //Sphere variables
    short[] indices;
    int nvertices, nindices;
    VertexPositionColorNormal[] vertices;
    VertexBuffer vbuffer;
    IndexBuffer ibuffer;

    public Sphere(float radius)
        : base()
    {
        basicEffect = new BasicEffect(Engine.GraphicsDevice);
        SetupEffect();
        Setup(radius);
    }

    public Sphere(float radius, GameScreen Parent)
        : base(Parent)
    {
        basicEffect = new BasicEffect(Engine.GraphicsDevice);
        SetupEffect();
    }

    private void Setup(float radius)
    {
        nvertices =Convert.ToInt32( spehereRes) * Convert.ToInt32(spehereRes); // nr of vertices in a circle, nr of circles in a sphere
        nindices = Convert.ToInt32(spehereRes) * Convert.ToInt32(spehereRes) * 6;
        vbuffer = new VertexBuffer(Engine.GraphicsDevice, typeof(VertexPositionNormalTexture), nvertices, BufferUsage.WriteOnly);
        ibuffer = new IndexBuffer(Engine.GraphicsDevice, IndexElementSize.SixteenBits, nindices, BufferUsage.WriteOnly);
        CreateIndices();
        CreateSphereVertices(radius);
        CalculateNormals();
        vbuffer.SetData<VertexPositionColorNormal>(vertices);
        ibuffer.SetData<short>(indices);

    }

    #region// Setup BasicEffect
    /// <summary>
    /// Setsup basic effect parameters
    /// </summary>
    private void SetupEffect()
    {
        //basicEffect.VertexColorEnabled = true;
        //basicEffect.TextureEnabled = true;
        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

    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;

        // For each pass..
        foreach (EffectPass pass in basicEffect.CurrentTechnique.Passes)
        {
            pass.Apply();

            // Draw the terrain vertices and indices
            Engine.GraphicsDevice.SetVertexBuffer(vbuffer);
            Engine.GraphicsDevice.Indices = ibuffer;
            Engine.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, vertices, 0, nvertices, indices, 0, indices.Length / 3, VertexPositionColorNormal.VertexDeclaration);
        }
    }

    #region //CreateIndices()
    /// <summary>
    /// Creates Sphere Indices
    /// </summary>
    private void CreateIndices()
    {
        indices = new short[nindices];
        int i = 0;
        for (int x = 0; x < spehereRes; x++)
        {
            for (int y = 0; y < spehereRes; y++)
            {
                int s1 = x == spehereRes-1 ? 0 : x + 1;
                int s2 = y ==spehereRes-1 ? 0 : y + 1;
                short upperLeft = (short)(x * spehereRes + y);
                short upperRight = (short)(s1 * spehereRes + y);
                short lowerLeft = (short)(x * spehereRes + s2);
                short lowerRight = (short)(s1 * spehereRes + s2);

                indices[i++] = upperLeft;
                indices[i++] = upperRight;
                indices[i++] = lowerLeft;
                indices[i++] = lowerLeft;
                indices[i++] = upperRight;
                indices[i++] = lowerRight;
            }
        }
    }
    #endregion

    #region //CreateSphereVertices(float radius)
    /// <summary>
    /// Setup Sphere object
    /// </summary>
    /// <param name="radius"></param>
    void CreateSphereVertices(float radius)
    {
        vertices = new VertexPositionColorNormal[nvertices];
        Vector3 center = new Vector3(0, 0, 0);
        Vector3 rad = new Vector3((float)Math.Abs(radius), 0, 0);
        for (int x = 0; x < spehereRes; x++) //nr of circles, difference between each is 4 degrees
        {
            float difx = 360.0f / spehereRes;
            for (int y = 0; y < spehereRes; y++) //nr of veritces, difference between each is 4 degrees
            {
                float dify = 360.0f / spehereRes;
                Matrix zrot = Matrix.CreateRotationZ(MathHelper.ToRadians(y * dify)); //rotate vertex around z
                Matrix yrot = Matrix.CreateRotationY(MathHelper.ToRadians(x * difx)); //rotate circle around y
                Vector3 point = Vector3.Transform(Vector3.Transform(rad, zrot), yrot);//transformation

                vertices[x + y * Convert.ToInt32(spehereRes)].Position = point;
                vertices[x + y * Convert.ToInt32(spehereRes)].Color = Color.Black;
            }
        }
    }

    #endregion

    #region //CalculateNormals()
    /// <summary>
    /// Calculates Noramals for vertices
    /// </summary>
    private void CalculateNormals()
    {
        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();
    }
    #endregion
}

```

Any ideas about this would be appreciated. I lowered the spheres "resolution" to 10 to try find an answer while doing the drawing but looks kind of tricky.

# Answer
> 0 votes
Solved. Typical... :) Been struggling with this for a while now. and now that I posted for any tips i finally found the solution.

I had theese Rasterizer settings for rendering.

```
        RasterizerState rs = new RasterizerState();
    rs.CullMode = CullMode.None;
    rs.FillMode = FillMode.Solid;
    Engine.GraphicsDevice.RasterizerState = rs;

```

If i removed them and only ran

Engine.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

It worked as it should. Well if anyone else should have problem with overlapped drawing I hope this helps to check out how the Rastarizer is set.

---
Tags: xna, c#, 3d, vertex
---


# Question
Title: Techniques for lighting a texture (no shadows)
I'm trying to learn about dynamic shadows for 2D graphics. While I understand the basic ideas behind determining what areas should be lit and which should be in shadow, I don't know how I would "lighten" a texture in the first place.

Could you go over various popular techniques for lighting a texture and what (dis)advantages each one has? Also, how is lighting a texture with colored light different from using white light?

# Answer
> 1 votes
The most common lighting model is Blinn Phong and Wikipedia has also this list of lighting techniques.

Lighting with textures is same, but you have diffuse (specular) color stored in texture instead of per vertex color.

> Also, how is lighting a texture with colored light different from using white light?

Same as in real. If you lighten white paper with green light it will reflect green light so paper will look green, but if you'll lighten red paper with green light it won't reflect green light (just little bit, but that doesn't matter).

# Answer
> 1 votes
Bump mapping is one technique. It creates dark and light areas on a flat texture that would normally be the same brightness.

This requires the use of a pixel shader,A bump(normal) map to determine normals. And the texture you want to apply the bumps.

With bump mapping you could make a flat drawn cylinder actually look round with the correct normal map. You also need to position you light source in your 2D space. It doesn't have to be an actual light source as you can feed any coordinate into the shader without one. But it will look like you have a light source.

This tutorial helped me understand it the most. I still couldn't make it from scratch. http://www.swiftless.com/tutorials/glsl/8\_bump\_mapping.html

---
Tags: 2d, lighting
---


# Question
Title: Cocos2d: Using single timer/scheduler for multiple sprites
want to know if is it possible to use single timer or scheduler method for multiple sprites ? Like I am now working on a game and there could be any number of sprites and i want to perform some actions on all of that sprites, So do I have to use as many timers or schedulers as sprites ? Or How can the job be done using only a single timer or scheduler ? What is I schedule a method and use it for, Say 10 sprites ? Will it affect the performance..?

# Answer
Usually you'll just create one scheduler that calls the `update` method of your world/game. There you iterate through all entities/sprites and call their update method.

This gives you much better control about the flow of your code. You'll be able to run the physics-simulation first and then iterate through all bodies/sprites and update their position.

Having all entities within a data-structure also gives you greater control about when/how entities will be added and removed from updates as well as better means of debugging (scheduled updates can be cumbersome to debug if you have lots of sprites).
> 3 votes

---
Tags: iphone, cocos2d-iphone, box2d
---


# Question
Title: Detect mouse click on a bezier curve's neighborhood
I'm developing a game in HTML5 and JavaScript using Canvas API for drawing graphics. I want to detect if the user has clicked on a bezier curve which has the line width of 20 pixels (something like this one on the picture). I need to validate if the user has clicked on the area drawn by the curve (red and black).

I implemented such an algorithm for lines, but could not adapt it to quadratic and cubic bezier curves. So I need an algorithm that will compare the position of a point relative to a bezier curve which has the form of

$$ B(t) = P\_0 (1-t)^2 + P\_1 (1-t)t + P\_2t^2$$

for quadratic bezier curves or

$$ B(t) = P\_0 (1-t)^3 + 3P\_1 (1-t)t + 3P\_2(1-t)t^2 + P\_3t^3$$

for cubic bezier curves, and check if it is in the neighborhood of the bezier curve's path, I mean on the black drawn area.

\[Red: Bezier curve's path; Black: Bezier curve's drawn area\]

# Answer
> 2 votes
https://stackoverflow.com/questions/2742610/closest-point-on-a-cubic-bezier-curve

In particular, The last answer on the page gives this link, which I thought explained it fairly clearly:

http://jazzros.blogspot.com/2011/03/projecting-point-on-bezier-curve.html?m=1

---
Tags: mathematics, graphics, javascript, html5
---


# Question
Title: I am looking to create realistic car movement using vectors
I have goggled how to do this and found this http://www.helixsoft.nl/articles/circle/sincos.htm I have had a go at it but most of the functions that were showed didn't work I just got errors because they didn't exist. I have looked at the cos and sin functions but don't understand how to use them or how to get the car movement working correctly using vectors. I have no code because I am not sure what to do sorry.

Any help is appreciated.

EDIT:

I have restrictions that I must use the TL engine for my game, I am not allowed to add any sort of physics engine. It must be programmed in c++. Here is a sample of what i got from trying to follow what was done in the link I provided.

```
if(myEngine->KeyHeld(Key_W))
    {
        length += carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_S))
    {
        length -= carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_A))
    {
        angle -= carSpeedIncrement;
    }
    if(myEngine->KeyHeld(Key_D))
    {
        angle += carSpeedIncrement;
    }

    carVolocityX = cos(angle);
    carVolocityZ = cos(angle);

    car->MoveX(carVolocityX * frameTime);
    car->MoveZ(carVolocityZ * frameTime);

```

# Answer
It's not that hard to create a fairly good car movement (but this post will be pretty long). You'll need to "simulate" a couple of basic forces to make the car move physically plausible.

(All the code samples are pseudocode.)

***Acceleration***

First, you'll obviously need acceleration. Something as simple as the following line would do:

```
acceleration_vector = forward_vector * acceleration_input * acceleration_factor

```
* `forward_vector` — A vector pointing in the same direction as the car.
* `acceleration_input` — The input should be in the interval \[-1, 1\].
* `acceleration_factor` — The value of the acceleration (pixels / second^2, or whatever your units are).

***Steering***

Steering is also fairly simple. In principle, what you will do is to rotate the forward vector of the car as to make it point in some other direction.

```
steer_angle = steer_input * steer_factor
new_forward_vector = rotate_around_axis(forward_vector, up_vector, steer_angle)

```

You might encounter a complication here, however. If your input is through a keyboard, its value will be either -1 or 1 which means your car would turn instantaneously. You can fix this using a very simple linear interpolation (lerping):

```
 amount = time_since_last_frame * steer_lerp_factor
 forward_vector = lerp(forward_vector, new_forward_vector, amount)

```

The amount should depend on time such that your movement does not depend on your frame rate. The amount should be between \[0, 1\] and the smaller it is, the smoother the transition between the old and new vectors will be.

(At this point you will find that the car will steer even if it is standing still. To prevent that, multiply `steer_angle` by `current_speed / max_speed`, where `max_speed` is a constant defined by you.)

***Moving***

Now we'll apply the acceleration and move the car a certain number of pixels based on its velocity, acceleration, and on steering. We will also want to limit the car's speed such that it doesn't end up moving infinitely fast.

```
current_speed = velocity_vector.norm()
if (current_speed < max_speed)
{
    velocity_vector += acceleration_vector * time_since_last_frame
}

position_vector += velocity_vector * time_since_last_frame

```

***Your car is now sliding***

If I'm right, your car should now appear to be sliding whenever you are turning as if it was on ice. This is because there is no friction. On a real car there a high lateral friction (due to the wheels not being able to rotate sideways :P ).

You will need to reduce the lateral velocity. By not reducing it completely you can also make the car appear to be drifting.

```
 lateral_velocity = right_vector * dot(velocity_vector, right_vector)
 lateral_friction = -lateral_velocity * lateral_friction_factor

```

Since we're talking about friction, you might also want to have a force (of friction) that reduces your velocity such that when you stop accelerating, your car will eventually stop.

```
 backwards_friction = -velocity_vector * backwards_friction_factor

```

Your code for moving the car should now look like this:

```
// Friction should be calculated before you apply the acceleration
lateral_velocity = right_vector * dot(velocity_vector, right_vector)
lateral_friction = -lateral_velocity * lateral_friction_factor
backwards_friction = -velocity_vector * backwards_friction_factor
velocity_vector += (backwards_friction + lateral_friction) * time_since_last_frame

current_speed = velocity_vector.norm()
if (current_speed < max_speed)
{
    velocity_vector += acceleration_vector * time_since_last_frame
}

position_vector += velocity_vector * time_since_last_frame

```

***Closing notes***

I mentioned how you should apply lerping to steering; I think you might need to do the same thing for acceleration and possibly for the steer angle as well (you will have to store their values from the previous frame and lerp from that). Also all the vectors relative to the car (forward, right, up) should be of length 1.

Also, friction is a bit more complicated than I showed here. You should always make sure that its length is never greater than that of the acceleration needed to make the car stop (otherwise friction would make the car move the opposite way). So you should have something like:

```
dt = time_since_last_frame
backwards_friction.resize(min(backwards_friction.norm(), velocity_vector.norm() / dt))
lateral_friction.resize(min(lateral_friction.norm(), lateral_velocity.norm() / dt))

```
> 25 votes

# Answer
Judging from your question, I am going to assume you are relatively new to programming (which is a-ok btw!). I would suggest to use existing frameworks as realistic car simulation is one of the hardest aspects of physics to get right.

You did not mention 2D/3D restrictions so I am going to go ahead and suggest you download Havok SDK (free for non-commercial use) and get a simple demo up and running (they actually have demos that run out of the box \[get compiled on your system, all the code is there\], you don't have to do anything to get it to compile... just open the project and hit build).

Once you have some idea on the behind the scenes aspects of car physics (although you won't see the actual implementation of the physics, that is hidden, you will get to see the interfaces), I believe you will be in a better position to get it right when you do start on your own.

I also asked a similar question not too long ago. The links in there may help as well. And here's another link.

---

After looking at your edit, it seems you are looking to simply change the velocity of the car depending on the calculated angles (that is not realistic btw, so you should change the original question to reflect that). If the angles are part of the question (that you can't change) and you have to use the angles to calculate the new velocity, then go with what @teodron put in the comments.

Another way is to use vectors only. There are multiple approaches using vectors, I am going to present one.

A velocity is direction * magnitude (where magnitude is speed and direction is a normalized vector). Calculate the car's current speed and direction. Take the direction and add a vector (let's call it `D'`) to it that is perpendicular to it. This will change the car's velocity. No angles to mess around with (although you *can* use angles to determine the length of the perpendicular vector which can be you *turn factor* \[see below\] )

**How to calculate `D'`**: To find the perpendicular vector, take the direction of the original velocity, cross it with the direction vector coming towards the screen where the order you cross the vectors in determines the direction of the perpendicular vector. Then multiple this perpedicular factor with some *turn factor* which determines how fast the car it turning.
> 0 votes

---
Tags: c++, mathematics, movement, car
---


title: Saving and loading large tilemaps

text:
# Question
Title: Saving and loading large tilemaps
As the title state, I have a large tilemap 400 x 400 x 26. Which currently just about fairs when using it. Saving takes a couple of seconds and it saves to a .ser file which is okay at the moment however when re-loading the map it takes a couple of minutes and is painful.

I'm wondering how I can improve my saving/loading and also if possible improve the way the maps are used eg: using a 2D array instead of a 3D array but still with the z-level.

# Answer
> 1 votes
There are many things you can do.

First off, you can try compressing the data, which might and probably will help in many situations.

Another thing that might help is using chunks - dividing the map into smaller pieces (16x16, 32x32 or whatever you find to work best for you).
You can either use multiple files for this and load only the chunks that you need(or load them in order if you need all of them but not immediately) or, if your map is fixed in size, save them uncompressed in one big file with an index telling you which chunks are where and otherwise doing it the same as with multi-file solution.
Chunks have an additional advantage of not having to rewrite everything every time you modify something - just open the relevant file(s) or seek and write data at given locations in the file.

You should also investigate your loading/saving code because loading something that took seconds to save shouldn't be taking minutes. A good first guess would be to make sure you're not resizing an array thousands of times - if that's the case then either preallocate it or use a list and then convert it to an array.

Hope this helps.

# Answer
> 0 votes
Aside from the fact that even loading a file with some data of this dimension shouldn't take minutes (could you post your loading and tile filling algorithm?) you should try to load only what is instantly needed by your game and load the rest while the player is playing your game.

You could take your loading code and the fields that it fills and put it in an seperate thread that notifies the game if there is enough data ready for the player to start.

I'm writing a small 2D RTS Engine in Java and I use 2DArrays (ArrayList\>) while every Entity has its own z value (they wont change in my game). So it breaks 3 nested for loops down to 2 nested for loops. Even that approach isn't the most efficient way I think.

# Answer
> 0 votes
Map **chunks** is the key to optimize maps: loading, saving, drawing, processing etc.

---
Tags: java, tilemap
---


# Question
Title: How to use generic level editors with my arbitary code?
I have a game, breakout clone. It has a Block class that contains CCSprite as a property. Usually I made levels by manually setting those blocks to positions. Here comes the question, how do I use generic level editors with my custom code? All editors work with CCSprites and not my class. How can I overcome that?

# Answer
As sarahm said in a comment, you need to either import the maps from files saved by the level editor or write an exporter for it(if it supports plugins/extensions like this).

Since they're generic and as such meant to be used by more than just one game, the format is probably quite simple(and almost certainly documented somewhere, just search a bit) so writing an importer is most likely the better choice.

You will probably need to read type/position/any other properties you're interested in and use them to build your map(place objects, set tile types, etc.). You could always also convert said level files to your own format, but I doubt there is much reason to do this.
> 2 votes

---
Tags: cocos2d-iphone, ios
---


# Question
Title: apply non-hierarchial transforms to hierarchial skeleton?
I use Blender3D, but the answer might not API-exclusive.

I have some matrices I need to assign to PoseBones. The resulting pose looks fine when there is no bone hierarchy (parenting) and messed up when there is.

I've uploaded an archive with sample blend of the rigged models, text animation importer and a test animation file here: http://www.2shared.com/file/5qUjmnIs/sample\_files.html
Import the animation by selecting an Armature and running the importer on "sba" file. Do this for both Armatures.

This is how I assign the poses in the real (complex) importer:

```
matrix_bases = ... # matrix from file
animation_matrix = matrix_basis * pose.bones['mybone'].matrix.copy()
pose.bones[bonename].matrix = animation_matrix

```

If I go to edit mode, select all bones and press Alt+P to undo parenting, the Pose looks fine again.

The API documentation says the PoseBone.matrix is in "object space", but it seems clear to me from these tests that they are relative to parent bones.

> Final 4x4 matrix after constraints and drivers are applied (**object** space)

I tried doing something like this:

```
matrix_basis = ... # matrix from file
animation_matrix = matrix_basis * (pose.bones['mybone'].matrix.copy()  * pose.bones[bonename].bone.parent.matrix_local.copy().inverted())
pose.bones[bonename].matrix = animation_matrix

```

But it looks worse. Experimented with order of operations, no luck with all.

For the record, in the old 2.4 API this worked like a charm:

```
matrix_basis = ... # matrix from file
animation_matrix = armature.bones['mybone'].matrix['ARMATURESPACE'].copy() * matrix_basis
pose.bones[bonename].poseMatrix = animation_matrix

pose.update()

```

Link to Blender API ref:

http://www.blender.org/documentation/blender\_python\_api\_2\_63\_17/bpy.types.BlendData.html#bpy.types.BlendData

http://www.blender.org/documentation/blender\_python\_api\_2\_63\_17/bpy.types.PoseBone.html#bpy.types.PoseBone

# Answer
> 1 votes
I don't know if this is the correct answer (as I know relatively little about blender's behavior), but are the bones long enough? It kind of seems like the deformation is not being applied properly because of the way the bones are weighted. I am used to seeing other skeleton systems where the end of one bone touches the beginning of the next - here they appear to not connect.

---
Tags: 3d, matrix, blender, skeletal-animation
---


# Question
Title: Circle collision with a specific tile on a grid
Does anyone know of a good tutorial that will show collision detection on a 2d game platform without using any engines?

# Answer
> 0 votes
You can read a book about mathematics, like Eric Lengyel, Mathematics for 3D Computer Graphics. Real Time rendering book website has a lot of intersection methods and their mathematics.

---
Tags: android, collision-detection
---


title: C++ Function Parameter Changes Problem

text:
# Question
Title: C++ Function Parameter Changes Problem
I have a problem regarding how the values under a certain parameter doesn't change after being called again.

I have this kind of code, where, an imp (monster) and a character has to go for a battle:

```
#include <iostream>
using namespace std;

int gems = 0;

float imp (float imphp) {
float implife = imphp - 5.0;
return implife;
};

float character (float charlife) {
float charalives = charlife - 2.0;
return charalives;
};

int main () {
string charactername;
cout << "Hero Life: ";
cout << character(10.0) <<endl;
cout << "Monster Life: ";
cout << imp (10.0) <<endl;

};

```

My problem or rather a question is if I call the monster function again is that it returns the value as 1.

Code I used to call monster for the second time after the first turns of damage is done:

```
cout << monster << endl;

```

what happens there was it sends me a value of 1. how can i make it show the current value after the damage has been taken...? say if the imp takes another damage, how can i make my program show the current value, since if the imp took out 2.0 at first attack, then takes another 2.0, the value for the hp of the character to show is 6.0? Same with the other function, how can i return it to the current value?

# Answer
The problem with these functions are that they are pretty much depending on what is going in.

Your functions are not objects as you intended them to be.

```
#include <iostream>
using namespace std;

int gems = 0;

float characterHealth  = 10.0f;    //Can work with till it goes out of scope
float enemyHealth = 10.0f;    //Can work with till it goes out of scope

float imp (float imphp) {
float implife = imphp - 5.0f;
return implife;
};

float character (float charlife) {
float charalives = charlife - 2.0f;
return charalives;
};

int main () {
string charactername;
cout << "Hero Life: ";
cout << character(characterHealth ) <<endl;
cout << "Monster Life: ";
cout << imp (enemyHealth) <<endl;

};

```

Your problem is that you work with local variables of a function that are completely depended on what is going in.

You were aiming a bit more for this ( I think):

```
#include <iostream>
using namespace std;

int gems = 0;

class Entity {
    public:
      Entity(float startingHealth) : health(startingHealth){}; // initialize health
      float getHealth(){return health;}
      void setHealth(float value){ health = value;};
    private:
      float health;
};

float subtractHealthFrom(Entity& ent, float damage) {
   ent.setHealth(ent.getHealth() - damage);
   return ent.getHealth();
};

int main () {

 Entity character(10.0f);
 Entity enemy(10.0f);

 cout << "Hero Life: ";
 cout << subtractHealthFrom(character, 2.0f) <<endl;
 cout << "Monster Life: ";
 cout << subtractHealthFrom(enemy, 2.0f) <<endl;
 cout << "Hero Life: ";
 cout << subtractHealthFrom(character, 2.0f) <<endl;
 cout << "Monster Life: ";
 cout << subtractHealthFrom(enemy, 2.0f) <<endl;

};

```

This is just an example not THE way to do it. Just showing how you could manage data by creating classes and producing objects of them.

Also use f to tell the compiler that you are working with floats.

```
 float A = 1.0; // converts static double on right to float ( double is twice a float, therefor a double doesnt fit in a float)
 float B = 1.0f;// Nothing to do here, ok

```
> 0 votes

---
Tags: c++
---


title: IOException java problem

text:
# Question
Title: IOException java problem
I'm working through the Head First Java book, and one piece of code it makes me write looks like this:

```
import java.io.*;
public class GameHelper {
    public String getUserInput(String promt){
        String inputLine = null;
        System.out.print(promt + " ");
        try {
            BufferedReader is = new BufferedReader(
                    new InputStreamReader(System.in));
            if (inputLine.length() == 0) return null;
        } catch (IOException e){
            System.out.println("IOException: " + e);
        }
        return inputLine;
    }
}

```

But eclipse tells me the exception is never thrown from the try statement, what does that mean?

# Answer
> 1 votes
Your problem is simple. When the function reaches the end (getUserInput) and returns a value. That value is null because  `inputLine` is set to null and never set to anything else. Do what the other guy said (`inputLine = is.readLine();`) which reads the next line in the input (in this case the next input line). I am guessing that you are trying to get the next input and display it. This is what you want:

```
public String getUserInput(String promt){
String inputLine = null;
System.out.print(promt + " ");
try {
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        inputLine = is.readLine();
        if (inputLine.length() == 0) return null;
    } catch (IOException e){
        System.out.println("IOException: " + e);
    }
    return inputLine;
}

```

The error probably was with the `inputLine.length()` because inputline is null and `inputLine.length()` would be an error.

# Answer
> 2 votes
The telling part of your code is when you create the new BufferedReader and check to see if the newly-read line is of length zero:

```
BufferedReader is = new BufferedReader(
                new InputStreamReader(System.in));
        if (inputLine.length() == 0) return null;

```

Note that you haven't actually read in a line yet. Just add this line between the above two:

```
inputLine = is.readLine();

```

This will fix Eclipse's warning and ensure that you're actually reading a line from the input device.

---
Tags: java
---


# Question
Title: Engine and level of detail for maze / labyrinth / dungeon scene?
My question is similar to these:

I.e. in this case should I use jME3 or some other engine (I heard Unreal offers a free engine) for a 3D dungeon game and when I build up the dungeon, should I use an algorithm for a new dungeon every time or should I use a static scene?

I've code to build a small wall that adds it to my scene which is mostly programmaticly achieved with less 3D modelling and more algorithmic solutions:

```
  /** This loop builds a wall out of individual bricks. */
  public void initWall() {
    float startpt = brickLength / 4;
    float height = 0;
    for (int j = 0; j < 15; j++) {
      for (int i = 0; i < 6; i++) {
        Vector3f vt =
         new Vector3f(i * brickLength * 2 + startpt, brickHeight + height, 10);
        makeBrick(vt);
      }
      startpt = -startpt;
      height += 2 * brickHeight;
    }
  }

  /** This method creates one individual physical brick. */
  public void makeBrick(Vector3f loc) {
    /** Create a brick geometry and attach to scene graph. */
    Geometry brick_geo = new Geometry("brick", box);
    brick_geo.setMaterial(wall_mat);
    rootNode.attachChild(brick_geo);
    /** Position the brick geometry  */
    brick_geo.setLocalTranslation(loc);
    /** Make brick physical with a mass > 0.0f. */
    brick_phy = new RigidBodyControl(2f);
    /** Add physical brick to physics space. */
    brick_geo.addControl(brick_phy);
    bulletAppState.getPhysicsSpace().add(brick_phy);
  }

```

# Answer
> 2 votes
This is a rather broad question, and appears to cover two separate issues, generating the mazes and rendering them.

**Generation:** If your goal is to make a simple game with full control over how it plays out, a static map designed by you is the best way to go. However, if your goal is for lots and lots of replayability, or maybe a very, very long game, dynamically-generated maps are a good option.

There are numerous algorithms written up on generating mazes, and each one has its own quirks. I don't have much experience with them, however, so I can't suggest any.

**Rendering:** This all depends on how you want it to look. Scene graphs are not a cure-all, and are probably a bad idea for this, as scene graphs only take care of the translational relationships between objects.

If you take into account the fact that mazes have lots of walls, and if (of course) your walls actually go full height, the only walls you actually have to render are the ones immediately visible, and those are relatively easy to calculate with a modified version of the Ray Casting algorithm, or a breadth-first-search algorithm that runs off the 2D array that stores the maze.

If your maze imagery is simple enough, you can model a single wall and call the code that draws it, translating and rotating it for every location you need it drawn for.
(note that this is probably a good idea for your first maze game. Just make sure that your textures aren't too noisy so it's not blindingly obvious that this is what you're doing)

---
Tags: opengl, 3d, graphics-programming, jmonkeyengine, maze
---


# Question
Title: XNA: Instancing Cubes, Each Side Different Texture
I am trying to make thousands of instanced cubes, each with a unique texture on each side.

Am I going to have to split each cube into 6 instanced faces, or can I unwrap it in such a way the the texture atlas coordinates will come out right?

My idea is have each cube unwrapped into a 2 tile by 3 tile area as such:

Top Bottom Front Back Left Right

Will the unwrap make it into the DrawInstancedPrimitives call?

Next, some cubes will have different textures than others. I was thinking about handling it with an atlas. One 2x3 texture in one slot, and another texture in another, forming a multi-texture image.

Am I on the right track here?

# Answer
> 1 votes
Looking at your other question, you're building a Minecraft clone. Now I admit that I'm not sure what Minecraft's renderer does, but I would guess that it's not instancing.

Instancing helps you want to draw many identical *complicated* models in a single batch, with different transforms. While it is possible to use a custom shader to transform the texture coordinates, I don't really think it's a good idea.

If I were going to implement this, I'd probably start with a `DynamicVertexBuffer`. I'd fill the vertex buffer with faces - *not* cubes - doing the world transformation and selection of texture coordinates on the CPU.

**This is basically the same thing that `SpriteBatch` does to draw many different-textured quads** (and, like `SpriteBatch`, you must still use texture atlasing for this to work). But you will have the added advantage of not needing to rebuild the vertex buffer each frame - you only modify it when the world changes.

With this approach you can avoid drawing faces that are between two solid blocks - allowing you to skip most of the geometry. Additionally you can probably treat the vertex buffer as an unordered set of faces - so you'll only have to modify part of it when the world changes.

---
Tags: xna, textures, hardware, instancing
---


title: Understanding Tensors

text:
# Question
Title: Understanding Tensors
I don't seem to be able to visualize tensors. I am reading The Morgan Kauffman Game Physics Engine Development and he uses tensors to represent aerodynamics but he doesn't explain them so I am not really able to visualize them.

# Answer
> 3 votes
Instead of commenting, I decided to post this as an answer. Of course, it is a subjective view, but for students trying to understand the language of game physics and maths, it's a gem. You can view the explanation here:

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

---
Tags: physics, matrix
---


title: Rotating an object smoothly

text:
# Question
Title: Rotating an object smoothly
I'm trying to rotate a ship in an asteroid game. What I'm doing is creating a float angle variable and at each time I press left or right buttons, I increase and decrease it, and in the drawing function, I rotate the ship by that amount.

The behaviour that I get is not really correct, because what I want is at each press, the ship should move smoothly and not by small increments. This is what I'm doing:

```
 static float ang = 20.0f;

 if(event.getCode() == KeyEvent::KEY_RIGHT)
 {
      ship.m_Angle+=ang*getElapsedSeconds();
 }
 else if(event.getCode() == KeyEvent::KEY_LEFT)
 {
      ship.m_Angle-=ang*getElapsedSeconds();
 }

 gl::pushMatrices();
 gl::translate(Vec2f(m_Pos.x,m_Pos.y));

 gl::rotate(Vec3f(0,0,m_Angle));
 gl::scale(0.3,0.3,0.3);
 gl::color(ci::Color(1,1,1));

 gl::drawLine(Vec2f(-52,-23),Vec2f(69,0));
 gl::drawLine(Vec2f(-43,-20),Vec2f(-43,20));
 gl::drawLine(Vec2f(69,0),Vec2f(-52,23));
 gl::popMatrices();

```

EDIT: **I would also like to limit the angle, it goes forever and the variable will overflow.**

# Answer
```
static float ang = 20.0f;

if(  event.getCode() == KeyEvent::KEY_RIGHT)
{
    ship.m_Angle+=ang*getElapsedSeconds();
}
else if( event.getCode() == KeyEvent::KEY_LEFT)
{
    ship.m_Angle-=ang*getElapsedSeconds();

```

Should be:

```
static float ang = 20.0f;

if(  event.getCode() == KeyEvent::KEY_RIGHT)
{
    ship.m_Angle = fmod(ship.m_Angle + ang, 360);
}
else if( event.getCode() == KeyEvent::KEY_LEFT)
{
    ship.m_Angle = fmod(ship.m_Angle - ang, 360);
}

```

I've removed getElapsedSeconds(); as it would jump first frame as soon as a key would be pressed.

Note I've added the closing bracket on the second example, see last line, which looks like it is in the wrong place in your example and the fmod will ensure that it doesn't overflow.
> 1 votes

# Answer
Have 2 angles and a rotation speed value.

1 angle is a 'target' angle and another is the 'current' angle.

The 'current' angle is the displayed one that can take any visible rotation. The target angle is the one you change that can only take the angles you want to be selectable.

Every frame update make the 'current' angle increase or decrease in the direction of the 'target' angle by the desired rotation speed * elapsed time. When the buttons are pressed increase/decrease the target angle based on the direction in increments based on the number of rotation degree you want.

Just make sure that you don't overshoot the target angle otherwise you will jump back and forth around it.
> 2 votes

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


title: XNA 2D camera just part of screen

text:
# Question
Title: XNA 2D camera just part of screen
Is it possible to use the 2D camera, but just for a part of the screen? Perhaps I want some info on the screen about score and other things, but I want that at a fixed place, just like when not using a 2D camera?

# Answer
> 1 votes
Sure! Since there's no concept of 2D camera built into XNA, I am guessing that you are using some class to generate a `ViewMatrix` and passing that matrix as a parameter to `SpriteBatch.Begin()`.

If that's the case, the solution is simple... All you have to do is draw your score and anything that you don't want to be affected by the camera in a separate `SpriteBatch.Begin() / SpriteBatch.End()` block, but *without* passing it the `ViewMatrix`. Example:

```
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, camera.ViewMatrix);
// Draw game world
spriteBatch.End();

spriteBatch.Begin();
// Draw score and other information
spriteBatch.End();

```

# Answer
> 0 votes
Create a Vector2 called Camera. Say you want to show an object with respect to the camera, i.e. a non-HUD object, draw it at a position given by:

DrawPosition = ObjectPosition - CameraPosition;

For the score and other HUD stuff, don't consider the camera vector.

DrawPosition = ObjectPosition;

---
Tags: xna
---


title: Stage3D Agal Anti-Aliasing

text:
# Question
Title: Stage3D Agal Anti-Aliasing
I created an engine which draws 2D planes in the Stage3D API in Actionscript 3. And my question is, how do I turn all anti-aliasing off, because when I scale it all the pixels get really blurry, and I'm trying to use pixel-art for this.

This is the code I use:

```
protected function setupShaders() {
        var vertexShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
        vertexShaderAssembler.assemble( Context3DProgramType.VERTEX,
                "dp4 op.x, va0, vc0 \n"+
                "dp4 op.y, va0, vc1 \n"+
                "mov op.z, vc2.z    \n"+
                "mov op.w, vc3.w    \n"+
                "mov v0, va1.xy     \n"+
                "mov v0.z, va0.z    \n");

        var fragmentShaderAssembler:AGALMiniAssembler = new AGALMiniAssembler();
        fragmentShaderAssembler.assemble( Context3DProgramType.FRAGMENT,
                "tex ft0, v0, fs0 <2d,clamp,linear, nomip>\n"+
                "mov oc, ft0 \n");

        shader = context3D.createProgram();
        shader.upload(vertexShaderAssembler.agalcode, fragmentShaderAssembler.agalcode);
    }

public function draw() {

        context3D.setProgram(shader);
        context3D.setBlendFactors(Context3DBlendFactor.ONE, Context3DBlendFactor.ONE_MINUS_SOURCE_ALPHA);
        context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0, parent.modelViewMatrix, true);
        context3D.setTextureAt(0, sprites.texture);

        if (updateVBOs) {
            vertexBuffer = context3D.createVertexBuffer(vertices.length / 3,3);
            indexBuffer = context3D.createIndexBuffer(indices.length);
            uvBuffer = context3D.createVertexBuffer(UVs.length >> 1, 2);
            indexBuffer.uploadFromVector(indices, 0, indices.length);
            uvBuffer.uploadFromVector(UVs, 0, UVs.length >>1);
            updateVBOs = false;
        }

        vertexBuffer.uploadFromVector(vertices, 0, vertices.length / 3);
        context3D.setVertexBufferAt(0, vertexBuffer, 0, Context3DVertexBufferFormat.FLOAT_3);
        context3D.setVertexBufferAt(1, uvBuffer, 0,  Context3DVertexBufferFormat.FLOAT_2);

        context3D.drawTriangles(indexBuffer, 0, nChildren << 1);
    }

public function configureBackBuffer(width:uint, height:uint) {
        context3D.configureBackBuffer( width, height, 0, false);
    }

```

# Answer
> 0 votes
I found the answer, instead of `"tex ft0, v0, fs0 <2d, clamp, linear, nomip>\n"` I had to do `"tex ft0, v0, fs0 <2d, clamp, nearest, nomip>\n"`

---
Tags: actionscript-3, agal
---


# Question
Title: Should the frame rate be consistent or is it normal for it to jump around?
As I commented on a post, I started wondering if it was correct or not (the comment, not the answer). And I'd like to straighten that out.

Although not needed as info, here's the link to the question: Scene management for 3D editor

My comment: "Wouldn't mind that much about the framerate, as long as it stays above 60. you can get away with 30 even."

Still I think if the frame rate is over 30, the real time rendering stays as a good animation. But sometimes I read that people restrict the render() to 60fps or 30fps for performance. This could/would remove all unneccecary calculation wich we can't see anyway. Although true, they (sometimes) claim it is an optimization.

When a scene will render more objects, the fps will drop. Think that is normal.

So what's the deal with fps, should it stay more or less the same even when you turn the camera 90 or 180 degrees, or only when keeping (almost) the same view?

# Answer
The comment is both right and wrong at the same time. Framerate is very important to a well polished product. You don't want the player to suddenly pop into a view where their framerate tanks.

Having said that, when a game is being developed, there normally is a specific hardware level that is being designed to - ie, the minimum spec that is expected for the game be run on - and you should be looking for a minimum framerate on *that* environment. If it is higher on bigger machines, great - but never drop below your expected framerate on *that* built. That minimum framerate is normally 24 (which is what the human eye can pick up) - but that is also not quite true. While the human eye does work on around 24 "frames" per second, switching from a white to black screen is noticed, so the smoother you can make the transition, the better it will look to the viewer.

When it comes down to framerate and you are seeing a drop in a particular scene, the *real* question to ask is "Is the drop in framerate here worth what the player is seeing?". So, if you are playing a 1st person shooter and the center of a level drops in framerate by 20 fps, but the center of the level is a gorgeous view to an amazing model that will no doubt make the player oogle over, it might be worth it. If you can limit what they see by occluding certain parts of it, then it might be better. If you can reduce the poly size of the model so that it is still as visually appealing as before, but it doesn't tank fps, then even better.

tl;dr fps is always a tradeoff between how good something looks and how quickly you can render the environment.
> 0 votes

---
Tags: rendering
---


title: Creating 2D waveform for Cocos2d game

text:
# Question
Title: Creating 2D waveform for Cocos2d game
I'd like to have a Waveform in my iPhone game that I am developing using Cocos2d v2.0.

That's the ideal wave I'd like to achieve. A simpler wave which I would still be happy with is this one.

Some people suggested me to use ParticleEffects ands ParticleDesigners like 71squared but I am not sure that this is the right approach.

Brainstorming, I think that at the end a wave is a plot of some function, and at each frame translate the wave points that where from the origin apart (-x and +x) and computes new wave points for the origin.

Something like this:

```
for (duration of effect)
compute wave point intensity at origin and display it
and
for each wave point before the center translate to -x and display it
and after the center translate to +x and display it

```

Let me know what you think and if you have any better solution. I was thinking to achieve the display point by colouring a particular pixel but I need to figure out how :)..

# Answer
> 0 votes
I asked the question also on the cocos2d-iphone forum and someone kindly replied. I thought I would share his answer to avoid duplicate effort:

Answer

I haven't yet tried them because I am struggling deciding what to learn first ES 1.0 vs ES 2.0 as I have just migrated my code to Cocos2d v2.0 and I don't fully understand all the implications, but judging Apple's AurioTouch example posted in the answer it looks promising.

# Answer
> 2 votes
One way would be to read as binary and parse from that.

for example: (Assuming you have a 8Bit wav file)

```
//Get your file
Load wav into buffer
for each 8 bit chunk convert to unsigned Integer
  add to array.

//Generate image
for each Integer scale it down to half your image size
  draw pixel wide line from center to top from scaled result.
  Draw a mirror image of that line directly below.
  X coord + 1

//Add prettiness.
Create gradient starting from center out like your image
Use generated image as mask to only expose the pixels you want to see.

```

That should give you the result you wanted, Unfortunatly I can't post code as I have little understanding of Objective C. Maybe pseudo helps tho :)

---
Tags: iphone, cocos2d-iphone, graphic-effects, particles
---


title: Lighting problems with Terrain

text:
# Question
Title: Lighting problems with Terrain
I'm in the process of learning Open GL and am having issues with lighting on my Terrian, I don't know if the issue is related to how I calculate my normals or the shader itself (I am using the shader from the Open GL wikibook - Lighting Arc tutorial 1). I calculate the normals like this:

```
void Terrian::construct_normals()  {
    terrian_normals.reserve(width * height);

    for (int i = 0; i < terrian_elements.size() / 3; i++)  {
         int index1 = terrian_elements.at(i * 3);
         int index2 = terrian_elements.at(i * 3 + 1);
         int index3 = terrian_elements.at(i * 3 + 2);

         glm::vec3 side1 = terrian_vertices.at(index1) - terrian_vertices.at(index3);
         glm::vec3 side2 = terrian_vertices.at(index1) - terrian_vertices.at(index2);
         glm::vec3 normal = glm::cross(side1, side2);
         normal = glm::normalize(normal);

         terrian_normals.emplace_back(normal);
         terrian_normals.emplace_back(normal);
         terrian_normals.emplace_back(normal);
    }

    std::cout << "Terrian Vertices: " << terrian_vertices.size() << "\nTerrian Normals: " << terrian_normals.size();
}

```

And the vertex shader can be viewed here:

```
http://pastebin.com/3vU8SHvK

```

Here's what the terrain looks like:

If you would like me to post any more of my code I would be happy to do so.

**Edit:**

Vertices:

```
void Terrian::construct_vertices()  {
    terrian_vertices.reserve(width * height);
    terrian_colors.reserve(width * height);

    std::cout << "Generating data\n";

    for (int y = 0; y < height; y++)  {
        for (int x = 0; x < width; x++)  {
            int i = x + y * width;

            terrian_vertices.emplace_back(glm::vec3(x, terrian_heightmap[y][x], -y));
            terrian_colors.emplace_back(Color(0.0, 1.0, 0.0, true));
        }
    }
}

```

and elements:

```
void Terrian::construct_elements()  {
    terrian_elements.reserve((width - 1) * (height - 1) * 6);

    for (int y = 0; y < height - 1; y++)  {
        for (int x = 0; x < width - 1; x++)  {
            GLushort bottom_left = x + y * width;
            GLushort bottom_right = (x + 1) + y * width;
            GLushort top_left = x + (y + 1) * width;
            GLushort top_right = (x + 1) + (y + 1) * width;

            terrian_elements.emplace_back(top_left);
            terrian_elements.emplace_back(bottom_right);
            terrian_elements.emplace_back(bottom_left);

            terrian_elements.emplace_back(top_left);
            terrian_elements.emplace_back(top_right);
            terrian_elements.emplace_back(bottom_right);
        }
    }
}

```

# Answer
> 2 votes
Try this instead:

```
void Terrian::construct_normals()  {
    terrian_normals.resize(width * height, glm::vec3(0.f)); // Resize and initialize to zero

    for (int i = 0; i < terrian_elements.size() / 3; i++)  {
         int index1 = terrian_elements.at(i * 3);
         int index2 = terrian_elements.at(i * 3 + 1);
         int index3 = terrian_elements.at(i * 3 + 2);

         glm::vec3 side1 = terrian_vertices.at(index1) - terrian_vertices.at(index3);
         glm::vec3 side2 = terrian_vertices.at(index1) - terrian_vertices.at(index2);
         glm::vec3 normal = glm::cross(side1, side2);
         normal = glm::normalize(normal); // <- this is optional

         // accumulate normals for each triangle
         terrian_normals.at(index1) += normal;
         terrian_normals.at(index2) += normal;
         terrian_normals.at(index3) += normal;
    }

    // normalize all the accumulated normals
    for (std::size_t i=0; i<terrian_normals.size(); ++i)
        terrian_normals[i]=glm::normalize(terrian_normals[i]);

    std::cout << "Terrian Vertices: " << terrian_vertices.size() << "\nTerrian Normals: " << terrian_normals.size();
}

```

This code generates point normals by "averaging" the triangle normals of the adjacent triangles. I assumed this is what you wanted anyways. Note that this is an arbitrary method to generate point normals. Strictly speaking, points to not have normals. But for lighting, it is usually fine to generate them like this - it "fakes" a smoother surface. I normally leave out the normalization of the triangle normals - it biases the final normals to the directions with greater surface (on a terrain, these would be the slopes). Just experiment with it a little.

Alternatively, you can also derive the normals by constructing partial derivatives of your heightmap. This is a lot faster, but needs special treatment on the broders.

# Answer
> 4 votes
I assume you are using glDrawElements, and not the (deprecated) glVertex\* functions. Then you have to decide, if

* you want to have 1 normal per vertex, which means you have to average the normals of all faces adjacent to the vertex, or
* you want to have 3 normals per triangle, which means you have to duplicate the vertices and store 3 normals for each face.

Currently your code looks like a mixture of both. You're adding 3 normals per terrain triangle, but your terrian\_normals.reserve() call only allocates one normal for each vertex. I suspect your terrian\_vertices and terrian\_normals arrays have different size, and you're not properly aligning vertices with their normals during rendering.

---
Tags: c++, opengl, shaders, glsl, lighting
---


# Question
Title: Problem with position for player and 2D camera
I'm not sure I understand how the Matrix class for a 2D camera works in XNA. I have a Player object that I'm trying to position in the middle of the screen and then I have the Camera object that I want to follow the Player. But The position of the player is at the top left corner!?

Preciate som help to understand and to improve my code.

Game1.cs

```
player = new Player(texturePlayer, new Vector2(screenSizeX / 2, screenSizeY / 2));

```

And in the Update method:

```
camera.Position = player.PlayerPosition;

```

The Camera class:

```
    class Camera
{
    public Vector2 Position { get; set; }
    private Viewport viewPort;

    // Konstruktor
    public Camera(Viewport viewPort)
    {
        this.viewPort = viewPort;
        Position = Vector2.Zero;
    }
    public Matrix GetViewPortMatrix()
    {
        return Matrix.CreateTranslation(new Vector3(-Position, 0f));
    }
}

```

I guess there is no need to calcualte an origin for the Matrix when the camera isn't going to rotate!?

And finally some part of the Player class. Note that I'm using a "timer" to achieve a movement of the player in steps. Is this OK or is there a better way to achieve this?

```
    class Player:GameObjects
{
    //public Vector2 Position { get { return position; } }

    private int walkingSpeed = 60;
    private float walkingTimer = 100;
    private float milliSeconds1;

    // Konstruktor
    public Player(Texture2D texture, Vector2 position) : base(texture, position)
    {
    }

    public void Update(GameTime gameTime)
    {
        milliSeconds1 += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
    }

    public Vector2 PlayerPosition
    {
        get
        {
            return position;
        }
        set
        {
            position = value;
        }
    }

    public void Up()
    {
        if (milliSeconds1 >= walkingTimer)
        {
            if(position.Y > 60)
                position.Y -= walkingSpeed;

            milliSeconds1 = 0;
        }
    }

    public void Down()
    {
        if (milliSeconds1 >= walkingTimer)
        {
            if(position.Y < 630)
                position.Y += walkingSpeed;

            milliSeconds1 = 0;
        }
    }

```

# Answer
Since you're not setting an origin in your camera class, the origin ends up being the top left corner of the screen instead of the center of the screen.

Without changing anything else, the easiest solution would be to change the assignment to:

```
camera.Position = player.PlayerPosition - new Vector2(screenSizeX/2f, screenSizeY/2f);

```

Otherwise, add the origin translation to the camera class, so that you don't need to compensate outside.
> 1 votes

---
Tags: xna
---


title: Child parent rendering (flash) in XNA

text:
# Question
Title: Child parent rendering (flash) in XNA
i am currently in the process of implementing a render engine that works like flash's. Where a sprite is drawn inside another sprite and reflects all transformation (rotation, scale, etc) on the parent.

I have my transformation setup like so.

```
    public Matrix transform
    {
        get
        {
            Matrix m_transform =
                Matrix.CreateTranslation(new Vector3(x, y, z)) *
                Matrix.CreateRotationZ(rotation) *
                Matrix.CreateScale(scale)
                ;
            return m_transform;
        }

    }

```

But i cannot use spritebatch to render the sprite with a matrix. Is there a way to properly do this ?

Thanks alot ;)

# Answer
> 0 votes
Use the following helper method which decomposes any `Matrix` into a set of `position`, `rotation` and `scale` that can be used directly with a `SpriteBatch`. It's basically a wrapper around the existing `Matrix.Decompose` method but making it `SpriteBatch` friendly:

```
public static void DecomposeMatrix(ref Matrix matrix, out Vector2 position, out float rotation, out Vector2 scale)
{
    Vector3 position3, scale3;
    Quaternion rotationQ;
    matrix.Decompose(out scale3, out rotationQ, out position3);
    Vector2 direction = Vector2.Transform(Vector2.UnitX, rotationQ);
    rotation = (float) Math.Atan2(direction.Y, direction.X);
    position = new Vector2(position3.X, position3.Y);
    scale = new Vector2(scale3.X, scale3.Y);
}

```

It should be pretty straightforward, but here's an example of how to use the method above:

```
Matrix transform = /* The transform of your sprite */

Vector2 position, scale;
float rotation;
DecomposeMatrix(ref transform, out position, out rotation, out scale);

spriteBatch.Draw(texture, position, null, Color.White, rotation, Vector2.Zero, scale, SpriteEffects.None, 0.0f);

```

Notice how the `origin` parameter is left as `Vector2.Zero` in the example. This is because I usually already embed the origin transformation into the matrix, so the resulting `position` already includes it.

For more information on the subject of implementing a sprite hierarchy in XNA, I will simply leave two links to related answers of mine:

# Answer
> 0 votes
Shawn Hargreaves write this Link article on his blog about it. Create BasicEffect instance, set transforms and draw:

```
spriteBatch.Begin(0, null, null, null, null, basicEffect);
//draw something
spriteBatch.End();

```

---
Tags: xna, c#, flash, rendering
---


title: Dealing with keyboard input

text:
# Question
Title: Dealing with keyboard input
In game design how should keyboard input be handled and why? Do i A: check the state of keys in the main loop each iteration? B: Read key down and key up events from the event queue.

Im using allegro 5 and using the event queue model atm, but ive seen the other method in some samples..

# Answer
> 1 votes
Either model will work, and it really ends up depending on the overall structure of your game. While I'm not familiar with allegro specifically, the model that I see most often is the queue model, with a system that looks something like this:

```
//Main game loop
while(running) {
     //Read in all the events from the queue
     while(eventQueue.hasNext()) { //While there are more events on the queue..
          Event e = eventQueue.pop(); //Get the event
          if(e.type == mouseClick) { //Check the event
               //Whatever logic here
          }
     }

     //Other game logic and rendering here
}

```

This code is obviously very non-specific, but I have seen similar work with SDL, SFML and allegro samples. The advantage this has is that it is easier to work with, at least in my opinion, when one does that have to deal with saving the state of each key.

# Answer
> 0 votes
If you use state based input, then you only are ever going to be able to process information available at exactly the time you run your logic iteration. This means if something happens between iterations, you will miss input.

With events, you can examine the timestamp and know exactly when something happened. You can know whether or not a key was actually held down during the entire time between iterations. But often that is irrelevant in terms of keyboard input. In many cases, you'll find that people do something like:

```
case ALLEGRO_EVENT_KEY_DOWN:
  if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
    input.left = true;
  break;

case ALLEGRO_EVENT_KEY_UP:
  if (event.keyboard.keycode == ALLEGRO_KEY_LEFT)
    input.left = false;
  break;

```

This gives you state based input, but you can mix it in with other event code such that you don't have two different ways to process data.

So basically, events are mandatory if you do not want to miss any input or if you need to know the "precise" time something occurred. Otherwise, state based is sufficient.

---
Tags: c++, keyboard, allegro
---


title: Why doesn't my MatrixStack class work?

text:
# Question
Title: Why doesn't my MatrixStack class work?
I've been trying to get openGLES2 to work on my Android device and this is starting to drive me insane. I've spent well over ten hours now trying to get this to work. I just don't understand anymore. What I want is the ordinary GL3.0/ES1.0 behaviour, there's a stack of modelview matrices and when I call a 'push' function, I get a duplicate to work with and any subsequent matrix operations happen in the local coordinate space.

Here's my MatrixStack class:

```
public class MatrixStack {
private String TAG = "MatrixStack";

public float[] mMatrix = new float[16];
public float[] vMatrix = new float[16];
public float[] pMatrix = new float[16];

public float[] mvMatrix = new float[16];
public float[] mvpMatrix = new float[16];

private Stack stack = new Stack();

public MatrixStack() {
}

public void push() {
/*if(stackM.empty() || stackV.empty()) {
    Log.d(TAG, "say wha? I'm empty.... ERROR ERROR");
} else {
    //mMatrixPrev = (float[]) stackM.peek();
    //vMatrixPrev = (float[]) stackV.peek();
}*/

float[] mvMatrixDupe = mvMatrix.clone();

stack.push(mvMatrixDupe);
}

public void pop() {
if(stack.empty()) {
    Log.d(TAG, "Can't pop this empty stack...");
} else {
    mvMatrix = (float[]) stack.pop();
}
}

public void loadIdentity() {
Matrix.setIdentityM(mvMatrix, 0);

}

public void setProjection(float[] pMatrix) {
this.pMatrix = pMatrix;
}

public void translate(float x, float y, float z) {
Matrix.translateM(mvMatrix, 0, x, y, z);
}

public float[] getM() {
return mMatrix;
}

public float[] getV() {
return vMatrix;
}

public float[] getMV() {
return mvMatrix;
}

public float[] getMVP() {
Matrix.multiplyMM(mvpMatrix, 0, pMatrix, 0, mvMatrix, 0);

return mvpMatrix;
}

```

}

Here's the renderer:

```
public class MyGLRenderer implements GLSurfaceView.Renderer {
public static final String TAG = "MyGLRenderer";

private MatrixStack matrixStack = new MatrixStack();
private World world;
private float[] mVMatrix = new float[16];
private float[] mMVPMatrix = new float[16];
private float[] mProjMatrix = new float[16];
private float[] mMMatrix= new float[16];
private float[] mMVMatrix = new float[16];
private float[] mRotationMatrix = new float[16];

private volatile double dt;
private volatile double endTime; //for working out the dt

public void sendWorld(World targetworld) {
world = targetworld;
}
public void onSurfaceCreated(GL10 unused, EGLConfig config) {
    GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
GLES20.glDisable(GLES20.GL_DEPTH_TEST);
GLES20.glDepthMask(false);

world.init();
}

public void onDrawFrame(GL10 unused) {
if(world != null) {
    dt = System.currentTimeMillis() - endTime;

    world.update( (float) dt);

    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    matrixStack.setProjection(mProjMatrix);

    matrixStack.loadIdentity();

    matrixStack.translate(0.f, 0.f, -3.f);

    world.draw(matrixStack);
        endTime = System.currentTimeMillis();
} else {
    Log.d("Quad", "There is no world....");
}
}

public void onSurfaceChanged(GL10 unused, int width, int height) {
    GLES20.glViewport(0, 0, width, height);

float ratio = (float) width / height;

Matrix.frustumM(mProjMatrix, 0, -ratio, ratio, -1, 1, 1, 4);

//Matrix.orthoM(mProjMatrix, 0, 0, width, 0, height, -1.f, 1.f);
}

public static int loadShader(int type, String shaderCode){

int shader = GLES20.glCreateShader(type);

GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);

return shader;
}

```

}

And here's the quad class (with embedded shaders):

```
class Quad {
private String TAG = "Quad";

private FloatBuffer vertexBuffer;
private ShortBuffer indicesBuffer;
private float height;
private float width;
public float xPos = 0;
public float yPos = 0;
public float zPos = 0;
private float xVel = 0;
private float yVel = 0;
private float xAcc = 0;
private float yAcc = 0;
private int mProgram;
private int posAttr;
private int texAttr;
private int mMVMatrixHandle;
private int mPMatrixHandle;

private final String vertexShaderCode =
"attribute vec4 vPosition;" +
"uniform mat4 uMVMatrix;" +
"uniform mat4 uPMatrix;" +
"void main() {" +
"  gl_Position = uPMatrix * uMVMatrix * vPosition;" +
"}";

private final String fragmentShaderCode =
"precision mediump float;" +
"uniform vec4 vColor;" +
"void main() {" +
"  gl_FragColor = vColor;" +
"}";

static final int COORDS_PER_VERTEX = 3;

private final int vertexCount = quadCoords.length / COORDS_PER_VERTEX;
private final int vertexStride = COORDS_PER_VERTEX * 4; // bytes per vertex

static float quadCoords[] = {
-0.5f,  0.5f, 0.0f,   // top left
-0.5f, -0.5f, 0.0f,   // bottom left
 0.5f, -0.5f, 0.0f,   // bottom right
 0.5f,  0.5f, 0.0f  // top right
};

private short indices[] = {1, 0, 2, 3};

float color[] = {
0.0f, 0.0f, 1.0f, 1.0f
};

public Quad() {
ByteBuffer vbb = ByteBuffer.allocateDirect(quadCoords.length * 4); //each float is four bytes
vbb.order(ByteOrder.nativeOrder());
vertexBuffer = vbb.asFloatBuffer();
vertexBuffer.put(quadCoords);
vertexBuffer.position(0);

ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2); //shorts are just two bytes!!!
ibb.order(ByteOrder.nativeOrder());
indicesBuffer = ibb.asShortBuffer();
indicesBuffer.put(indices);
indicesBuffer.position(0);

int vertexShader = MyGLRenderer.loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
int fragmentShader = MyGLRenderer.loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

mProgram = GLES20.glCreateProgram();             // create empty OpenGL ES Program
GLES20.glAttachShader(mProgram, vertexShader);   // add the vertex shader to program
GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment shader to program
GLES20.glLinkProgram(mProgram);                  // creates OpenGL ES program executables
}

public void setXVel(float xVel) {
this.xVel = xVel;
}

public void setYVel(float yVel) {
this.yVel = yVel;
}

public void setXAcc(float xAcc) {
this.xAcc = xAcc;
}

public void setYAcc(float yAcc) {
this.yAcc = yAcc;
}

public void update(float dt) {
xVel += xAcc * dt;
yVel += yAcc * dt;

xPos += xVel;
yPos += yVel;
}

public void draw(MatrixStack stack) {
stack.push();

stack.loadIdentity();

stack.translate(xPos, yPos, zPos);

GLES20.glUseProgram(mProgram);

posAttr = GLES20.glGetAttribLocation(mProgram, "vPosition");
texAttr = GLES20.glGetUniformLocation(mProgram, "vColor");

GLES20.glVertexAttribPointer(posAttr, COORDS_PER_VERTEX, GLES20.GL_FLOAT, false, 0, vertexBuffer);

GLES20.glEnableVertexAttribArray(posAttr);

GLES20.glUniform4f(texAttr, 0.0f, 0.0f, 1.0f, 1.0f);

mMVMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uMVMatrix");
mPMatrixHandle = GLES20.glGetUniformLocation(mProgram, "uPMatrix");

GLES20.glUniformMatrix4fv(mMVMatrixHandle, 1, false, stack.getMV(), 0);
GLES20.glUniformMatrix4fv(mPMatrixHandle, 1, false, stack.pMatrix, 0);

GLES20.glDrawElements(GLES20.GL_TRIANGLE_STRIP, 4, GLES20.GL_UNSIGNED_SHORT, indicesBuffer);

GLES20.glDisableVertexAttribArray(posAttr);

stack.pop();
}

```

}

When I render, whatever the hell I do, that Matrix.translateM resets the mv matrix and draws to world coordinates, not a local system, regardless of what it pops back to.

How is this supposed to work? I've everything I can find on the web, every tutorial and even trawled open game engine source code, to no avail. Could anyone help? Just some pseudocode on how that MatrixStack is supposed to work to replicate the one in openGL3+ES1.

Thanks.

# Answer
Don't try to replicate stacks of matrices, you're wasting 10 hours on debugging a matrix stack class rather than learning the 'new' way ;-) Find a decent matrix & vector library that supports useful functions (dot product, cross product, translation, rotation, etc) - the Internet is full of them, Google will give you loads.

Then, consider splitting your world/whatever into objects and give each object its own matrix. This will define the object's local transformations.

Make a simple tree so that objects can have children. Give each one a way to pass its object matrix into its children. Have a 'head' node that defines the overall transformation.

The gradual multiplication of these matrices through the tree builds the modelview matrices for each object automatically. No messy pushing or popping required.

Every object's position and orientation will be defined in relation to its parent object (so make children as appropriate).

In short, forget the matrix stack idea and find some tutorials that lead you through GLES2. It's quite difficult to understand, so find as many different tutorials as you can (include ones related to iOS OpenGL ES, it's the same GL).
> 4 votes

---
Tags: opengl, matrix
---


# Question
Title: Parallelizing creation of geometry chunks in minecraft-like game
In my game I separate creation of chunks into two stages. The first is where I generate the heightmap using simplex noise and the 2nd is when I create the actual vertex buffers. I do it like this so that when creating the geometry I can always look at neighboring chunks so I can do decide things like visibility of faces.

Right now I'm working on loading chunks in the background. My first attempt was to create a simple job queue and just push all of the jobs for stage 1 first followed by all the jobs for stage 2. The problem then becomes a thread trying to start a job for the 2nd stage before all the necessary 1st stage jobs are done.

I suppose I could just have another worker thread that waits for all the 1st stage jobs to finish but that seems less than ideal. It also means I can't do anything clever like starting a stage 2 chunk job after that chunk and all surrounding chunks have gone through stage 1 instead of just waiting for *all* pending chunks to have gone through stage 1.

What is the correct system to use when dealing with dependencies of this kind?

# Answer
> 2 votes
Every time you retire a stage 1 job, figure out which neighboring stage 2 jobs now have their dependencies satisfied, and add them to the job queue at that point. That could be as simple as keeping a counter per chunk, starting at zero and maxing out at 6, incremented every time a neighbor completes stage 1.

If you have access to atomic add operations and the ability to add to the job queue from any thread, this would be pretty simple. If not, you need a single designated worker that is in charge of handling the completion of a stage 1 job, incrementing the counter for all its neighbors, and kicking a stage 2 job when a counter reaches its maximum.

---
Tags: procedural-generation, terrain, minecraft-modding, multithreading
---


# Question
Title: Getting width and height of view of game
well I have googled it and got some answers, asked many times, answered many times. as I read viewport is the "inside window" So I have 2 integers, height and width and this code:

```
        heightofwindow = graphicsDevice.Viewport.Bounds.Height;
        widtthofwindow = graphicsDevice.Viewport.Bounds.Width;

```

However, I get the error. It doesnt matter if I put it under update or draw. This seems like a more of language problem due to my limited knowlodge.

```
Object reference not set to an instance of an object.

```

# Answer
The graphics device manager is created in the game class constructor...

You should use the reference that provides the game instance to access to the GraphicsDevice

if you are inheriting from Game class... in your main class code you can use

```
this.GraphicsDevice.Bounds.Width/Height

```

if you are inheriting from GameComponent... in your component code you can use

```
this.Game.GraphicsDevice.Bounds.Width/Height

```
> 0 votes

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