title: Unity falling body pendulum behaviour

text:
# Question
Title: Unity falling body pendulum behaviour
I wonder if someone could provide some guidance.

Im attempting to create a pendulum like behaviour in 2D space in Unity without using a hinge joint.

Essentially I want to affect a falling body to act as though it were restrained at the radius of a point, and to be subject to gravity and friction etc.

Ive tried many modifications of this code, and have come up with some cool 'strange-attractor' like behaviour but i cannot for the life of me create a realistic pendulum like action.

This is what I have so far:

```
    startingposition = transform.position;          //Get start position
    newposition = startingposition + velocity;      //add old velocity
    newposition.y -= gravity * Time.deltaTime;      //add gravity
    newposition = pivot + Vector2.ClampMagnitude(newposition-pivot,radius); //clamp body at radius???
    velocity = newposition-startingposition;        //Get new velocity
    transform.Translate (velocity * Time.deltaTime, Space.World);   //apply to transform

```

So im working out the new position based on the old velocity + gravity, then constraining it to a distance from a point, which is the element in the code i cannot get correct. Is this a logical way to go about it?

# Answer
> 20 votes
I thought this would be a relatively simple problem to solve but I spent a couple days trying to figure out how the heck to simulate pendulum movement. I didn't want to cheat and just change the x,y position based on sin(theta) and cos(theta) curves. Instead I wanted to deal with the two forces that are applied in real life, **Gravity** and **Tension**. The main piece I was missing was centripetal force.

The Pendulum (mathematics) wikipedia page has a great animation(below, on left) explaining the pendulum motion. You can see my result(on right) strikingly similar to that diagram

The "bob" is the swinging object and the "pivot" is the origin/root.

I also found this article and diagram(below) pretty helpful:

---

`Theta` equals the angle between the rope and the direction of gravity.

When the bob is on the left or right the tension equals:

The reason the tension force is greater as the bob approaches equilibrium point(middle) is because of centripetal force:

So the overrall tension formula looks like as the bob swings is:

There are two forces in the pendulum system:

* Gravity
    + `GravityForce = mass * gravity.magnitude`
    + `GravityDirection = gravity.normalized`
* Tension
    + `TensionForce = (mass * gravity * Cos(theta)) + ((mass * velocityTangent^2)/ropeLength)`
    + `TensionDirection = ropeDirection = bob to pivot`

Just apply gravity to your object like you would for a normal object and then apply the tension. When you apply the forces, just multiply the force by the direction and deltaTime.

Below is the `Pendulum.cs` script(also as a GitHub Gist). It works quite well but there is some rounding error drift if you leave it for a while (doesn't return to exactly same position).

The script works in 3D but of course a pendulum only swings in a 2D plane. It also works with gravity in any direction. So for example, if you invert the gravity the pendulum works upside down. `Edit->Project Settings->Physics->Gravity`

It is very important to have a consistent relatively small deltaTime when updating the pendulum so that you do not bounce around the curve. I am using the technique found in this article, FIX YOUR TIMESTEP! by Glenn Fiedler to accomplish this. Check the `Update()` function below to see how I implemented it.

## Also as a GitHub Gist

```
using UnityEngine;
using System.Collections;

// Author: Eric Eastwood (ericeastwood.com)
//
// Description:
//      Written for this gd.se question: http://gamedev.stackexchange.com/a/75748/16587
//      Simulates/Emulates pendulum motion in code
//      Works in any 3D direction and with any force/direciton of gravity
//
// Demonstration: https://i.stack.imgur.com/izYdd.gif
//
// Usage: https://i.stack.imgur.com/HIr37.png
public class Pendulum : MonoBehaviour {

    public GameObject Pivot;
    public GameObject Bob;

    public float mass = 1f;

    float ropeLength = 2f;

    Vector3 bobStartingPosition;
    bool bobStartingPositionSet = false;

    // You could define these in the `PendulumUpdate()` loop
    // But we want them in the class scope so we can draw gizmos `OnDrawGizmos()`
    private Vector3 gravityDirection;
    private Vector3 tensionDirection;

    private Vector3 tangentDirection;
    private Vector3 pendulumSideDirection;

    private float tensionForce = 0f;
    private float gravityForce = 0f;

    // Keep track of the current velocity
    Vector3 currentVelocity = new Vector3();

    // We use these to smooth between values in certain framerate situations in the `Update()` loop
    Vector3 currentStatePosition;
    Vector3 previousStatePosition;

    // Use this for initialization
    void Start () {
        // Set the starting position for later use in the context menu reset methods
        this.bobStartingPosition = this.Bob.transform.position;
        this.bobStartingPositionSet = true;

        this.PendulumInit();
    }

    float t = 0f;
    float dt = 0.01f;
    float currentTime = 0f;
    float accumulator = 0f;

    void Update()
    {
        /* */
        // Fixed deltaTime rendering at any speed with smoothing
        // Technique: http://gafferongames.com/game-physics/fix-your-timestep/
        float frameTime = Time.time - currentTime;
        this.currentTime = Time.time;

        this.accumulator += frameTime;

        while (this.accumulator >= this.dt)
        {
            this.previousStatePosition = this.currentStatePosition;
            this.currentStatePosition = this.PendulumUpdate(this.currentStatePosition, this.dt);
            //integrate(state, this.t, this.dt);
            accumulator -= this.dt;
            this.t += this.dt;
        }

        float alpha = this.accumulator/this.dt;

        Vector3 newPosition = this.currentStatePosition*alpha + this.previousStatePosition*(1f-alpha);

        this.Bob.transform.position = newPosition; //this.currentStatePosition;
        /* */

        //this.Bob.transform.position = this.PendulumUpdate(this.Bob.transform.position, Time.deltaTime);
    }

    // Use this to reset forces and go back to the starting position
    [ContextMenu("Reset Pendulum Position")]
    void ResetPendulumPosition()
    {
        if(this.bobStartingPositionSet)
            this.MoveBob(this.bobStartingPosition);
        else
            this.PendulumInit();
    }

    // Use this to reset any built up forces
    [ContextMenu("Reset Pendulum Forces")]
    void ResetPendulumForces()
    {
        this.currentVelocity = Vector3.zero;

        // Set the transition state
        this.currentStatePosition = this.Bob.transform.position;
    }

    void PendulumInit()
    {
        // Get the initial rope length from how far away the bob is now
        this.ropeLength = Vector3.Distance(Pivot.transform.position, Bob.transform.position);
        this.ResetPendulumForces();
    }

    void MoveBob(Vector3 resetBobPosition)
    {
        // Put the bob back in the place we first saw it at in `Start()`
        this.Bob.transform.position = resetBobPosition;

        // Set the transition state
        this.currentStatePosition = resetBobPosition;
    }

    Vector3 PendulumUpdate(Vector3 currentStatePosition, float deltaTime)
    {
        // Add gravity free fall
        this.gravityForce = this.mass * Physics.gravity.magnitude;
        this.gravityDirection = Physics.gravity.normalized;
        this.currentVelocity += this.gravityDirection * this.gravityForce * deltaTime;

        Vector3 pivot_p = this.Pivot.transform.position;
        Vector3 bob_p = this.currentStatePosition;

        Vector3 auxiliaryMovementDelta = this.currentVelocity * deltaTime;
        float distanceAfterGravity = Vector3.Distance(pivot_p, bob_p + auxiliaryMovementDelta);

        // If at the end of the rope
        if(distanceAfterGravity > this.ropeLength || Mathf.Approximately(distanceAfterGravity, this.ropeLength))
        {

            this.tensionDirection = (pivot_p - bob_p).normalized;

            this.pendulumSideDirection = (Quaternion.Euler(0f, 90f, 0f) * this.tensionDirection);
            this.pendulumSideDirection.Scale(new Vector3(1f, 0f, 1f));
            this.pendulumSideDirection.Normalize();

            this.tangentDirection = (-1f * Vector3.Cross(this.tensionDirection, this.pendulumSideDirection)).normalized;

            float inclinationAngle = Vector3.Angle(bob_p-pivot_p, this.gravityDirection);

            this.tensionForce = this.mass * Physics.gravity.magnitude * Mathf.Cos(Mathf.Deg2Rad * inclinationAngle);
            float centripetalForce = ((this.mass * Mathf.Pow(this.currentVelocity.magnitude, 2))/this.ropeLength);
            this.tensionForce += centripetalForce;

            this.currentVelocity += this.tensionDirection * this.tensionForce * deltaTime;
        }

        // Get the movement delta
        Vector3 movementDelta = Vector3.zero;
        movementDelta += this.currentVelocity * deltaTime;

        //return currentStatePosition + movementDelta;

        float distance = Vector3.Distance(pivot_p, currentStatePosition + movementDelta);
        return this.GetPointOnLine(pivot_p, currentStatePosition + movementDelta, distance <= this.ropeLength ? distance : this.ropeLength);
    }

    Vector3 GetPointOnLine(Vector3 start, Vector3 end, float distanceFromStart)
    {
        return start + (distanceFromStart * Vector3.Normalize(end - start));
    }

    void OnDrawGizmos()
    {
        // purple
        Gizmos.color = new Color(.5f, 0f, .5f);
        Gizmos.DrawWireSphere(this.Pivot.transform.position, this.ropeLength);

        Gizmos.DrawWireCube(this.bobStartingPosition, new Vector3(.5f, .5f, .5f));

        // Blue: Auxilary
        Gizmos.color = new Color(.3f, .3f, 1f); // blue
        Vector3 auxVel = .3f * this.currentVelocity;
        Gizmos.DrawRay(this.Bob.transform.position, auxVel);
        Gizmos.DrawSphere(this.Bob.transform.position + auxVel, .2f);

        // Yellow: Gravity
        Gizmos.color = new Color(1f, 1f, .2f);
        Vector3 gravity = .3f * this.gravityForce*this.gravityDirection;
        Gizmos.DrawRay(this.Bob.transform.position, gravity);
        Gizmos.DrawSphere(this.Bob.transform.position + gravity, .2f);

        // Orange: Tension
        Gizmos.color = new Color(1f, .5f, .2f); // Orange
        Vector3 tension = .3f * this.tensionForce*this.tensionDirection;
        Gizmos.DrawRay(this.Bob.transform.position, tension);
        Gizmos.DrawSphere(this.Bob.transform.position + tension, .2f);

        // Red: Resultant
        Gizmos.color = new Color(1f, .3f, .3f); // red
        Vector3 resultant = gravity + tension;
        Gizmos.DrawRay(this.Bob.transform.position, resultant);
        Gizmos.DrawSphere(this.Bob.transform.position + resultant, .2f);

        /* * /
        // Green: Pendulum side direction
        Gizmos.color = new Color(.3f, 1f, .3f);
        Gizmos.DrawRay(this.Bob.transform.position, 3f*this.pendulumSideDirection);
        Gizmos.DrawSphere(this.Bob.transform.position + 3f*this.pendulumSideDirection, .2f);
        /* */

        /* * /
        // Cyan: tangent direction
        Gizmos.color = new Color(.2f, 1f, 1f); // cyan
        Gizmos.DrawRay(this.Bob.transform.position, 3f*this.tangentDirection);
        Gizmos.DrawSphere(this.Bob.transform.position + 3f*this.tangentDirection, .2f);
        /* */
    }
}

```

More glamour shots:

---
Tags: c#, 2d, unity, physics
---


title: OpenGL ES 1 Pixel Error?

text:
# Question
Title: OpenGL ES 1 Pixel Error?
I am developing a game on android using OpenGL ES 1.0 for Android OS. It is a 2d game using a simple Orthographic projection and textures for the sprites. One of these textures has a small line (it looks like 1 pixel) all the way across the top that has the same colors as the bottom 1-pixel line of the texture. It is almost as if the bottom line of the image raster was copied and pasted as the top line as well.

Is anyone familiar with this type of error? What could the problem be?

# Answer
> 1 votes
When this happens in my experience it's usually due to a combination of using texture wrapping/repeat and bilinear filtering. The bilinear filtering can sometimes sample from coordinates outside the 0-1 range and because it's set to repeat it will sample pixels from the other side of the image. Try using GL\_CLAMP\_TO\_EDGE (example of usage) to confirm this is the case.

There's a few different ways to fix it:

* Don't use wrapping
* Don't use bilinear filtering
* Add a row of transparent pixels at the bottom of the image.

---
Tags: opengl, android, graphics, opengl-es, graphics-programming
---


# Question
Title: How do I convert screen coordinates to between -1 and 1?
I'm writing a function that allows me to click on my tiles. The origin for my tiles is the center, however, the mouse's origin is the top left. I need a way to transform my mouse coordinates into my tile coordinates.

Here is what I already have (but is not working):

```
void mouseClick(int button, int state, int x, int y)
{
    x -= 400;
    y -= 300;
    float xx = x / 100; // This gets me close but the number is still high.
    float yy = y / 100; // It needs to be between -1 and 1
}

```

# Answer
> 6 votes
Your description is a bit vague, but it sounds like what you're trying to do is map coordinates from one space (the window coordinates) to another (your tile coordinate space). Doing so is a simple transformation using the window size:

```
x_trans = x - (windowWidth / 2);
y_trans = y - (windowHeight / 2);
x_norm = x / (windowWidth / 2);
y_norm = y / (windowHeight / 2);

```

`x_trans` and `y_trans` are the `x` and `y` coordinates of your mouse click transformed into the coordinate space where the center of the window is `0,0`. `x_norm` and `y_norm` are the "normalized" (normalized would ordinarily mean `[0,1]`) coordinates, in a `[-1,1]` range.

# Answer
> 2 votes
You need to know the width and height of the window. How to do this depends on your platform, but I will use "WindowWidth" and "WindowHeight" as placeholders.

```
void mouseClick(int button, int state, int x, int y)
{
    float xx = x / (WindowWidth / 2.0f);  // This will give a value from 0 - 2
    float yy = y / (WindowHeight / 2.0f);  // This will give a value from 0 - 2
    xx -= 1.0f; // Subtract 1 to get a value from -1 to 1.
    yy -= 1.0f; // Subtract 1 to get a value from -1 to 1.
}

```

---
Tags: mathematics, coordinates, projection, scale
---


title: What is "immediate mode" in LWJGL?

text:
# Question
Title: What is "immediate mode" in LWJGL?
I am not sure what "immediate mode" is in the context of LWJGL. I think it's when you use `gluPerspective()` function?

# Answer
> 2 votes
It refers to using OpenGL's direct (immediate) mode of rendering (the family of functions that includes `glBegin` and `glEnd` as well as all the immediate vertex attribute specification functions like `glVertex*` and `glColor*`).

Immediate mode functionality is deprecated in modern OpenGL/ If available, something like vertex buffer objects should be used instead.

`gluPerspective` is not an immediate-mode function, but it is a utility function that makes use of OpenGL's matrix stack, which is also deprecated.

---
Tags: java, lwjgl
---


# Question
Title: Why does my terrain turn white when I get close to it?
When I zoom in on my terrain it goes white: The further in I zoom, the greater the whiteness becomes. Is this normal? Is this to speed up rendering or something? Can I turn it off?

I'm also getting these error messages in the console over and over again:

> rc.right != m\_GfxWindow-\>GetWidth() || rc.bottom != m\_GfxWindow-\>GetHeight()

and

> GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly.

Does this bear any correlation on the issue?

**Update** I create virtual desktops to flit between using the program Deskpot. Turning this program off and restarting has stopped the above errors appearing in the console. However, I still get white terrain when I zoom in. Not a single error message.

I've restarted my computer to no avail.

I have an Asus NVidia GeForce GTX 760 2GB DDR5 Direct CU II OC Edition Graphics Card. Any known issues?

**Update** I don't think it's fog...

# Answer
> 3 votes
I fixed the error by deleting the terrain and creating brand new terrain. This wasn't some momentary glitch though; that weird terrain remained weird after a restart, even. Hopefully the problem won't came back.

Sadly I have no idea how one could salvage terrain they've worked hard on. My only theory is that Dexpot somehow corrupts something, and my only advice is to never use it and Unity at the same time.

Dexpot is lovely program and I don't want to give it ill-credit, but I'm 99% sure it was causing that

> GUI Window tries to begin rendering while something else has not finished rendering! Either you have a recursive OnGUI rendering, or previous OnGUI did not clean up properly.

error, and qutting Dexpot and recreating the terrain has solved the issue, so it does look like its the culprit. Hopefully I've nailed it.

# Answer
> 3 votes
Check your Fog settings in the Edit/Render Settings menu. If you set the Linear Fog Start higher than the Linear Fog End, you can get this type of effect.

Try turning off the Fog completely to see if the problem goes away.

I was able to reproduce your issue with fog:

---
Tags: unity
---


# Question
Title: Sphere-Sphere intersection and Circle-Sphere intersection
I have code for circle-circle intersection. But I need to expand it to 3-D. How do I calculate:

* Radius and center of the intersection circle of two spheres
* Points of the intersection of a sphere and a circle?

Given two spheres `(sc0,sr0)` and `(sc1,sr1)`, I need to calculate a circle of intersection whose center is `ci` and whose radius is `ri`.
Moreover, given a sphere `(sc0,sr0)` and a circle `(cc0, cr0)`, I need to calulate the two intersection points `(pi0, pi1)`
I have checked this link and this link, but I could not understand the logic behind them and how to code them.

I tried ProGAL library for sphere-sphere-sphere intersection, but the resulting coordinates are rounded. I need precise results.

# Answer
> 18 votes
## Sphere-Sphere Intersection

Let's start with the more obvious one - sphere-sphere. It's almost identical to the circle-circle case in 2D. We can project down on any plane containing the line between the spheres' centers to get an identical 2D picture:

Here the first sphere has center `c_1` and radius `r_1`, the second `c_2` and `r_2`, and their intersection has center `c_i` and radius `r_i`. Let `d = ||c_2 - c_1||`, the distance between the spheres.

**Edge Cases:**

As was pointed out previously, if `r_1 + r_2 < d` then there is no intersection at all. The spheres have a separation between them.

If `r_1 + r_2 == d`, then the intersection is a single point, located a distance of `r_1` on the line from `c_1` to `c_2`, or: `c_i = c_1 + (c_2 - c_1) * r_1/d`

This can also happen from the other side, if `d + min(r_1, r_2) = max(r_1, r_2)`. In this case, the single point of intersection lies on the larger sphere, at `c_i = c_larger + (c_smaller - c_larger) * r_larger/d`

Finally, if one circle is entirely encompassed within the other, such that `d + min(r_1, r_2) < max(r_1, r_2)`, then once again there is no intersection.

**Typical intersections**

Okay, now the meaty bit.

Let's define `c_i = c_1 + h * (c_2 - c_1)`, for some value of `h`. Note that `h` can be negative or greater than one in the case where one circle encompasses the center of the other. Fortunately, the signs will "just work," so we don't need to add any special case logic for this condition.

We can express `r_1` and `r_2` in terms of `r_i`, `h`, and `d` using Pythagorean Theorem, then solve the system of equations to find h:

$$\require{cancel} \begin{array}{r|l} (hd)^2 + r\_i^2 = r\_1^2 & \left((1-h)d\right)^2 + r\_i^2 = r\_2^2\\ h^2d^2 - r\_1^2 = -r\_i^2 & \left(1 - 2h + h^2 \right)d^2 - r\_2^2 = -r\_i^2 \end{array}\\ \begin{align} \cancel{h^2d^2} - r\_1^2 &= d^2 - 2hd^2 + \cancel{h^2d^2} - r\_2^2\\ 2hd^2 &= d^2 + r\_1^2 - r\_2^2\\ h &= \frac 1 2 + \frac {r\_1^2 - r\_2^2} {2 d^2} \end{align}$$

```
h = 1/2 + (r_1 * r_1 - r_2 * r_2)/(2 * d*d)

```

We can sub this into our formula for c\_i above to find the center of the circle of intersections. Then, reversing one of our earlier Pythagorean relations:

```
r_i = sqrt(r_1*r_1 - h*h*d*d)

```

So, now we have the center and radius of our intersection. Now we can revolve this around the separating axis to get our full circle of solutions. The circle lies in a plane perpendicular to the separating axis, so we can take `n_i = (c_2 - c_1)/d` as the normal of this plane.

After choosing a tangent and bitangent `t_i` and `b_i` perpendicular to this normal and each other, you can write any point on this circle as:

```
p_i(theta) = c_i + r_i * (t_i * cos(theta) + b_i sin(theta));

```

Because of the Hairy Ball Theorem, there's no one universal way to choose the tangent/bitangent to use. My recommendation would be to pick one of the coordinate axes not parallel to `n_i`, and set `t_i = normalize(cross(axis, n_i))`, and `b_i = cross(t_i, n_i)` or somesuch.

---

## Sphere-Circle Intersection

A circle, being flat/2-dimensional, can only intersect with things within its own plane. So, the first thing is: find out where that plane intersects our sphere.

Given a circle with center & radius `c_c` and `r_c`, respectively, in the plane with (unit) normal `n`, and a sphere with center & radius `c_s` and `r_s`...

The plane of the circle cuts the sphere `d = dot(n, c_c - c_s)` units from the sphere's center. Again, this can be negative if the normal is pointing toward the sphere's center, but the signs will work out.

If `abs(d) > r_s` then there is no intersection. Our plane passes above/below the sphere entirely.

If there is an intersection, it will be between our original circle and a new one formed where this plane meets the sphere, with center `c_p = c_s + d*n`.

If `d == r_s` then this is the sole point of intersection with the plane; otherwise we have a circle whose radius `r_p` we can find with Pythagorean Theorem:

```
r_p = sqrt(r_s*r_s - d*d)

```

And now we've reduced the problem to circle-circle, which we already know how to solve. Checking the distance/radii involved according to the edge cases above will let us take care of the non-intersecting and single point of intersection cases.

If the two circles do overlap by more than one point, we can use the formulae from the Sphere-Sphere check to find `c_i` and `r_i` as before.

Instead of a full circle of intersection points though, we'll have only the two points lying in the plane of the circle.

To express these points, we can define a tangent vector in the plane,

```
t = normalize(cross(c_p - c_c, n))

```

Then our intersection points are:

```
p_0 = c_i - t * r_i

p_1 = c_i + t * r_i

```

And we're done. :D

I hope that helps!

---
Tags: java, geometry, computational-geometry, sphere
---


# Question
Title: How do I change the relative origins of a Box2D World and a TiledMap in Libgdx?
I'm playing around with Box2D and TiledMaps and I've come across this minor annoyance.

As you can see, both Box2D and TiledMap render at the center of the screen. This forces me to compensate by adding `.5` to every item I spawn in the Box2D world, giving me some problems down the road.

How do I change the origin of these two things? Maybe it has something to do with the camera?

# Answer
> 1 votes
I use and extended OrthographicCamera to fix this.

```
package ferret.util;

import com.badlogic.gdx.graphics.OrthographicCamera;

/**
 * OrthographicCamera that cannot go beyond specified rectangle.
 */
public class BoundedCamera extends OrthographicCamera {

    private float xmin;
    private float xmax;
    private float ymin;
    private float ymax;

    public BoundedCamera() {
        this(0, 0, 0, 0);
    }

    public BoundedCamera(float xmin, float xmax, float ymin, float ymax) {
        super();
        setBounds(xmin, xmax, ymin, ymax);
    }

    public void setBounds(float xmin, float xmax, float ymin, float ymax) {
        this.xmin = xmin;
        this.xmax = xmax;
        this.ymin = ymin;
        this.ymax = ymax;
    }

    public void setPosition(float x, float y) {
        setPosition(x, y, 0);
    }

    public void setPosition(float x, float y, float z) {
        position.set(x, y, z);
        fixBounds();
    }

    private void fixBounds() {
        if(position.x < xmin + viewportWidth / 2) {
            position.x = xmin + viewportWidth / 2;
        }
        if(position.x > xmax - viewportWidth / 2) {
            position.x = xmax - viewportWidth / 2;
        }
        if(position.y < ymin + viewportHeight / 2) {
            position.y = ymin + viewportHeight / 2;
        }
        if(position.y > ymax - viewportHeight / 2) {
            position.y = ymax - viewportHeight / 2;
        }
    }

}

```

then in the Game Class or what ever you call it.

You do:

```
BoundedCamera cam = new BoundedCamera();
cam.setBounds(0, tileMapWidth * tileSize, 0, tileMapWidth * tileSize);

```

Then in your render method:

```
cam.setPosition(player.getPosition().x * SCREEN_WIDTH / 4, SCREEN_HEIGHT / 2);//Set this to your own liking.
cam.update();

tileMapRenderer.setView(cam);//Assuming your are using a tmxloader
tileMapRenderer.update();

spriteBatch.setProjectionMatrix(cam.combined);
player.render(spriteBatch);

```

One thing you gotta watch out for is, wether or not you are using "Pixels Per Meter" scaling. Then you should adjust accordingly.

**Requested EDIT:** This should work because you use the camera as draw origin. Everything x-y related which involves the SpriteBatch will be calculated from the camera if you do this properly.

# Answer
> 0 votes
I had similar problem with zoomed in rendering. I assume by "Box2D" render you mean Box2D debug renderer. Well, here is your problem. Before rendering debug data of Box2D, transform camera accordingly (add 0.5 or whatever, as you said) and after rendering Box2D debug stuff do the inverse transformation (subtract 0.5).

I hope I understood your problem and my suggestion will solve that ;)

# Answer
> 0 votes
I edited my camera matrix to convert the origin of libgdx and debugRenderer to lower left..

```
    static final float BOX_TO_WORLD = 100f;
        //onShow()

        camera.position.set(SCR_WIDTH / 2, SCR_HEIGHT / 2, 0);
        debugMatrix = new Matrix4(camera.combined);
        debugMatrix.translate((-SCR_WIDTH / 2), (-SCR_HEIGHT / 2), 0);
        debugMatrix.scale(BOX_TO_WORLD, BOX_TO_WORLD, 1f);
        debugRenderer = new Box2DDebugRenderer();
        //onRender(delta)

        batch.setProjectionMatrix(camera.combined);
        camera.update();
        World_Update(delta);
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        batch.begin();

        p1.draw(batch);
        p2.draw(batch);

        batch.end();
        debugRenderer.render(world, debugMatrix);

```

---
Tags: java, libgdx, box2d, camera, tilemap
---


# Question
Title: Creating blur with an alpha channel, incorrect inclusion of black
I'm trying to do a blur on a texture with an alpha channel. Using a typical approach (two-pass, gaussian weighting) I end up with a very dark blur. The reason is because the blurring does not properly account for the alpha channel. It happily blurs in the invisible part of the image, whcih happens to be black, and thus results in a very dark blur.

Is there a technique to blur that properly accounts for the alpha channel?

# Answer
Your problem is that you're blurring a texture which has had its alpha pre-multiplied into its color channels. That is, the rgba of a 100% transparent white pixel is stored as `{0,0,0,0}`, and the rgba color of a 50% transparent white pixel is `{0.5,0.5,0.5,0.5}`. Which means that when you're using that pixel as part of your blur, you're not blurring half-strength white; you're blurring half-strength 50% grey.

Which means that even when you correct for varying alpha levels, the source color of the pixels has *already* been darkened before your shader ever got there, and so you're still not getting the overall blur brightness level that you were expecting.

The simple answer is: don't use textures with pre-multiplied alpha; make sure that your 100% transparent white pixels are encoded as `{1,1,1,0}` instead of `{0,0,0,0}`. There are some plausible arguments for using pre-multiplied alpha in certain situations (mostly to do with simple compositing operations), but they really cause severe problems any time you want to do non-trivial processing on textures, such generating mipmaps, or such as performing the blur operation that you're doing.

The more complicated answer is: if you really want to keep using premultiplied textures, you can un-premultiply the pixel colors inside your fragment shader. Basically, you ignore any pixel with an alpha of 0, and any other pixel, you adjust its rgb color by multiplying by 1.0 / alpha. So in the case of a 50% transparent white pixel, which from your premultiplied alpha texture contains rgba of `{0.5,0.5,0.5,0.5}`, your blur shader multiplies the rgb values by `1.0 / alpha` == `1.0 / 0.5` == `2.0`, to recover the original pixel color from before the alpha premultiplication was applied -- `{1.0,1.0,1.0.0.5}`. You can then use that pixel color for the blurring calculation.

But really, you want to use the simple approach. It's much faster and easier and better in every way.
> 2 votes

---
Tags: algorithm, glsl
---


# Question
Title: Forcing Non-Pitch Preserving Audio in HTML5, Construct 2
I'm working on a simple game built in HTML5 using Construct 2, in which a circle eats other circles; nothing fancy. The idea is that a song plays during the game, starting at a low pitch, and rising as more circles get eaten (which along with increasing movement speed, makes it pretty manic). Construct 2 has a way to set the playback speed for audio tracks (using the .ogg or aac formats for browser support), but passes the actual implementation of setting the speed to the browser used.

Since some browsers use a pitch-preserving algorithm, and others do not, the same HTML5 game may have the desired low to high pitch transition in one browser, but a artifact filled pitch-preserving version in another. I was wondering, then, is there a way to force the playback speed of the audio to act equivalently to a pitch setting, regardless of the browser used?

# Answer
If you've not found a way, maybe an alternative could be to make low and high pitch versions of the song, but it may mean bigger file.
> 1 votes

---
Tags: html5, audio, construct-2
---


title: Will Unity skills be transferable?

text:
# Question
Title: Will Unity skills be transferable?
I'm currently learning Unity and working my way through a video game maths primer text book.

My goal is to create a racing game for WebGL (using Three.js and maybe Physic.js).

I'm well aware that the Unity program shields you from a lot of what's going on and a lot of the grunt work attached to developing even a simple video game, but if I power through a bunch of Unity tutorials, will a lot of the skills I learn translate over to other frameworks/engines?

I'm pretty proficient at level design with WebGL, and I'm a good 3D modeller. My weaknesses are definitely AI and Physics.

While I am rapidly shoring up my math, and while Physics is undeniably interesting there's only so many hours in the day and there's a wealth of engines out there to take care of this sort of thing.

AI does appeal to me a lot more, and is a lot more necessary. AI changes drastically from game to game, is tweaked heavily during development, and the physics is a lot more constant.

Will leaning AI concepts in Unity allow me to transfer this knowledge pretty much anywhere? Or will I just be paddling up Unity creek with these skills?

# Answer
Speaking very broadly, there are two sorts of skills:

1. **"I can make this thing shiny by clicking that button."** This is Unity-domain knowledge; it's something you've learned about how to use Unity, and probably won't help you much when learning another system's interface. (While that other system is likely to have some way to make an object shiny, it will probably have a completely different system for configuring that appearance -- learning Unity's way won't automatically teach you the other system's way)
2. **"If I want to be sure that the player notices this object, I can make it shiny."** This is game-domain knowledge; it's something you've learned about how games work, and how players interact with games, independent from how any particular engine or SDK implements things.

If you're learning algorithms, or if you're learning when and why particular techniques should be used, then you're building highly transferable skills which are relevant to all games. If you're just learning how to manipulate an engine's interface, then you're probably building less-transferable skills.
> 27 votes

# Answer
Yes. Learning algorithms is learning algorithms. Implementations may change, but you'll still understand the overall strategy.

However, it's also true that you'll be learning at a high level of abstraction. That means that moving around to other engines, or no engine, may require you to learn the finer details of the algorithm and the gritty details of the implementation.

Overall, it's always a good strategy to learn new things. Even if if only improves your general understanding of the topic, it makes learning and implementing it again on a different technology that much easier.
> 7 votes

# Answer
**It depends.**

There are aspects some aspects that can carry over, like the ability to design a coherent game that works. But that comes from learning to use any game engine/SDK.

But it all depends on:

-Your level of use If you're borrowing scripts and only know for the most part things that are visual, its likely that the only thing will carry over is familiarity with some of the tools.

-The software you've built up some sort of background in vs the new software Going from something like GameMaker to something like CryEngine, UDK, Unity doesn't really go well unless:

-You have background in various programming languages Unity uses Unityscript which is their own bastardization of C# and java

If you are new, like you seemed to have indicate, then I would start with the basic with GameMaker. Get familiar with the drag and drop interface and very basic gameplay programming, then learn how to write your own scripts with their GameMaker Language. Meanwhile, start learning programming languages (java,C,C++,C#,...etc), the concepts from which will be incredibly useful for when you start to learn the first party engine language.

If AI's is what you are really interested in, then **cannot stress enough** how important it is to learn programming languages, and **the logic behind them.** AI's are tough, really tough, and there is a lot that is involved in writing the scripts for them. That being said, those concepts behind the writing of good AI's should carry on, but not necessarily the exact methods of doing so, since every game engine/SDK is different.

I know you probably don't want to hear this, and I am in no way trying to discourage you whatsoever. But you have a long road ahead of you. Outside looking in, studying game design sounds like it would be a lot of fun, and sometimes it is, but there is a lot to know, and even more work to be done.

I hope this helps steer you in the right direction.

Source: Video Game Design/Programming Student with experience in Unity,UDK, and GameMaker. Also useful experience: C,C++,Java,OOP Data Structures,Autodesk Maya,ProTools,Reaper,Audition,Photoshop,GIMP... you get the idea.

If your knowledge is very limited, start with something like GameMaker or Project Spark. It will really help you understand basics.
> 3 votes

---
Tags: unity, career
---


# Question
Title: How to ignore collision between two objects
I have a player that shoots in the direction that it is facing. However, the shot that is created when I click, also destroys the player (example). How would I make the shot ignore collision with the player? Or better yet, how to make a shot destroy anything it touches and destroy itself without affecting the player?

This is the code that controls collisions:

```
function OnTriggerEnter (col : Collider) {
    Destroy(col.gameObject);
}

```

The shot is a trigger, but the player isn't. Not sure if this changes anything in this case.

# Answer
There are a lot of ways to ensure that.

The best approach is to use the "Layer Collision Matrix". To keep things organized, you could create a `Bullets`, `Enemies` and a `Player` Layer. Then go to *Edit* \> *Project Settings* \> *Physics* and you'll see the collision matrix.

You can check all the layer-pairs that should report collisions there. In the screenshot you can see that Bullets will only collide with Enemies and Enemies also collide with the Player. Then all that's left to do is assign the matching layers to your GameObjects or Prefabs.

Using the collision matrix is the best approach, because it directly affects the physics simulation (non-colliding layers don't have to be checked for collisions at all) which is the most performant solution to your problem.

Another approach (or you could also combine the two) is to implement `OnCollisionEnter` or `OnTriggerEnter` on the Enemies and Players, and not the Bullet. Then you're free to implement different behavior for each entity and also report scores or perform other tasks.

Bullets could also use

```
col.gameObject.SendMessage("HitByBullet", null,
    SendMessageOptions.DontRequireReceiver);

```

instead of your current `Destroy(col.gameObject)`. Then you can implement a `HitByBullet` method in your Enemy Script and destroy the object there, play a sound effect etc.
> 11 votes

# Answer
You can use `Physics.IgnoreCollision` and make your projectile ignore your player: http://docs.unity3d.com/ScriptReference/Physics.IgnoreCollision.html

Or, you could specify and use 3 different layers: one for your player, one for your projectile, and one for your enemies. Then if you go **Edit \> Project Settings \> Physics**, you can adjust the collision matrix to ensure that your projectile and player layers don't collide with each other.

*Or,* within your `OnTriggerEnter` function, you could check to see if the `col.gameObject.name` matches your player's name, or check `col.gameObject.tag`, or `col.gameObject.GetComponent(Foo)` to see if the collider contains a component that only your player uses.

Few different ways!
> 6 votes

---
Tags: unity, javascript
---


# Question
Title: What platform should educational games target?
Should educational games target the PC or mobile market? My professional development experience has been with the PC, but I'm wondering if mobile (iOS, Android, etc.) has a better market for educational games (elementary/middle). Has anyone been in this market and have a good idea?

This article says

> “Mobile educational games are now outselling PC educational games,” he said. “And the entrepreneurs are incredibly passionate about what they are doing. What we find interesting is the interest among investors in mobile.”

# Answer
Most kids don't download educational games on their phones, so I feel that it would be best to make a Windows program for schools. All the schools I've ever been in use Windows, but it differs.
> 2 votes

# Answer
In my opinion, I think you should go for the mobile market. Younger and younger ages have more access to mobile technologies as they become more popular, and they avoid a lot of hassle to get started to play the game. For example, a child that wants to play a game on the computer usually needs an adult to log them in, find the shortcut or exe, and usually requires a higher level of knowledge to play (mouse, keyboard takes more brain power than jabbing a screen). With a mobile app, they pick up the device and jab the picture of the game they want to play. The mobile platform has many other intuitive controls that apply to children such as rotation and tilting, and easier access to things like a microphone which could be used for voice.
> 1 votes

# Answer
As a parent, I'd buy worthwhile educational games for my daughter on my tablet and phone. It depends on the target age group, but a touch screen is a lot more intuitive to a young child than a mouse.
> 1 votes

# Answer
A reasonable answer here is **both**.

In my (limited, ~1 year) experience in this space, the areas that do well are:

1) Mobile native app

or

2) Responsive web-based game that looks and feels great on many devices (from PCs down to phones).

Schools are moving more and more towards having tablets in class to supplement lessons so (1) would target that area.

Having a game that is accessible regardless of platform (2) is obviously the largest net you can cast. With that comes its own set of challenges however (testing multiple devices, security for the user, etc).

Making a fun game is hard, making a fun game that also achieves educational goals is even harder. Good luck!
> 1 votes

---
Tags: ios, educational-games
---


# Question
Title: XNA, how to draw two cubes standing in line parallelly?
I just got a problem with drawing two 3D cubes standing in line. In my code, I made a cube class, and in the game1 class, I built two cubes, A on the right side, B on the left side. I also setup an FPS camera in the 3D world. The problem is if I draw cube B first(Blue), and move the camera to the left side to cube B, A(Red) is still standing in front of B, which is apparently wrong.

I guess some pics can make much sense. Then, I move the camera to the other side, the situation is like: This is wrong.... From this view, the red cube, A should be behind the blue one, B....

Could somebody give me help please?

This is the draw in the Cube class

```
Matrix center = Matrix.CreateTranslation(
new Vector3(-0.5f, -0.5f, -0.5f));
Matrix scale = Matrix.CreateScale(0.5f);
Matrix translate = Matrix.CreateTranslation(location);
effect.World = center * scale * translate;
effect.View = camera.View;
effect.Projection = camera.Projection;

foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                device.SetVertexBuffer(cubeBuffer);

                RasterizerState rs = new RasterizerState();
                rs.CullMode = CullMode.None;
                rs.FillMode = FillMode.Solid;
                device.RasterizerState = rs;

                device.DrawPrimitives(
                PrimitiveType.TriangleList,
                0,
                cubeBuffer.VertexCount / 3);
            }

```

This is the Draw method in game1

```
 B.Draw(camera, effect);
 A.Draw(camera, effect);

```

\**

# Answer
> 6 votes
It seems to me that you don't have any depth testing going on. For that you have to have a depth buffer and write to that while drawing your geometry.
If you are drawing to a rendertarget then create it like this:

```
RenderTarget2D rt = new RenderTarget2D(device, device.Viewport.Width, device.Viewport.Height, false, SurfaceFormat.Color, DepthFormat.Depth24);

```

If you are drawing directly to the backbuffer you already have a depth texture bound to it.

In your drawing code you need to clear the depth too (well it's optional but it should be cleared to avoid some artifacts, also this doesn't cost you much to do so) while clearing the backbuffer (or rendertarget) color:

```
 device.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Color.Black, 1.0f, 0);
//device is your GraphicsDevice

```

You also have to turn on depth testing before drawing your geometry, you can do it like this:

```
 device.DepthStencilState = DepthStencilState.Default;
//device is your GraphicsDevice

```

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


# Question
Title: How should I interpret these DirectX Caps Viewer values?
Briefly asking - what do the nodes mean and what the difference is between them in DirectX Caps Viewer?

1. DXGI Devices
2. Direct3D9 Devices
3. DirectDraw Devices

The most interesting for me is 1 vs 2. In the **Direct3D9 Devices** under **HAL** node I can see that my GeForce 8800GT supports **PixelShaderVersion 3.0**. However, under **DXGI Devices** I have DX 10, DX 10.1 and DX 11 having **Shader model 4.0** (actually why DX 11? My card is not compatible with DX 11).

I am implementing a DX 11 application (including d3d11.h) with shaders compiled in 4.0 version, so I can clearly see that 4.0 is supported.

What is the difference between 1 and 2? Could you give me some theory behind the nodes?

# Answer
> 4 votes
There was a huge change in the architecture of DirectX when Vista came out. All versions of Direct3D up to 9 were pretty much all-in APIs. With Direct3D 10, part of the API -mostly all the low level stuff like talking to the hardware- was sent to a different API called DXGI. Direct3D10, 10.1 and 11 are different services that interact with DXGI.

Even though they share the same name, Direct3D 9 and below are completely different APIs to DXGI, and that's why you can have both working side to side on Vista and above (you couldn't have Direct3D8 and 9 installed on the same computer. In fact, Direct3D9 is AFAIK backwards compatible a long way back)

Regarding the caps viewer, "DXGI" makes reference to what your card is available to do when running a DXGI-based program (Direct3D 10 and above), while "Direct3D9" makes reference to what your card is available to do when running a program based on Direct3D 9. That's all there is to it.

You see that `PixelShaderVersion` is 3 in the Direct3D9 device, because that's the last version supported by Direct3D 9. You cannot use Shader model 4.0 from a Direct3D 9 program, even if the card supports it.

Regarding DXGI support, if your card supports Direct3D9, then it supports DXGI, and therefore Direct3D11. Direct3D11 is not based on "caps" like 9 and before, but on feature levels. The most basic feature level (9\_1) is (mostly) equivalent to Direct3D9 support, so any program written with Direct3D11 that targets feature level 9\_1 will most likely work on a Direct3D9 capable card, even if it came out before Direct3D11 came out.

Remember that "feature level" is different from the Direct3D version: if the caps viewer says that your card supports up to shader model 4.0, then it probably means that it is unlikely to support feature levels above 10\_0, but you can certainly create a Direct3D11 device based on feature level 9\_1 if you want.

Supporting feature level 11\_0 and above is what manufacturers usually mean with "Direct3D11 support".

Regarding DirectDraw, that's a completely different, and even older (DirectX 7 era) API.

You can read more about DXGI in here, and feature levels in here. The docs are your friends.

---
Tags: directx
---


# Question
Title: Implementing traffic conditions in TORCS
I am working on a project about "Effects of Traffic conditions and Track Complexity on Car Driving Behavior".

**Is it possible to implement traffic in TORCS, or should I use another car simulator?** By the word "*traffic*" I mean there are cars running on both tracks in both directions and I can detect the distances, direction and speed of these cars. Depending on this information I can decide whether I should slow down, speed up and calculate the correct timing to overtake.

# Answer
Since TORCS is an open source project, yes, of course it's possible to implement traffic. You can implement anything you like by changing the code entirely.

If it's reasonable or not is another question entirely. And, it's one only you have the best answer for.

It sounds like your project is more research oriented. And thus, doesn't need to have fancy graphics like a racing simulator provides (yes TORCS does more, I'm speaking more about other simulators). Ideally, if you want something that's more deterministic, you'd have your simulation able to run without any interface whatsoever. If you'd like to have an interface, it can be a very simple one. As simple as having each car represented by a single pixel.

Get your part of the simulation working before worrying about how pretty it looks. It's certainly worth looking further into TORCS to see how difficult it would be to modify for this purpose, to give you more robust simulations, but you might want to get something simple working first.
> 1 votes

---
Tags: game-design, simulations
---


title: Implementing Camera Zoom in a 2D Engine

text:
# Question
Title: Implementing Camera Zoom in a 2D Engine
I'm currently trying to implement camera scaling/zoom in my 2D Engine. Normally I calculate the Sprite's drawing size and position similar to this pseudo code:

```
render()
{
    var x = sprite.x;
    var y = sprite.y;
    var sizeX = sprite.width * sprite.scaleX; // width of the sprite on the screen
    var sizeY = sprite.height * sprite.scaleY; // height of the sprite on the screen
}

```

To implement the scaling i changed the code to this:

```
class Camera
{
    var scaleX;
    var scaleY;
    var zoom;
    var finalScaleX; // = scaleX * zoom
    var finalScaleY; // = scaleY * zoom
}

render()
{
    var x = sprite.x * Camera.finalScaleX;
    var y = sprite.y * Camera.finalScaleY;
    var sizeX = sprite.width * sprite.scaleX * Camera.finalScaleX;
    var sizeY = sprite.height * sprite.scaleY * Camera.finalScaleY;
}

```

The problem is that when the zoom is smaller than 1.0 all sprites are moved toward the top-left corner of the screen. This is expected when looking at the code but i want the camera to zoom on the center of the screen.

Any tips on how to do that are welcome. :)

# Answer
> 1 votes
When your sprite is in the center of the screen its position should be unchanged by zooming. This tells me that if sprite.x is 0.5 the resulting x should still be 0.5 after the equation assuming that the center of the screen is 0.5.

This could achieve that:

```
var halfScreenWidth = Screen.width/2.0f;
var x = (sprite.x - halfScreenWidth) * Camera.finalScaleX + halfScreenWidth;

```

---
Tags: 2d, mathematics, sprites, rendering, camera
---


title: Understanding dot notation

text:
# Question
Title: Understanding dot notation
Here's my interpretation of dot notation:

```
a = [2,6]
b = [1,4]
c = [0,8]
a . b . c = (2*6)+(1*4)+(0*8) = 12 + 4 + 0 = 16

```

What is the significance of 16? Apparently it's a scalar.

Am I right in thinking that a scalar is the number we times a unit vector by to get a vector that has a scaled up magnitude but the same direction as the unit vector? So again, what is the relevance of 16? When is it used? It's not the magnitude of all the vectors added up.

The magnitude of all of them is calculated as follows:

```
sqrt( ax * ax + ay * ay ) + sqrt( bx * bx + by * by ) + sqrt( cx * cx + cy * cy)
sqrt( 2 * 2 + 6 * 6 ) + sqrt( 1 * 1 + 4 * 4 ) + sqrt( 0 * 0 + 8 * 8)
sqrt( 4 + 36 ) + sqrt( 1 + 16 ) + sqrt( 0 + 64)
sqrt( 40 ) + sqrt( 17 ) + sqrt( 64)
6.3 + 4.1 + 8
10.4 + 8
18.4

```

So I don't really get this diagram:

Attempting with sensible numbers:

```
a = [1,0]
b = [4,3]

a . b = (1*0) + (4*3) = 0 + 12 = 12

```

So what exactly is `a . b` describing here? The magnitude of that vector? Because that isn't right:

```
the 'a.b' vector = [4,0]
sqrt( x*x + y*y )
sqrt( 4*4 + 0*0 )
sqrt( 16 + 0 )
4

```

So what is 12 describing?

# Answer
You did your dot product wrong as DMGregory pointed out...

Anyways this is the formula for a dot product, which answers your question but probably isn't useful to you so I'll cover where I've found dot product useful.

```
A·B = |A|*|B|*cos(Θ)

|A| is the lenght of A
|B| is the lenght of B
Θ is the angle between A and B using 0,0 as a pivot

```

The dot product is typically used for telling where a an object is in relation to movement. If 0,0 is current location and A is the movement vector and B is an object we can tell 3 things about it from the result of the dot product.

1. If A and B are perpendicular (at 90 degrees to each other), the result of the dot product will be zero, because cos(Θ) will be zero.
2. If the angle between A and B are less than 90 degrees, the dot product will be positive (greater than zero), as cos(Θ) will be positive, and the vector lengths are always positive values.
3. If the angle between A and B are greater than 90 degrees, the dot product will be negative (less than zero), as cos(Θ) will be negative, and the vector lengths are always positive values.

You can extend from that and assuming all vectors are normalized you can the below which allows for easy line of sight checking.

```
θ = acos(D'V')

```

D is the direction the object doing the seeing is pointing. V is the direction from the object diong the seeing to the object we are checking is in the line of sight.

So for example if the cone of vision was 90degrees any result of θ below 45degrees would be in the line of sight.

I'm a bit rusty on this stuff so feel free to call me out on errors.
> 0 votes

---
Tags: linear-algebra
---


title: Empty Synchronized method in game loop

text:
# Question
Title: Empty Synchronized method in game loop
I am studying the gameloop used in Replica Island to understand a bit about Android game development. The main loop has the below logic...

**GameThread.java** (note the variable names in sample code dont match exact source code)

```
 while (!finished) {

        if (objectManager != null) {

            renderer.waitDrawingComplete();
            //Do more gameloop stuff after drawing is complete...
      }
 }

```

I was curious to see what waitDrawingComplete actually does, but found its just an empty syncrhonized method! I guess it does nothing, am I missing something here?

**GameRenderer.java** line 328

```
 public synchronized void waitDrawingComplete() {
 }

```

Source code can be checked out here with SVN if you feel like having a look: https://code.google.com/p/replicaisland/source/checkout

# Answer
> 3 votes
The source code gives a good clue:

```
/**
 * This function blocks while drawFrame() is in progress, and may be used by other threads to
 * determine when drawing is occurring.
 */

public synchronized void waitDrawingComplete() {

```

Then if we look in `onDrawFrame` we see

```
synchronized (this) {
  // big block of drawing code
}

```

The synchronized keyword usage here means that one of the methods will block until the other function is complete (onDrawFrame or waitDrawingComplete). In other words the empty function is simply used to wait until the drawing is complete, so it does do something.

A sequence of events might look like this:

* Thread 1: code execution is inside onDrawFrame
* Thread 2: waitDrawingComplete is called. This thread blocks because code is inside the synchronized in Thread 1.
* Thread 1: Reaches the end of onDrawFrame
* Thread 2: waitDrawingComplete executes and returns and execution returns to the following code.

---
Tags: android
---


# Question
Title: Why is GL_TEXTURE_MAX_ANISOTROPY_EXT undefined?
So I'm writing my texture class in my opengl game, I get to the part where I would normally set GL\_TEXTURE\_MAX\_ANISOTROPY\_EXT, and I'm shocked to discover that it's undefined! This exact same extensions worked perfectly in a different application, so I know it's not a typo or something.

It's worth noting that I'm getting my extensions using glcorearb.h, instead of glext.h, because I have no intention of supporting the compatibility profile. Could this be my problem, and if so, how do I work around it?

# Answer
> 4 votes
It's hard to say without seeing the whole project so here are a few ideas:

* Check if you have the project's paths properly set up - maybe a path to some library/header file is missing. Check the other project (the one which works) and compare. Make sure to adjust the paths/settings for the new project's location.
* Are you using the same version of library/ies that in the other project? If not maybe this version doesn't support `GL_TEXTURE_MAX_ANISOTROPY_EXT` (I don't know if it should, just looking for possible explanations).
* Make sure you have necessary header file(s) included in the source file where you're trying to use `GL_TEXTURE_MAX_ANISOTROPY_EXT`.

**Update:**

From what I gather, it seems that anisotropic filtering is still implemented as an extension and isn't included in `OpenGL Core`. Therefore you have to use it like any other extension (if you don't know how, there are plenty of tutorials).

As for the value itself, the docs define it as:

```
#define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE
#define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF

```

If you don't want to define it by yourself or if need more `OpenGL` extensions you should just use `glext.h` or some other library like you used to.

# Answer
> 4 votes
> This information may not be completely relevant/true since the latest OpenGL versions

If you are wondering why anisotropy is not included in OpenGL core, I found that the following page had a good explanation:

https://paroj.github.io/gltut/Texturing/Tut15%20Anisotropy.html#d5e11942

> The “Open” in OpenGL refers to the availability of the specification, but also to the ability for anyone to implement it. As it turns out, anisotropic filtering has intellectual property issues associated with it. If it were adopted into the core, then core OpenGL would not be able to be implemented without licensing the technology from the holder of the IP. It is not a proprietary extension because none of the ARB members have the IP; it is held by a third party.

---
Tags: opengl, c++, extension
---


# Question
Title: Progress bar in Super Hexagon using OpenGL ES 2 (Android)
I'm wondering how the progress bar in Super Hexagon was made. (see image, top left) Actually I am not very sure how to implement a progress bar at all using OpenGL ES 2 on Android, but I am asking specifically about the one used in Super Hexagon because it seems to me less straightforward / obvious than others: the bar changes its colour during game play.

I think one possibility is to use the built-in Android progress bar. I can see from some Stackoverflow questions that you can change the default blue colour to whatever you want, but I'm not sure whether you can update it during the game play.

The other possibility I can think of for implementing a progress bar is to have a small texture that starts with a scale of 0 and that you keep scaling until it reaches the maximum size, representing 100%. But this suffers from the same problem as before: you'll not be able to update the colour of the texture during run-time. It's fixed.

So what's the best way to approach this problem?

\*I'm assuming he didn't use a particular library, although if he did, it would be interesting to know. I'm interested in a pure OpenGL ES 2 + Android solution.

# Answer
Think shaders. If it's this kind of progress bar you're after just write a custom shader and have the width and colour parameterised -- you don't even need a texture image for that, just a shader writing fragment colour based on UV coords.

If you'd like a fancier progress bar with a texture image then you can use a grayscale texture and a shader which colourises the fragment based on the texture luminance and the parameters (fragment\_col = texel\_luminance * current\_col). Then it's up to you whether you'd like the texture stretched as the progress bar width changes (e.g. by altering its UV coords) or just skip the part which is outside the bar.

To avoid if-else blocks (which are often costly on mobile GPUs) you can multiply your fragment by the result of the step function (https://www.opengl.org/sdk/docs/man/html/step.xhtml)
> 1 votes

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


# Question
Title: Get stick analogue XY position using Jinput in lwjgl
I want to capture the movement of the analogue stick of the gamePad.

*is there any equivalent function to this?*

```
 public void mouseMoved(MouseEvent mouseEvent) {
    mouseEvent.getX(); //return the X coordinate of the cursor inside a component
    mouseEvent.getY();//return the Y coordinate of the cursor inside a component
    }

```

into ***`lwjgl.input.Controllers`***, I found **`controller.getAxisValue()`** but this one doesn't work as the function above.

# Answer
Define 'doesn't work as the function above' -- what would you expect and what are you getting? Controller.getAxisValue(..) is the correct way to read gamepad inputs.

Check the Controller.getPovX/Y(), .getButton(..) and other methods too. Also, please note that there is no standard stick/button/trigger/etc to axis/key mapping so you'll get different values for different controllers, some controllers will report negative values for left/down, some will report negative for right/up, some will report keys as buttons, some as analogue inputs with only two values or a mix of the two, and there are also analogue triggers/shoulders -- in short, be prepared for a curiosity show :)
> 0 votes

---
Tags: java, game-mechanics, lwjgl, gamepad
---


title: Load Meshes with Bullet Physics

text:
# Question
Title: Load Meshes with Bullet Physics
I just started implementing some physics in my game with Bullet Physics and I was just wondering how would i use bullet physics to load in meshes. For my for DirectX I load in x files into a ID3DXMesh. I'd like to know how do I create a mesh in bullet physics instead of using boxes and spheres. I can't seem to find a way to do this. It would be great if someone could help me out. Thank you.

# Answer
You should get the mesh's vertex positions to create a btTriangleIndexVertexArray which is required by the btBvhTriangleMeshShape's constructor. You should look into the samples (demos) provided in the Bullet library for more.
Note that Bullet meshes can only be used as static colliders (terrain for instance), not for dynamic bodies. For that you should either use Convex Hulls and/or basic shapes to create bodies that resemble your mesh to some extent. Please see ConvexDecomposition demo for that.
> 2 votes

---
Tags: c++, collision-detection, physics, directx, mesh
---


# Question
Title: How to rotate a set of points on z = 0 plane in 3-D, preserving pairwise distances?
I have a set of points `double n[]` on the plane `z = 0`.
And I have another set of points `double[] m` on the plane `ax + by + cz + d = 0`.
Length of `n` is equal to length of `m`.
Also, euclidean distance between `n[i]` and `n[j]` is equal to euclidean distance between `m[i]` and `m[j]`.

I want to rotate `n[]` in 3-D, such that for all `i`, `n[i] = m[i]` would be true.

In other words, I want to turn a plane into another plane, preserving the pairwise distances.

Here's my code in java. But it does not help so much:

```
double[] rotate(double[] point, double[] currentEquation, double[] targetEquation)
{

    double[] currentNormal = new double[]{currentEquation[0], currentEquation[1], currentEquation[2]};
    double[] targetNormal = new double[]{targetEquation[0], targetEquation[1], targetEquation[2]};
    targetNormal = normalize(targetNormal);
    double angle = angleBetween(currentNormal, targetNormal);
    double[] axis = cross(targetNormal, currentNormal);
    double[][] R = getRotationMatrix(axis, angle);
    return rotated;
}

double[][] getRotationMatrix(double[] axis, double angle)
{
    axis = normalize(axis);

    double cA = (float)Math.cos(angle);
    double sA = (float)Math.sin(angle);
    Matrix I = Matrix.identity(3, 3);
    Matrix a = new Matrix(axis, 3);

    Matrix aT = a.transpose();

    Matrix a2 = a.times(aT);

    double[][] B =
        {
            {0, axis[2], -1*axis[1]},
            {-1*axis[2], 0, axis[0]},
            {axis[1], -1*axis[0], 0}
        };
    Matrix A = new Matrix(B);

    Matrix R = I.minus(a2);

    R = R.times(cA);
    R = R.plus(a2);
    R = R.plus(A.times(sA));
    return R.getArray();
}

```

This is what I get. The point set on the right side is actually part of a point set on the left side. But they are on another plane.

Here's a 2-D representation of what I try to do:

There are two lines. The line on the bottom is the line I have. The line on the top is the target line. The distances are preserved (a, b and c).

**Edit:**
I have tried both methods written in answers. They both fail (I guess).

Method of *Martijn Courteaux*

```
   public static double[][] getRotationMatrix(double[] v0, double[] v1, double[] v2, double[] u0, double[] u1, double[] u2)
        {

            RealMatrix M1 = new Array2DRowRealMatrix(new double[][]{
                    {1,0,0,-1*v0[0]},
                    {0,1,0,-1*v0[1]},
                    {0,0,1,0},
                    {0,0,0,1}
            });

            RealMatrix M2 = new Array2DRowRealMatrix(new double[][]{
                    {1,0,0,-1*u0[0]},
                    {0,1,0,-1*u0[1]},
                    {0,0,1,-1*u0[2]},
                    {0,0,0,1}
            });

            Vector3D imX = new Vector3D((v0[1] - v1[1])*(u2[0] - u0[0]) - (v0[1] - v2[1])*(u1[0] - u0[0]),
                    (v0[1] - v1[1])*(u2[1] - u0[1]) - (v0[1] - v2[1])*(u1[1] - u0[1]),
                    (v0[1] - v1[1])*(u2[2] - u0[2]) - (v0[1] - v2[1])*(u1[2] - u0[2])
            ).scalarMultiply(1/((v0[0]*v1[1])-(v0[0]*v2[1])-(v1[0]*v0[1])+(v1[0]*v2[1])+(v2[0]*v0[1])-(v2[0]*v1[1])));

            Vector3D imZ = new Vector3D(findEquation(u0, u1, u2));
            Vector3D imY = Vector3D.crossProduct(imZ, imX);

            double[] imXn = imX.normalize().toArray();
            double[] imYn = imY.normalize().toArray();
            double[] imZn = imZ.normalize().toArray();
            RealMatrix M = new Array2DRowRealMatrix(new double[][]{
                    {imXn[0], imXn[1], imXn[2], 0},
                    {imYn[0], imYn[1], imYn[2], 0},
                    {imZn[0], imZn[1], imZn[2], 0},
                    {0, 0, 0, 1}
            });
            RealMatrix rotationMatrix = MatrixUtils.inverse(M2).multiply(M).multiply(M1);
            return rotationMatrix.getData();
        }

```

Method of *Sam Hocevar*

```
static double[][] makeMatrix(double[] p1, double[] p2, double[] p3)
    {
        double[] v1 = normalize(difference(p2,p1));
        double[] v2 = normalize(cross(difference(p3,p1), difference(p2,p1)));
        double[] v3 = cross(v1, v2);
        double[][] M = { { v1[0], v2[0], v3[0], p1[0] },
                         { v1[1], v2[1], v3[1], p1[1] },
                         { v1[2], v2[2], v3[2], p1[2] },
                         {   0.0,   0.0,   0.0,   1.0 } };
        return M;
    }

    static double[][] createTransform(double[] A, double[] B, double[] C,
                         double[] P, double[] Q, double[] R)
    {
        RealMatrix c = new Array2DRowRealMatrix(makeMatrix(A,B,C));
        RealMatrix t = new Array2DRowRealMatrix(makeMatrix(P,Q,R));
        return MatrixUtils.inverse(c).multiply(t).getData();
    }

```

The blue points are the calculated points. The black lines indicate the offset from the real position.

# Answer
New post, clean and well. I tried to implement Sam's answer, but slightly different, and it works. This approach is simpler than all the others, simply because it relies on you to make sure that your preserve the distance. If you don't, it will still match the points, but without distance and angles being preserved.

Here you have the check:

In code this would be (based on Sam's snippet):

```
static double[][] makeMatrix(double[] p1, double[] p2, double[] p3)
{
    double[] v1 = difference(p2,p1);
    double[] v2 = difference(p3,p1);
    double[] v3 = cross(v1, v2);
    double[][] M = { { v1[0], v2[0], v3[0], p1[0] },
                     { v1[1], v2[1], v3[1], p1[1] },
                     { v1[2], v2[2], v3[2], p1[2] },
                     {   0.0,   0.0,   0.0,   1.0 } };
    return M;
}

static double[][] createTransform(double[] A, double[] B, double[] C,
                     double[] P, double[] Q, double[] R)
{
    RealMatrix c = new Array2DRowRealMatrix(makeMatrix(A,B,C));
    RealMatrix t = new Array2DRowRealMatrix(makeMatrix(P,Q,R));
    return t.multiply(MatrixUtils.inverse(c)).getData();
}

static double[][] transformPoints(double[][] points, double[][] matrix)
{
    double[][] tfd = new double[points.length][];
    for (int i = 0; i < points.length; ++i)
    {
        tfd[i] = multiply(matrix, points[i]);
    }
    return tfd;
}

static double[] multiply(double[][] matrix, double[] point)
{
     double[] temp = new double[4];
     for (int i = 0; i < 3; ++i) temp[i] = point[i];
     temp[3] = 1.0;

     double[] res = new double[3];
     for (int i = 0; i < 3; ++i)
     {
         for (int j = 0; j < 4; ++j)
         {
             res[i] += temp[j] * matrix[i][j];
         }
     }

     return res;
}

```
> 1 votes

# Answer
If I understand correctly, you have three points `A`, `B`, `C`, and three points `P`, `Q`, `R` and you would like to know the affine transform (*i.e.* preserving distances) that transforms the first set into the second set.

Finding the transform is straightforward; you just need to create two orthonormal bases from your sets of points, fill matrixes with the basis vectors, and combine them.

Here is one way to do it (assuming you got some method to subtract two vectors):

```
double[][] makeMatrix(double[] p1, double[] p2, double[] p3)
{
    double[] v1 = normalize(p2 - p1);
    double[] v2 = normalize(cross(p3 - p1, v1));
    double[] v3 = cross(v1, v2);
    double[][] M = { { v1[0], v2[0], v3[0], p1[0] },
                     { v1[1], v2[1], v3[1], p1[1] },
                     { v1[2], v2[2], v3[2], p1[2] },
                     {   0.0,   0.0,   0.0,   1.0 } };
    return M;
}

mat4 createTransform(double[] A, double[] B, double[] C,
                     double[] P, double[] Q, double[] R)
{
    return mul(inverse(makeMatrix(A, B, C)),
               makeMatrix(P, Q, R));
}

```
> 4 votes

# Answer
# **Update:**

This was much harder to solve than I thought. However, I think I managed it to fix it, after trying 5 different approaches. So, the requirements really are that you have 3 source points and 3 corresponding destination points. And that you are sure that the distance between the points is conserved. And finally that the source points define a plane.

**(Note that all indices in Maple start at 1 instead of 0)**

Your 3 source and destination points are represented like this:

First step is to create matrices that translate these points to the origin. The matrixes will be:

Here `M1` will put the source points to the origin and `M2` will do the same for the dest points, both using the first of the three points. Now we have two times a zero vector and two source vectors and two dest vectors:

The names refer to Source Points Centered (spC) and Destination Points Centered (dpC).

Next, we are going to find the linear combination of those two source vectors that produce the unit x vector (1, 0, 0). So we are looking for a solution for:

```
alpha * spC[0] + beta * spC[1] = (1, 0, 0)

```

Maple can solve this for us:

So, now, we have found a representation for the unit vector in function of the source vectors. We know that after applying the final linear transformation, the image of the x unit vector will be a linear combination of the destination vectors, again with the same coefficients we just found: alpha and beta. So, let's compute the image of the x unit vector after our linear transform:

So, at this point, we already know what the image of the x unit vector will be. We can also compute the normal vector of our three destination points. This will be the image of our z unit vector. This normal vector is given by the cross product of the two destination vectors.

So, now we know already two images of the unit vectors x and z. The image of the unit vector y can be found by taking into account that we want an orthonormal transformation. Just take the crossproduct of these two image vectors, to get the image of the y unit vector. Once we found the images, we have to normalize them of course by dividing by their length:

(Note: the requirement was that the distance was conserved. That means that normalizing the image of x would not be necessary.)

Now we can create the linear component of our transformation matrix by putting `imXn`, `imYn` and `imZn` in that order as column in a matrix:

You can see I homogenized the matrix to an affine matrix by adding zeroes at the right and bottom and a 1 at right bottom position of the matrix. To clarify:

```
a b c              a b c 0
d e f    becomes   d e f 0
g h i              g h i 0
                   0 0 0 1

```

Now we can compute the total matrix! The transformation is basically:

1. Translate the source points to the origin
2. Apply the linear transform
3. Translate the points to the dest position

This gives this matrix in total:

---

# Old answer:

Well, this was actually a great exercise for my finals tomorrow. Here you have the technical part. If you want to, I can add explanation later:

Large image here.

This is done with Maple. So as you can see, if we let the normal vector of plane `z = 0`, which is `<0, 0, 1>` get through the transformation matrix, we have the expected normal vector for your `ax + by + cz + d = 0` plane. If you assume that `a^2 + b^2 + c^2 = 1`, then it's even nicer.

Note that you have one degree of freedom: randomVector can be random and determines the rotation, because you didn't specify anything on how to rotate this thing.

If you make the randomVector less random, you can get a cleaner matrix, but I'm not sure if this will work for all kinds of target planes, because it can occur that the CrossProduct turns out to be zero, if the normalVector and the randomVector can be parallel:

Large image here.

Also note that you might want to add a translational component afterwards to make the plane match the equation `ax + by + cz + d = 0`, because if you transform all your points with this matrix, they are going to be in the plane `ax + by + cz = 0` right now.
> 3 votes

---
Tags: java, rotation, matrix
---


# Question
Title: Can't read .cso files but I can read their .hlsl versions?
Well I've been trying to read a .cso file to use as a shader for a DirectX program I'm currently making.

Problem is no matter how I implemented a way to read the file it never worked. And after fidgeting around I discover that it's only the .cso files I can't read.

I can read anything else (which means it works) even their .hlsl files. Which is strange because the .hlsl (high level shader language) files are supposed to turn into .cso (compiled shader object) files.

What I'm currently doing is:

```
vector<byte> Read(string File){
    vector<byte> Text;
    fstream file(File, ios::in | ios::ate | ios::binary);

    if(file.is_open()){
        Text.resize(file.tellg());
        file.seekg(0 , ios::beg);
        file.read(reinterpret_cast<char*>(&Text[0]), Text.size());
        file.close();
    }

    return Text;
};

```

If I then implement it.

```
Read("VertexShader.hlsl"); //Works
Read("VertexShader.cso"); //Doesn't Works?!?!

```

And I need the .cso version of the shader to draw my sexy triangles. Without it my life and application will never continue and I have no idea what could be wrong.

(I've also asked this at stack overflow but still no answers.)

# Answer
Depending on how you've set up your project, you likely have your .cso files going to the project output `$(OutDir)`, and your debug working directory set to the project directory `$(ProjectDir)`. As a result, file paths are relative to the project directory. You should change your working directory to the output directory for debugging, and you should be able to load the .cso files.

Note that this will cause loading your .hlsl files to *stop* working though, unless you copy them to the output directory as well (but you shouldn't need them there if you're compiling at build-time).
> 2 votes

# Answer
Can be multiple things, don't have access to VS right now to give you exact answer but it can be:

* VS shader compiler is not attached to your project. Right click on project-\> build customization and check the list
* shader file is not acctually set as shader file. Right click on shader file in your project and make sure it has selected shader type and properties
* by default VS will compile your hlsl files into cso files before it compiles your main project and put them in //debug or //release, make sure you search in the right directory
> 0 votes

---
Tags: c++, shaders, directx, hlsl, directx11
---


# Question
Title: XNA - 3D AABB collision detection and response
I've been fiddling around with 3D AABB collision in my voxel engine for the last couple of days, and every method I've come up with thus far has been *almost* correct, but each one never quite worked exactly the way I hoped it would.

Currently what I do is get two bounding boxes for my entity, one modified by the X translation component and the other by the Z component, and check if each collides with any of the surrounding chunks (chunks have their own octrees that are populated only with blocks that support collision). If there is a collision, then I cast out rays into that chunk to get the shortest collision distance, and set the translation component to that distance if the component is greater than the distance.

The problem is that sometimes collisions aren't even registered. Here's a video on YouTube that I created showing what I mean. I suspect the problem may be with the rays that I cast to get the collision distance not being where I think they are, but I'm not entirely sure what would be wrong with them if they are indeed the problem.

Here is my code for collision detection and response in the X direction (the Z direction is basically the same):

```
// create the XZ offset vector
Vector3 offsXZ = new Vector3(
    ( _translation.X > 0.0f ) ? SizeX / 2.0f : ( _translation.X < 0.0f ) ? -SizeX / 2.0f : 0.0f,
    0.0f,
    ( _translation.Z > 0.0f ) ? SizeZ / 2.0f : ( _translation.Z < 0.0f ) ? -SizeZ / 2.0f : 0.0f
);

// X physics
BoundingBox boxx = GetBounds( _translation.X, 0.0f, 0.0f );
if ( _translation.X > 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = GetShortestCollisionDistance( chunk, Vector3.Right, offsXZ ) - 0.0001f;
            if ( dist < _translation.X )
            {
                _translation.X = dist;
            }
        }
    }
}
else if ( _translation.X < 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = GetShortestCollisionDistance( chunk, Vector3.Left, offsXZ ) - 0.0001f;
            if ( dist < -_translation.X )
            {
                _translation.X = -dist;
            }
        }
    }
}

```

And here is my implementation for GetShortestCollisionDistance:

```
private float GetShortestCollisionDistance( Chunk chunk, Vector3 rayDir, Vector3 offs )
{
    int startY = (int)( -SizeY / 2.0f );
    int endY   = (int)(  SizeY / 2.0f );
    int incY   = (int)Cube.Size;

    float dist = Chunk.Size;
    for ( int y = startY; y <= endY; y += incY )
    {
        // Position is the center of the entity's bounding box
        Ray ray = new Ray(
            new Vector3(
                Position.X + offs.X,
                Position.Y + offs.Y + y,
                Position.Z + offs.Z
            ),
            rayDir
        );

        // Chunk.GetIntersections(Ray) returns Dictionary<Block, float?>
        foreach ( var pair in chunk.GetIntersections( ray ) )
        {
            if ( pair.Value.HasValue && pair.Value.Value < dist )
            {
                dist = pair.Value.Value;
            }
        }
    }

    return dist;
}

```

I realize some of this code can be consolidated to help with speed, but my main concern right now is to get this bit of physics programming to actually work.

# Answer
> 1 votes
I've solved it. It doesn't work perfectly with corners, but it works well enough for me right now.

What I'm doing is instead of only casting rays in the direction I'm traveling in, I'm also casting rays in the "opposite" direction so that I can check blocks in both +X/+Z and -X/-Z. Here's my updated code for the X direction (again, the Z direction is basically the same):

```
// create the XZ offset vectors
Vector3 offsX = new Vector3( Size.X / 2.0f, 0.0f, 0.0f );
Vector3 offsZ = new Vector3( 0.0f, 0.0f, Size.Z / 2.0f );

// X physics
BoundingBox boxx = GetBounds( _translation.X, 0.0f, 0.0f );
if ( _translation.X > 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = Math.Min(
                GetShortestCollisionDistance( chunk, Vector3.Right, offsX + offsZ ),
                GetShortestCollisionDistance( chunk, Vector3.Right, offsX - offsZ )
            ) - 0.0001f;
            if ( dist < _translation.X )
            {
                _translation.X = dist;
            }
        }
    }
}
else if ( _translation.X < 0.0f )
{
    foreach ( Chunk chunk in surrounding )
    {
        if ( chunk.Collides( boxx ) )
        {
            float dist = Math.Min(
                GetShortestCollisionDistance( chunk, Vector3.Left, -offsX + offsZ ),
                GetShortestCollisionDistance( chunk, Vector3.Left, -offsX - offsZ )
            ) - 0.0001f;
            if ( dist < -_translation.X )
            {
                _translation.X = -dist;
            }
        }
    }
}

```

Also, to help speed up the collision checking, I updated my chunks to only add exposed blocks to the octree instead of every block that supported collision.

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


# Question
Title: How to use OpenGL functions from multiples thread?
I'm writing a small game using OpenGL.

I'm implementing basic networking in this game and I'm facing a problem.

I have a thread in my client socket class that check for available data, when there are data I raise an event like this :

```
immutable int len = this.m_socket.receive(data);

if(len > 0)
{
    this.m_onDataEvent(data);
}

```

Then on my game class, I have a function that handle and parse data like this :

```
switch(msgId)
{
    case ProtocolID.CharacterData:

        // Load terrain with opengl, character model....

```

Im not able to call opengl functions because my opengl context is created from a different thread.

But I really don't know how I can solve this problem, I tried Google but it's really hard to find a solution.

I'm using D programming language if it can help.

# Answer
> 10 votes
You're right on track with using the context only from a single thread. You can only use an OpenGL context from one thread at a time, but you can do everything else in another thread.

---

The simplest way to take advantage would be to do all the loading as you normally would, but send some kind of "event" back to your main thread to actually call the OpenGL upload with everything already prepared.

---

Once you have that working you can take it a step further by introducing asynchronous DMA mappings using a functions like glMapBuffer. In this case, you will still pass an "event" to your render thread to do the OpenGL call, but instead of waiting for the upload, you will receive a pointer where OpenGL wants the data, and it doesn't care what thread puts it there.

It might go like this: You get your network event, send a "buffer request event" to your main render thread. Still working from the network thread, continue loading / preparing your data and then when it's ready for upload, wait for the `glMapBuffer` pointer back from the OpenGL thread, copy the data into it and then send ... another ... event back to your renderer to tell it "The data is there, do `glUnmapBuffer` and set up other GL stuff now"

# Answer
> 4 votes
As it was mentioned by others, it is a safer play to keep the GL context to a single thread and communicate with it via producer/consumer buffers, events, etc. The OpenGL API wasn't really developed with treading in mind.

But I think it is worth mentioning that you can move your existing context between threads. Every windowing system that supports OpenGL has a proper method for it:

Windows: wglMakeCurrent()

MacOS: NSOpenGLContext

OpenGL ES / EGL: eglMakeCurrent()

All the above allow you to bind a context to a thread and then call GL functions normally from that thread.

`wglMakeCurrent` was historically buggy, I haven't used it for a long time, so I'm not sure how it stands today, but I have found that NSOpenGLContext and eglMakeCurrent work very well.

---
Tags: opengl, multithreading
---


title: OpenGL setup on Windows

text:
# Question
Title: OpenGL setup on Windows
I have been trying to use OpenGL for two days now. First on Mac, then on Windows. The problem with Mac is that it doesn't support the newer versions of OpenGL. I ran a tutorial that actually did get some things working, but it only works in XCode (i.e., I can't create a new file, paste in the same code, and get it to work). Because of these issues, I moved to Windows. My Windows 7 has OpenGL 4.3, which is the same that is used in alot of other tutorials. However, not one of these tutorials gives any instruction on how to set it up for the first time. I have come across some vague posts saying that some libraries need to be linked. But WHAT libraries, and HOW do I link them?

Please help. I am pretty desperate to set this up as this project is due for work soon. I have actually used OpenGL before at my university, but the computers already had everything set up. The project itself is very easy, but setting up OpenGL is not something I know how to do.

Edit: Using C++.

# Answer
## Visual Studio

The Swiftless Tutorials should function as a good basis. I'm going to point out the second paragraph in the Coding section in particular:

> So open up Visual Studio and create a new Windows Console Application in C++. Make sure it is empty to begin with, and then create 4 files. I am calling them: “main.cpp, main.h, opengl\_3.cpp, opengl\_3.h”. I am going to go through these files one by one, starting with the header files, so that we don’t get mixed up shuffling between them.

And its pragmas:

```
#pragma comment(lib, "glew32.lib")
#pragma comment(lib, "opengl32.lib")

```

Though I'm not particularly familiar with visual studio, so I'm just going to leave you with that tutorial.

## CodeBlocks

You can create an OpenGL project in the projects menu. However, that sets up an OpenGL 2.1 project, not an OpenGL 4.2 project. Once you have that project created, you can fallow along with most visual-studio tutorials to the point of copy/past. (only adjusting things here and there for the compiler differences.)

***Feel free to stop reading. The following is how I prefer to do it (In codeblocks.) It might not be how you want to do it for whatever reason, it works regardless.***

But, since I can: You can add in the code that upgrades it from 2.1 to 4.2 yourself with `wglCreateContextAttribsARB(...)` Which you would use after the 2.1 context was created. In the particular case of the CodeBlocks projects, that would be by modifying the `EnableOpenGL()` function.

```
//#include <GL/gl.h> <- this is OpenGL 2.1 header. You don't want that.
#include <GL/wglext.h> // you might need to download these
#include <GL/gl3.h>

//...

void EnableOpenGL(HWND hwnd, HDC* hDC, HGLRC* hRC)
{
    //...

    PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL;

    int attributes[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, major,
        WGL_CONTEXT_MINOR_VERSION_ARB, minor,
        WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
        0,
    };

    wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB");

    if (wglCreateContextAttribsARB == NULL)
    {
        // HANDLE FAILURE
    }

    HGLRC sglcv = wglCreateContextAttribsARB(hDC, NULL, attributes);

    if (sglcv != NULL)
    {
        wglMakeCurrent(NULL, NULL);
        wglDeleteContext(hRC);
        hRC = sglcv;
        wglMakeCurrent(hDC, hRC);

        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
    }
    else
    {
        // HANDLE FAILURE
    }
}

```

Then (Only then. You need a context to be bound first.) you can get OpenGL functions as needed with:

```
PFN$(glFunctionCapitalized)PROC FunctionName;
FunctionName = (PFN$(glFunctionCapitalized)PROC)wglGetProcAddress("$(glFunctionName)");
if (FunctionName == NULL)
{
    // You cannot use that function. Handle as needed.
}

```

For example:

```
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
VertexAttribPointer = (PFNGLVERTEXATTRIBPOINTERPROC)wglGetProcAddress("glVertexAttribPointer");
if (VertexAttribPointer == NULL)
{
    cout << "glVertexAttribPointer could not be loaded. Exiting application." << endl;
    system("pause");
    return FATAL_ERROR;
}

```

Lastly, changing the 2.1 rendering code that's near the end of the main function, in the program loop. It should be fairly Identifiable. (it uses `glBegin`, `glVertex`, and `glEnd`) The section should be something like this:

```
        /* OpenGL animation code goes here */

        glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        glPushMatrix();
        glRotatef(theta, 0.0f, 0.0f, 1.0f);

        glBegin(GL_TRIANGLES);

            glColor3f(1.0f, 0.0f, 0.0f);   glVertex2f(0.0f,   1.0f);
            glColor3f(0.0f, 1.0f, 0.0f);   glVertex2f(0.87f,  -0.5f);
            glColor3f(0.0f, 0.0f, 1.0f);   glVertex2f(-0.87f, -0.5f);

        glEnd();

        glPopMatrix();

        SwapBuffers(hDC);

        theta += 1.0f;
        Sleep (1);

```

Which you can change around to your liking. Any input, or window-stuff you might want to do would be in the `WindowProc` function, just after the `main` function.
> 2 votes

# Answer
There is no way on windows to get "direct" access to OpenGL (e.g. load a header and link a lib), instead you need to ask Windows to give you the pointer to the different functions at run time.

So you need to define a bunch of function pointers like this:

```
void (*glUseProgram)(GLuint program) = nullptr;
void (*glValidateProgram)(GLuint program) = nullptr;
[... etc ...]

```

And assign them

```
glUseProgram = glfwGetProcAddress("glUseProgram");
glValidateProgram = glfwGetProcAddress("glValidateProgram");
[... etc ...]

```

In this case I am using glfw to get the function pointers, but the same is possible with WGL. (WGL = Windows OpenGL API, glfw wraps multiple different APIs including WGL from different systems into one and makes sure everything just works)

This is of course a lot of redundant code but unfortunately necessary. Using WinAPI directly will make it even more complex in the case of post 2.1 OpenGL so I recommend using GLFW.

Thankfully there are quite a few loader libraries, which do all the function pointer loading for you so you don't have to do it manually: http://www.opengl.org/wiki/OpenGL\_Loading\_Library
> 1 votes

# Answer
Use GLEW it does all the platform specific stuff linking what otherwise would you do manually. You also mustn't worry about compatibility, it generates you a list with all possible (and impossible sometimes :D) extensions. Here you are: http://glew.sourceforge.net/ :)
> 0 votes

# Answer
I recently started learning opengl myself, combined with SDL2; The only changes I needed to make to linking using CodeBlocks under win7 was to add ' -lopengl32 ' to my list.
> 0 votes

---
Tags: opengl, graphics, graphics-programming, windows, macos
---


# Question
Title: How can I use voice commands to control my Windows Phone game?
Is it possible to use simple voice commands like "run right", "run left", "jump", "stop", "attack", "defend", "finish" to control the player in a Windows Phone 8 game?

How can I implement voice recognition and some voice commands in my game?

# Answer
Yes, you can use voice commands in Windows Phone 8 applications. It's relatively straightforward, you need to create an XML file that maps spoken commands to actions (a VCD file) and then add the code to initialize the speech subsystem with your definitions file and handle the triggered actions. The definition file contains XML like:

```
<Command Name="RunDirection">
  <Example>Run right</Example>
  <ListenFor>Run {direction}</ListenFor>
  <Feedback>Running {direction}!</Feedback>
  <Navigate Target="/run.xaml"/>
</Command>

```

(Full reference for the XML schema is available here.)

You then call `InstallCommandSetsFromFileAsync` to register the commands file, and you accept commands via the `OnNavigatedTo` hander:

```
if (NavigationContext.QueryString.ContainsKey("voiceCommandName")) {
  var command = NavigationContext.QueryString["voiceCommandName"];
  if (command == "RunDirection") {
    var direction = NavigationContext.QueryString["direction"];

    m_player.SetDirection(direction); // ...or whatever.
  }
}

```

Far more complete overviews are available at the MSDN and via this MSDN magazine article.

Note that the system is *not* well suited to real-time iterative direction like you are suggesting; you invoke the voice commands by hitting the Start button, and saying something like ", run right" (although the prefix is optional).

Further, if the system fails to understand you it may come up with a disambiguation prompt, which will interrupt the action (this may be optional too, I haven't explored it deeply enough).

It's probably not a very good mechanism to control the actual gameplay, although you may be able to use it for things like showing high scores, starting a new game, and so on.
> 1 votes

# Answer
Yes, it's possible. First find a suitable voice recognition library or use the "built in" option. Then map commands from the voice recognition library to input commands in your game.

As for design implementation, you can look at an existing game, There came an echo. Implementing commands like "run right" or "jump" are likely going to be too challenging to use, since those types of commands are highly dependent on timing.
> 0 votes

---
Tags: c#, monogame, control, windows-phone-8, accessibility
---