# Question
Title: Does Direct3D have hardware-dependant extensions like OpenGL?
I am not familiar with Direct3D and I want to know if it has hardware and vendor dependant functions like the extensions in OpenGL?

A program written by a friend fails on certain computers while it runs perfectly on others. Also a simple program to get a list of supported extensions would be helpful (like `glGetString(GL_EXTENSIONS)` in OpenGL).

# Answer
> 2 votes
No, Direct3D doesn't have a functionality extension concept the same way OpenGL does.

* Direct3D 9 exposes device capabilities, which provide information about scalar or Boolean quantities related to feature support (such as "how many lights are supported" or "how many instructions can a vertex shader program contain").
* Direct3D 10 (and 10.1) provided firm guarantees about capabilities.
* Modern versions of Direct3D (11+) expose the concept of feature levels, which provide broad guarantees of certain functionality.

In a few rare cases, driver-specific workarounds or behavior can be triggered in D3D by passing otherwise invalid or undocumented parameters to certain Direct3D entry points. These are uncommon, usually not a good idea to rely on, and aren't made available for querying except by checking the hardware and driver versions. Similarly, a few pieces of hardware and/or a handful of drivers can play a bit fast and loose with their conformance to the D3D specification (whichever one they claim to support), but that's not really what you're looking for either.

While there are functions to query the above mechanisms, none of the mechanisms provide any way to introduce new entry points into the API or introduce entirely new functionality without versioning the API itself (which is what OpenGL's extension mechanism allows for).

In summary, there's no equivalent to `glGetString(GL_EXTENSIONS)` in Direct3D because there's no equivalent capability in the API. Your friend's program likely just has a legitimate bug of the variety that manifests as you describe (any number of things could be causing it).

---
Tags: opengl, directx
---


# Question
Title: Is it better to preserve scenes in memory or recreate them every time I need them?
I am using Cocos Builder to create scenes using `sceneWithNodeGraphFromFile:owner:`. Now I have doubts about whether it's better, on iOS, to save some memory or CPU cycles. In other words I have two options:

*First*, I could do lazy initialization of scenes without removing them from memory, like this:

```
- (CCScene*) myScene
{
    if(!_myScene)
        _myScene= [CCBReader sceneWithNodeGraphFromFile: @"MyFile.ccbi"];
    return _myScene;
}

```

Then I always call `self.myScene` and I possibly set `_myScene` to `nil` if the app receives a memory warning. I never remove a scene from the director, I just push without cleaning.

*Or*, I could initialize a new scene every time. I'd call *sceneWithNodeGraphFromFile:owner:* every time that I need to push a scene, popping and cleaning it from the director and creating it again if I need it.

Which should I prefer and why?

# Answer
> 1 votes
I'd advise that you prefer consuming memory to preserve CPU where possible. Keep scenes in memory as long as you can (or need to) to ensure a smooth transition experience for users. In other words, go with your first ("lazy loading") approach.

By preserving the scene, you also allow yourself to preserve any scene state as well, which means you can (if you want) return to them in the same state the user left them in, which can be desirable.

You should still obey iOS's requests to purge non-critical resources, so you'll want a lazy approach anyhow. Plus, especially on a mobile platform, high CPU utilization is likely to negatively impact battery life more than high memory utilization.

---
Tags: cocos2d-iphone, resource-management
---


# Question
Title: How do I determine a good path for 2D artillery projectiles?
I'm building a little "tank wars" game (like this one).

I understand the math, and I am able to define a parabola from the launcher to the objective I want to reach. The parabola depends on the projectile's initial angle and velocity. I don't really know how to find a good path that "fits" in the screen most of the time.

As an example: I started with a velocity of 100 in a level I created and the projectile was sent far far away upwards and took a long time to hit the target. On the other hand I would like to add some obstacles to each level for example a wall between both tanks with a hole in the middle where projectiles must fly through to damage the other tank.

Questions:

1. To get a valid path that mainly stays on screen, I think I could play with the maximum height of the projectile. How do I relate angle/initial velocity to maximum given height?
2. How can I make the computer tank scan obstacles on screen and find a path to the player? (For example, a wall with a hole in the center between them.)

# Answer
> 15 votes
If your AI has structured knowledge of the obstacles in the way (eg. it knows there is a wall in-between with a hole at vertical position holeY), then an analytic solution may be possible (ie. you drop your source, target, and gap coordinates into a function and get your launch velocity back out).

I'm going to assume that you need to solve a more general case though, where there could be *arbitrary geometry in the way*. As Arthur Wulf White has noted above, in this case your best bet is to **search through a family of potential parabolic trajectories, testing each one for collisions** with geometry, until you find one that works.

So, how do you describe this family of parabolas?

I wouldn't recommend parametrizing the family on the vertical velocity component. For each possible input, you'd have two possible trajectories (one that peaks before reaching the target, and hits the target before peaking). That means solving a quadratic every iteration of your search. For binary search we'd prefer a 1-to-1 mapping with simpler calculations each iteration, even if it means a little more work for setup.

When I've tackled this problem in past games, I've found it convenient to use the **duration of the projectile's flight - call it T**.

It may seem an odd choice, but for every choice of T there is a unique parabolic trajectory joining the source and target, and the math (though plenty ugly during set-up!) is neater per-iteration than using velocity directly.

It's also easy to map conceptually: `T = 0` represents the infinite-velocity straight line ray from source to target. Greater values of T represent increasingly tall (and indirect) arcs.

So, defining our knowns & unknownns:

```
Unknown
             T = the time of impact on our target, measured in seconds after launch
launchVelocity = the initial velocity of the projectile (vector)

Known
launchPosition = the initial position of the projectile (vector)
targetPosition = the position of the target at the time of firing (vector)
deltaP = targetPosition - launchPosition = the net travel of the projectile (vector)
  acceleration = the net acceleration (due to gravity, wind, etc) (vector)
          hMax = the ceiling height, we want to keep our projectile lower than this
  deltaH = hMax - launchPosition.y = the headroom we have above our firing spot

```

Next we'll want to establish the **range of our parameter T** to search through:

Your **minimum T** is the shortest/most direct flight possible:

```
float b1 = dot(deltaP, acceleration) + vMax*vMax;
float discriminant = b1*b1 - dot(a, a) * dot(deltaP, deltaP);
float T_min = sqrt((b1 - sqrt(discriminant)) * 2 / dot(acceleration, acceleration));

```

If `discriminant < 0`, that means the target is out of range and you can skip out early: no trajectory within our allowable speed can reach it.

Your **maximum T** is the least direct flight possible, shooting way up at maximum speed, so that the projectile eventually falls onto the target

```
// Limit due to launch power
float T_max = sqrt((b1 + sqrt(discriminant)) * 2 / dot(acceleration, acceleration));

```

But we might hit the ceiling first, so we have to account for the latest impact time that keeps us under that obstacle:

```
// Limit due to obstacles above.
float b2 = g * (2 * yMax - deltaY);
float T_ceiling = sqrt((
               (deltaP.y - 2.0f * deltaH)
              + 2.0f * sqrt(deltaH * (deltaH - deltaP.y))
            ) * 2.0f / acceleration.y);

T_max = min(T_max, T_ceiling); // Take the earlier / most limiting case.

```

One more T value that I've found useful is the **lowest-energy trajectory** (the one with the smallest initial velocity) - it has:

```
float T_lowEnergy = sqrt(sqrt(4.0 f * dot(deltaP, deltaP) / dot(acceleration, acceleration)));

```

This one's a good baseline for AI jumping. :)

Now **in each iteration** of your search, you'll pick a T value and test the resulting parabola. This step is much neater. **Calculate your launch velocity from T** using:

```
launchVelocity = deltaP/T - a * T/2.0f;

```

This works in any number of dimensions. In 2D, with `a = (0, -gravity)` it's equivalent to:

```
launchVelocity.x = (p_Target.x - pStart.x)/T - 0;
launchVelocity.y = (p_Target.y - pTarget.y)/T + gravity * T/2.0f;

```

For each trajectory in this range, you can test a set of line segments along the line...

$$\vec p(t) = \vec p\_0 + \vec v\_0 \cdot t + \frac {\vec a} 2 t^2$$

```
Vector position(float t) {
    return startPosition + launchVelocity * t + a * t*t/2.0f;
}

```

...to see if it collides with your terrain.

Here's a gif of the different trajectories we can form this way, as the target moves, bracketing the range of possible solutions:

T\_min = red, T\_lowEnergy = yellow, T\_max = green, ceiling = blue

If your terrain always consists of low obstacles and open sky, then as Arthur notes above you can use binary search on T between `T_min` and `T_max` until you find a viable (non-colliding) trajectory, or you hit an iteration limit and give up.

If you can have floating obstacles or a solid ceiling with stalactites, then you may do better to do a linear search - say starting at `T_lowEnergy` and expanding above & below in small steps until you hit `T_max` and `T_min`, respectively.

I hope that's useful, and that I haven't botched the math anywhere! :)

---

Here's a detailed derivation of these formulas:

First, we take our parametric equation for motion under constant acceleration, substitute \\$t = T\\$ so that our position is the target position \\$\vec p\_T\\$, and rearrange to isolate our initial velocity \\$\vec v\_0\\$:

$$ \begin{align} \vec p(t) &= \vec p\_0 + \vec v\_0 \cdot t + \frac {\vec a} 2 \cdot t^2 \\ \vec p\_T = \vec p(T) &= \vec p\_0 + \vec v\_0 \cdot T + \frac {\vec a} 2 \cdot T^2 \\ \vec v\_0 &= \frac 1 T \left( \vec p\_T - \vec p\_0 - \frac {\vec a} 2 \cdot T^2 \right) \\ \vec v\_0 &= \left( \frac{\vec {\Delta p}} T - \frac {\vec a} 2 \cdot T \right) \end{align}$$

Next we apply our constraint: our initial speed \\$ \begin{Vmatrix} \vec v\_0 \end{Vmatrix}\\$ mustn't exceed our max speed \\$v\_{max}\\$. At the limiting cases, the two are exactly equal, so we'll start with that equality then substitute the expression above...

$$\begin{align} \begin{Vmatrix}\vec v\_0\end{Vmatrix} &= v\_{max} \\ \vec v\_0 \cdot \vec v\_0 &= v\_{max}^2 \\ \frac 1 {T^2} \left( \vec{\Delta p} - \frac {\vec a} 2 T^2 \right) \cdot \left( \vec{\Delta p} - \frac {\vec a} 2 T^2 \right) &= v\_{max}^2 \\ \begin{Vmatrix}\vec {\Delta p}\end{Vmatrix}^2 - \left(\vec{\Delta p} \cdot \vec a \right) T^2 + \frac {\begin{Vmatrix} \vec a \end{Vmatrix}^2} 4 T^4 &= v\_{max}^2 T^2 \end{align}$$

This may look hairy, what with the fourth powers and all, but if we substitute \\$ u = T^2 \\$ and rearrange, we get a familiar-looking quadratic we can solve by the quadratic formula. :)

$$ \begin{array}{c|l} \frac {\begin{Vmatrix} \vec a \end{Vmatrix}^2} 4 u^2 + \left(-\vec{\Delta p} \cdot \vec a - v\_{max}^2\right) u + \begin{Vmatrix}\vec {\Delta p}\end{Vmatrix}^2 = 0 & A = \frac {\begin{Vmatrix} \vec a \end{Vmatrix}^2} 4 \\ \space & B = - \left(\vec{\Delta p} \cdot \vec a + v\_{max}^2\right) \\ \large {u = \frac {-B \pm \sqrt{B^2 - 4AC} } {2 A}} & C = \begin{Vmatrix}\vec {\Delta p}\end{Vmatrix}^2 \end{array} $$

And since \\$T\\$ is non-negative by definition, we can express it as:

$$T = \sqrt{\frac 2 {\begin{Vmatrix}a\end{Vmatrix}^2} \left( \left( \vec{\Delta p} \cdot \vec a + v\_{max}^2 \right) \pm \sqrt{\left( \vec{\Delta p} \cdot \vec a + v\_{max}^2 \right)^2 - \begin{Vmatrix}\vec {\Delta p}\end{Vmatrix}^2 \begin{Vmatrix}\vec a\end{Vmatrix}^2} \right) } $$

Here the inner negative gives us \\$T\_{min}\\$ and the positive gives us \\$T\_{max}\\$.

---

To find the limits due to our ceiling, \\$ h\_{max} \\$, we find the peak of our parabola by isolating the y axis and taking the derivative...

$$\begin{align} \vec p(t) &= \vec p\_0 + \vec v\_0 t + \frac {\vec a} 2 t^2 \\ p\_y(t) &= p\_{y\_0} + v\_{y\_0} t + \frac {a\_y} 2 t^2\\ \frac {\delta p\_y(t)} {\delta t} &= v\_{y\_0} + a\_y t \end{align}$$

At the time it hits its peak \\$t\_\*\\$, the derivative is equal to zero (flight levels off before falling), so we can substitute this time in to solve for the peak height of the parabola.

$$ \begin{align} \frac {d p\_y(t\_\*)} {d t} = v\_{y\_0} + a\_y t\_\* &= 0\\ t\_\* &= -\frac {v\_{y\_0}} {a\_y} \end{align} $$ $$\begin{align} h\_{max} &= p\_y(t\_\*) \\ h\_{max} &= p\_{y\_0} + v\_{y\_0} t\_\* + \frac {a\_y} 2 t\_\*^2 \\ h\_{max} &= p\_{y\_0} + v\_{y\_0}\left(-\frac{v\_{y\_0}}{a\_y}\right) + \frac{a\_y}2\left(-\frac{v\_{y\_0}}{a\_y}\right)^2 \\ h\_{max} - p\_{y\_0} &= -\frac{v\_{y\_0}^2}{a\_y}+ \frac{v\_{y\_0}^2}{2a\_y}\\ \Delta h &= -\frac {v\_{y\_0}^2} {2 a\_y} \end{align} $$

Substituting our formula for \\$v\_0 = \frac{ \vec {\Delta p}} T - \frac a 2 T\\$ lets us solve for the limiting time-to-target:

$$\begin{align} -2a\_y\Delta h & = \frac 1 {T^2} \left( \Delta p\_y - \frac {a\_y} 2 T^2 \right) \left( \Delta p\_y - \frac {a\_y} 2 T^2 \right) \\ -2a\_y\Delta h T^2 &= \Delta p\_y^2 - \Delta p\_y a\_y T^2 + \frac {a\_y^2} 4 T^4 \\ \frac {a\_y^2} 4 T^4 + a\_y\left(2\Delta h - \Delta p\_y \right) T^2 + \Delta p\_y &= 0 \end{align}$$

Which we can solve again using the quadratic formula as before. This time, we care about only the inner positive case. The inner negative corresponds to a trajectory where we hit our target before we have a chance to hit the ceiling anyway. ;)

$$ T\_{ceiling} = \sqrt{\frac 2 {a\_y} \left( \left(\Delta p\_y - 2\Delta h\ \right) + 2\sqrt{\Delta h^2 - \Delta h\Delta p\_y }\right)} $$

---

Lastly, to find the lowest-energy trajectory, we take the earlier expression for the square magnitude of the initial velocity as a function of \\$T\\$, and set its derivative equal to zero to locate its (unique) local minimum:

$$\begin{align} \begin{Vmatrix}\vec v\_0 \end{Vmatrix}^2 &= \frac {\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2} {T^2} - \left( \vec {\Delta p} \cdot \vec a \right) + \frac {\begin{Vmatrix}\vec a \end{Vmatrix}^2}4 T^2 \\ \frac { d \begin{Vmatrix}\vec v\_0 \end{Vmatrix}^2}{d T} &= -2 \frac {\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2} {T^3} - 0 + \frac {\begin{Vmatrix}\vec a \end{Vmatrix}^2}2 T \\ 0 &= -2 \frac {\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2} {T\_{low}^3} + \frac {\begin{Vmatrix}\vec a \end{Vmatrix}^2}2 T\_{low} \\ 0 &= -2\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2 + \frac {\begin{Vmatrix}\vec a \end{Vmatrix}^2}2 T\_{low}^4 \\ T\_{low}^4 &= \frac{4\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2}{\begin{Vmatrix}\vec a \end{Vmatrix}^2} \\ T\_{low} &= \sqrt\[4\]\frac{4\begin{Vmatrix}\vec {\Delta p} \end{Vmatrix}^2}{\begin{Vmatrix}\vec a \end{Vmatrix}^2} \end{align}$$

Somewhat magically, the time to hit a target with the least energy doesn't vary with the direction to the target, only the ratio of its distance away to the force of gravity.

---
Tags: physics, projectile-physics, aiming
---


# Question
Title: Why is my gameloop slightly faster than 60 per second?
Here is my gameloop (taken from http://www.koonsolo.com/news/dewitters-gameloop/) which is *supposed* to limit the game (logic) updates to 60 per seconds and render as fast as the device allows:

```
long nextGameTick = System.currentTimeMillis();
int loops;
final int maxFrameskip =5;
final int ticksPerSecond = 60;
final int skipTicks = 1000 / ticksPerSecond;
float dt = 1f/ticksPerSecond;
int ticks;
long secondCount;

onDrawFrame{

    //This loop will limit the logic update to defined value and render flat out
    loops = 0;

    while( System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){
        updateLogic();
        //Update nextGameTic by adding skipTicks value to it, ready for next comparison
        nextGameTick += skipTicks;
        //Update loops value ready for next comparison in while loop
        loops++;
        ticks++;
        }
        //Once thses conditions are no longer true, exit while loop and render
    render();

    if (System.currentTimeMillis()>secondCount+1000){
        Log.v("Blocks","Ticks this second:"+ticks);
        secondCount = 0;
        ticks=0;
        }
}

```

However, when I run this, I'm getting anywhere between 62 and 65 as you can see from my logcat output:

So, the loop doesn't do what it's supposed to.

# Answer
Your main problem is likely this:

```
final int skipTicks = 1000 / ticksPerSecond;

```

Dividing an int by an int returns an int (the value is rounded down if needed), so `skipTicks` evaluates to 16. 1000 / 16 is 62.5 so you get around this many ticks per second.

To solve this the easiest solution would be to use a `millisecondsPerTick` variable (what you are calling `skipTicks` now) instead of `ticksPerSecond` and `skipTicks`, which would be an int. If you still need to find your ticks per second it is `1000d / millisecondsPerTick`.

If you want to continue defining your tick length in ticks per second for whatever reason, you could try something like this:

```
double timeCorrection;

while( System.currentTimeMillis() > nextGameTick && loops < maxFrameskip){
    nextGameTick += skipTicks;
    timeCorrection += (1000d / ticksPerSecond) % 1;
    nextGameTick += timeCorrection;
    timeCorrection %= 1;
    //update tick...
}

```

Although this isn't guaranteed to result in 60 ticks per second it will be closer than what you currently have. If `updateLogic()` often takes longer than the length of a tick then you may get less than the amount of ticks you want per second. The precision of `System.currentTimeMillis()` also varies between machines and could affect your ticks per second, or the time between two ticks.

In either case I would change `skipTicks` to `millisecondsPerTick` because I think it better describes the variable.
> 19 votes

# Answer
Alex's answer seems sufficient, but you say you want more detail, so here goes.

First, why does the gameloop from http://www.koonsolo.com/news/dewitters-gameloop/ deliver its desired frame rate while your version doesn't? Because their integer division works out exactly:

```
const int FRAMES_PER_SECOND = 25;
const int SKIP_TICKS = 1000 / FRAMES_PER_SECOND;

```

SKIP\_TICKS is 40 (with no rounding). With increments of 40 msec, you get exactly 25 intervals in 1 second.

Your

```
final int ticksPerSecond = 60;
final int skipTicks = 1000 / ticksPerSecond;

```

has 1000 / 60 = 16.66667 but is truncated to 16 in integer division. So instead of 16.66667 msec increments you're getting 16.0 msec. This is about a 4% error. There are 62 full intervals of 16 msec in 1 second, plus a leftover 8 msec. (62 * 16 = 992 msec) So I would expect you'd get a mix of 62 fps or 63 fps, about 50% each.

But you're seeing higher tick counts, 63-64 (maybe up to 65 as your question states). What's going on? I suspect the problem is that you're using a low resolution system timer that is too close to the computer's own basic system timer. They aren't accurate (or repeatable) when timing intervals are too near the basic system timer interval. For a discussion see

http://www.java-gaming.org/index.php?topic=1329.0

where the first sentence states "There are significant flaws in the millisecond timer that ships with the normal JDK." That message also points to a high resolution timer article and library that provides accurate timer resloution down to fractional msec.

http://www.javaworld.com/article/2077327/core-java/my-kingdom-for-a-good-timer.html

Those links are old, and I don't know the state of Java timers today, but the approach remains the same. If you want precise and repeatable msec-range timing, use a high resolution timer and, along the way, stop doing integer math where the rounding error is anywhere near 4%.
> 7 votes

---
Tags: game-loop, timestep
---


# Question
Title: How do I use an external FBX object in Unity?
Is it possible to use an external `.fbx` object in Unity 3D the same way we can insert a picture?

Something like `myPath = "http://www.myserver.com/object/myobject.fbx";`?

# Answer
> 3 votes
To load up a 3D model in `run time` from a server, you need to use `AssetBundles`. You create an AssetBundle and upload it to a server. You can then download that AssetBundle with the unity WWW class.

There is a another way to do it, which is suggested here. In this solution you read the text file construct the model from that. Very difficult and time consuming.

---
Tags: unity, networking, fbx
---


title: How do I make a cube move by rolling?

text:
# Question
Title: How do I make a cube move by rolling?
I am learning jMonkeyEngine by making some small games with it. I have a simple rectangular cube that I want the player to be able to roll around the game world.

When he presses the arrow keys, the cube should make a roll in the direction of the key press. (So, for instance, pressing the right arrow key makes the cube roll 1 WU to the right.)

The problem isn't how to move the cube (I can do that with the `move()` method), but with how to make this rotation effect so it doesn’t look like the cube is moving to the destination, but is actually rolling.

The rolling effect should be like the cube in *Bloxorz*. (Here's a gameplay video.)

**UPDATE**

After I got some good help below, I have come up with a test solution, which I want to share with you.

```
Box box1 = new Box(1,1,1);
Geometry boxGeom = new Geometry("Box", box1);
Material mat1 = new Material(assetManager, "Common/MatDefs/Misc/Unshaded.j3md");
mat1.setColor("Color", ColorRGBA.Blue);
boxGeom.setMaterial(mat1);

//attach the cube to the pivot node
pivot = new Node("pivot");
pivot.setLocalTranslation(0.0f, 0.0f, 0.0f);
rootNode.attachChild(pivot); // put this node in the scene

pivot.attachChild(boxGeom);

//Translate the box so the pivot node is at the bottom right edge of the box
boxGeom.move(-1.0f, 1.0f, 0.0f);

```

And then rotate it like this.

```
@Override
public void simpleUpdate(float tpf) {
    //rotate along z-axis
    pivot.rotate(0.0f, 0.0f, -0.001f);
}

```

# Answer
Conceptually, you can do that by animating the rotation of the cube (or as in *Bloxorz*, a *cuboid*) 90 degrees around one of its edges. You don't need `move()` at all!

Side-on view of one rotation:

Here's a seriously good *JMonkeyEngine* tutorial showing you how to rotate `Box`es around pivot `Node`s. It explains everything step-by-step. These are the important lines:

```
/** Create a pivot node at (0,0,0) and attach it to the root node */
Node pivot = new Node("pivot");
rootNode.attachChild(pivot);

/** Attach your cuboid to the *pivot* node. (And transitively to the root node.) */
pivot.attachChild(yourCuboid);
/** Rotate the pivot node: This rotates everything attached to it! */
pivot.rotate(.4f, .4f, 0f);

```

Once you've got that, *rolling around* becomes successive rotations around different pivots:
> 8 votes

---
Tags: java, physics, rotation, movement, jmonkeyengine
---


# Question
Title: From Position/Target to Orientation/Elevation
I have an orbit camera class that calculates the camera position from Orientation/Elevation and distance from target. I decided to replace these initial values for the camera instantiation with simply Vector3's position and target. How do I calculate Orientation/Elevation and distance from target from these two vectors?

I only got as far as creating a Matrix (Matrix.LookAt) and decomposing it. The translation that can be used for the distance from target partition is trivial, but what do I do with the Quaternion portion to get the elevation/orientation?

# Answer
> 4 votes
Assuming Z is the vertical axis, the orientation in the XY plane can be computed using `atan2`:

```
float dx = target.x - position.x;
float dy = target.y - position.y;

yaw = atan2(dy, dx);

```

And same for the elevation angle:

```
float dz = target.z - position.z;

pitch = atan2(dz, sqrt(dx * dx + dy * dy));

```

---
Tags: sharpdx
---


# Question
Title: Mismatch cordinate system of unity and android
I am new to unity3d, Right now i am adding a cube as game object with coordinate 0,0,0 But when i run it on android device Iam facing 2 problem a) Coordinate system of unity3d are different from coordinate system of device, For device top left is 0,0 but for unity center of the screen is 0,0. How to fix that mismatch or i need to multiply with some factor to make it work.

b) Iam moving the object on x-axis this is what iam doing for moving object on x-axis

```
if(xback){
     xaxis+=(2*Time.deltaTime);
     if(xaxis >Screen.width/2){
      xback = false;
      }
     }
else if(!xback){
     xaxis-=(2*Time.deltaTime);
     if(xaxis<=-(Screen.width/2)){
      xback = true;
  }
 }

Vector2 temp = transform.position;
temp.x = xaxis;
temp.y = yaxis;
transform.position = temp;

```

But the problem iam facing is as soon as my xaxis equals 9 it touches the right of screen and then it get out of screen, so iam little bit confuse is unity3d pixel system is different from the one on device, because iam moving the cube by one pixel every time but movement is not equal to 1 pixel of device. so i want to know is pixel system of unity is different from pixel system of android or iam doing something wrong.

# Answer
Unity (or any other 3D engine i believe) is not using pixels for positioning objects in space (maybe mostly because there is no Z axis in pixels and also because it brings thousands of other issues)

Unity uses Unit system (i personally see it as metric) you should take the unit cube as one meter, this means few things :

* The pixel you see on screen cannot be naturally matched to Unity coordinates (and vice versa)
* You need to calculate the report screen to World and World to Screen to find out those relatives positions
* Gladly Unity has a function for you which do the job : Camera.ScreenToWorldPoint

And also those :
> 3 votes

---
Tags: android, unity, coordinates
---


title: Drawing .mtl files in Directx

text:
# Question
Title: Drawing .mtl files in Directx
So I've created my own obj loader and it loads normal's, UV's, vertices, indices and faces.. but it will only draw the whole obj a single color. I would like my loader to display the model as if it were in blender. So my question is how do i use the material file to give my model its "color".. the material file doesn't say very much nor anything i find useful, soooo do i have more work to do to create a texture out of each side or?... any help is appreciated.

# Answer
> 1 votes
Typical use-case would be to write a Blinn-Phong shader and use .mtl's ambient, diffuse and specular values there. .mtl also gives you the texture file name.

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


title: Shimmering, scrolling/panning a texture

text:
# Question
Title: Shimmering, scrolling/panning a texture
**Shimmering**

I understand shimmering in textures is caused by sub-pixel accuracy aliasing against the regular grid of pixels on the screen when drawn. I have a good example of it here, whereby I'm attempting to scroll/pan a 2d texture by modifying the texture coordinates rather than by moving some actual geometry. The texture is "wrapped" and my idea was to fill in the bit falling off the left (or right), filling it in on the other side, to effect a single scrolling/panning surface of (almost) infinite size.

Unfortunately with random noise on the texture, when I'm zoomed all the way out the shimmering is kind-of horrific. When I zoom in a bit it seems OK, which is kind-of confusing to me.

But anyway, is there a filter of some kind I can put into my shader to prevent this shimmering? I'm at something of a loss here.

(To complicate matters my texture is actually just L16 luminance and I'm palettising it in the shader - the L16 is sampled with LINEAR, the palette texture is POINT, though I'm pretty sure this makes little difference to the shimmering).

Please note that with the video, YouTube has done its absolute best to remove any detail from it, meaning it's difficult to see the shimmer under the encoding artifacts.

# Answer
> 1 votes
The standard solution to this type of texture shimmer in games is mipmapping.

When you are zoomed out far enough that the source texels are smaller than your screen pixels, you start rendering from a scaled-down version of the source, which has had this excess high-frequency detail removed.

You can cover the transition with trilinear filtering, so the excess detail fades out smoothly instead of popping. (If your view is orthographic as in the example vid, then you shouldn't need anisotropic filtering)

GPUs support mipmapped textures natively, although I'd need to know a bit more about the environment you're working in to describe exactly how to enable them.

Using mipmaps also has performance benefits due to being friendlier on the texture cache.

---
Tags: textures, antialiasing
---


title: Mega Man screen scrolling in JavaScript

text:
# Question
Title: Mega Man screen scrolling in JavaScript
I'm trying to create screen transitions similar to those found in Mega Man or Legend of Zelda (i.e. the active elements of the first screen are stopped as the screen scrolls in the direction of the new screen then the active elements of the new screen become active again). I'm making this for a 2D browser game written in JavaScript.
Right now, I can only make the screen scroll as long as the player remains on the edge of the screen; the player can still move when the transition is taking place, which stops the scrolling midway through transition. Below is the code I'm using to make this happen. If anyone can help me with this, I would really appreciate it.

```
//checks if player has touched right side of screen
//*used to change screen color
if(this.rightX == gameWidth){
    screenShift = true;
    if(bgDrawX2 > 600){
        bgDrawX-=5;
        bgDrawX2-=5;
        drawBg();
    }
    screenShift = false;
}

if(this.leftX == 0){
    screenShift = true;
    if(bgDrawX2 < 1200){
        bgDrawX+=5;
        bgDrawX2+=5;
        drawBg();
    }
    screenShift = false;
}

```

# Answer
I don't know most of your code but, apparently you have already a global variabel to hold the scrolling-state (screenShift). Why not simply ignore all incoming key/control-events until the variable screenShift is false again?
> 1 votes

# Answer
The way that I solved this in Hikari (a Mega Man clone) is by using different game "substates" and triggers to start the transitions.

There are triggers, called "transition regions" which sit at the sides of each room where the player can transition to another room. When the player enters the region, the game substate is set to "transitioning".

When the "transitioning" state is entered, all of the enemies in the current room are removed and the player controls are disabled. The transition takes place, moving the player and the camera into the next room. After the transition finishes, new enemies are spawned and the player's controls are restored.

Here's some pseudo C++-style code that describes the basic flow I'm using:

```
class SubState {
  void enter();
  void update(dt);
  void exit();
}

class TransitionSubState : public SubState {
  void enter() {
    // 1) Remove all enemies
    // 2) Disable player controls
  }

  void update(dt) {
    // 1) Move the camera and the player into the new room
    // 2) Check to see if we're done

    if(in new room) {
      exit();
      // Set the substate back to something else, we're done transitioning
    }
  }

  void exit() {
    // 1) Restore player controls
    // 2) Spawn enemies in the new room
  }
}

```

This can all be implemented in JavaScript as well. The key is that you have some kind of `enter`/`update`/`exit` set of functions you call to complete the lifecycle of the transition.

The code in Hikari is actually a bit more complex, but at a high level that same thing is happening.
> 1 votes

---
Tags: 2d, javascript
---


# Question
Title: Compare world space distance to shadow map depth
I am rendering shadow maps to cubemaps (just rendering raw depth buffer) then projecting them to the scene to do omni-directional shadow mapping.
The cubemap is sampled by the light direction vector on each fragment:

```
float3 lightvector = pos3D.xyz-lightPos.xyz;
float shadowmap = xTextureSh.Sample(Sampler,lightvector).r;

```

If I compare the shadowmap value to the lightvector length which is the distance from the fragment to the light, I get wrong results because that distance is in world space units, whereas the shadowmap values are not, they are normalized values.
My question is, how could I normalize the length of the light vector the same way the shadow map is normalized? I don't access the shadow view matrix in the fragment shader to do a W division on it, because I would need to send 6 matrices there and I switched to cubemaps exactly to avoid that. I do know hovewer the far clip distance to the shadow cameras, if it counts.
Previously I tried to multiply the shadow map value with the camera far clip distance reading this presentation (on the 30th page), but had no luck. What am I missing?

# Answer
I couldn't find a way to do this, I write the distance instead in SV\_DEPTH so I can compare the values. It requires a few additional constants so it is not as nice as I wanted it to be, so I am still interested in case anyone could solve this an other way.
> 1 votes

---
Tags: directx, hlsl, shadow-mapping
---


# Question
Title: Getting sprites to move exactly the same on different devices
**Background**

When moving a sprite along the X axis, this is my code:

```
spriteXReal = spriteXReal + (spriteXVel * dt);  //.5 would be halfway point of, 1 would be right hand side screen etc...
spriteXScreen=spriteXReal*deviceWidth;

```

And the spriteXVel value above is worked out as:

```
spriteXVel = 1/spriteXTime;

```

So I would set **spriteXTime** to 10 if I wanted my sprite to work it's way across the screen in 10 seconds.

My code:

* Uses a fixed delta time
* Has tics per second capped at 60 (so my delta is 1/60)

**The issue**

This is great and works well, however, I am getting odd results when running on a different device (with a different screen res).

When comparing the 2 devices (simply by starting the game on both devices at the exact same time, they are *almost* identical save for a tiny difference in speed.

The game world is tile based. Let's say the play area on my development device is 16 tiles wide. 16 tiles fit perfectly onto this device So, if I'm moving between 8 tiles, I'm effectively crossing 1/2 of the screen.

Initially, the sprite appears to move the same on both devices, (going back and forth between say the 1st 'proper' tile and the 8th 'proper' tile), but after about 25 seconds, they are clearly out of sync.

On this device, the tiles would look something like this:

So, I'm working out my sprite movement using the device's width as above.

However, if the tiles don't fit exactly, I'm centering the original tiles and adding 'padding' tiles to the play-area like so:

Therefore, my confusion lies in how I should be working out my sprite's new position. because, now 8 tiles is actually *less* than 1/2 of the device's screen. So should I still be using the code above or something like this:

spriteXScreen=spriteXReal\*(Block18X - Block2X);

I have actually tried both and when I did, the problem was still evident, so I'm not sure which one I'm *supposed* to be using.

What is really odd is that when I set my sprite's Time variable to certain amounts, it appears that everything stays in perfect sync between these 2 devices so I'm completely stumped - that's what I've observed thus far anyway. I'm going to test that theory a bit more.

What else could be causing this discrepancy?!

Really appreciate some help with this one!

**Edit**

I've pretty much tried everything I can, I've even tried implementing a very simple 'test' game loop that updates sprite positions once every second, and put the two devices side by side, however, the Samsung Galaxy Ace **Always** runs ahead of the Google tablet, is it possible that System.CurrentTimeMillis(); is actually running faster on the Ace than on the tablet?

# Answer
> 0 votes
The problem was actually when my sprites were turning around between their boundaries.

I was using their int positions (their physical pixels positions *after* they had been converted from their float positions) which wasn't very accurate. Therefore, on one device a sprite may not have reached the boundary and turn around where on the other device the sprite hasn't even reached it's boundary.

I got around this by using it's float position (spriteXReal) and setting it's boundary's to float values too then comparing the two.

After doing this everything appears (at least devices to run perfectly in sync).

# Answer
> 0 votes
You've got the right idea of using a normalized coordinate (namely, `spriteXReal`). However, you're still coupling it to the screen size.

What you should be doing is expressing every position in terms of a common unit. In your case, a unit square could be a tile. Letting a unit equal a meter also vastly simplifies physics code.

When you go to render, you have to convert your basic units into pixels. You might want to make each tile 50x50 pixels large when rendered, so you just multiply the position in units by 50 to get the position in pixels (you can then add an offset for scrolling).

# Answer
> 0 votes
You should use a deterministic physics approach, where floating points, all the data types would be integrated in the way that are always certainly work in every CPU Architecture.

---
Tags: sprites, movement, fixed-timestep, scale
---


# Question
Title: UV interpolation is wrong with a wide FOV
How should I take FOV into account when interpolating UV coordinates? This picture shows the result today. Everything works fine with a narrow fov, but when I make it really wide, things deviate. The black line is expected to be straight. I'm writing a software renderer myself, so I can't just invoke some OpenGL function. Any advice is appreciated.

https://bitbucket.org/jevring/threedee

# Answer
> 8 votes
UV interpolation needs to take into account the depth of the vertices.

You need to perform perspective-correct interpolation, which involves dividing by the w coordinate of the interpolated homogeneous vector.

The "folded plane" effect of affine interpolation becomes more pronounced at wide FOV or when the camera is close to an object, but it's not caused by the wide FOV itself. It's just that narrow views approximate an orthographic camera, which doesn't need perspective correction since it doesn't experience perspective.

Wikipedia gives an equivalent formulation without homogeneous coordinates. if the endpoints you're interpolating have coordinates u\_0 and u\_1, and an interpolation factor a, then your interpolated u\_a lies at

for affine texture mapping,

which becomes

for perspective-correct mapping,

where z\_0 and z\_1 are the distances of the endpoints from the viewer, along the axis perpendicular to the image plane.

---
Tags: textures, uv-mapping, software-rendering
---


# Question
Title: How to debug DXGI_ERROR_INVALID_CALL errors?
I am developping an application using SharpDX and on one of my machines the call

```
_swapChain = new SwapChain(factory, _device, desc);

```

fails with the error message

> HRESULT: \[0x887A0001\], Module: \[SharpDX.DXGI\], ApiCode: \[DXGI\_ERROR\_INVALID\_CALL/InvalidCall\], Message: Unknown

When I googled the error I found this where it states:

> DXGI\_ERROR\_INVALID\_CALL (0x887A0001)
>
> The application provided invalid parameter data; this **must be debugged** and fixed before the application is released.

But how?

The error message does not give me any indication whatsoever to *why* the creation failed.

I checked the debug layer output but that only shows Info. No Warning, no Error, nothing. The factory and the device are created just fine and I tried several combinations of parameters in my SwapChainDescription but the error always remains the same.

How am I supposed to find out what triggers the error?

Just to be clear: I am not so much looking for a solution for my specific problem as I am wondering how I would go about debugging such a problem in general.

This is the boiled down code:

```
const int MAXFPS = 60;
const Format PIXELFORMAT = Format.R8G8B8A8_UNorm;

// Create device
_device = new Device(DriverType.Hardware, DeviceCreationFlags.None); // Or DeviceCreationFlags.Debug

// SwapChain description
var desc = new SwapChainDescription()
{
    BufferCount = 2, // I tried 1 too
    ModeDescription = new ModeDescription(_renderSize.Width, _renderSize.Height,
                                          new Rational(MAXFPS, 1), PIXELFORMAT),
    IsWindowed = true,
    OutputHandle = _hwnd,
    SampleDescription = _samples,
    SwapEffect = SwapEffect.Discard,
    Usage = Usage.RenderTargetOutput
};

// Create SwapChain
var factory = new SharpDX.DXGI.Factory();
_swapChain = new SwapChain(factory, _device, desc);

```

I confirmed the sample description is valid using

```
_device.CheckMultisampleQualityLevels(PIXELFORMAT, _samples.Count) > _samples.Quality

```

(though, those are 1 and 0 anyway), that the format is supported using

```
_device.CheckFormatSupport(PIXELFORMAT).HasFlag(FormatSupport.RenderTarget)

```

and also checked that

```
_hwnd != IntPtr.Zero
_renderSize.Width > 0
_renderSize.Height > 0

```

What else to check?

---

**Update:** I was able to fix the problem following the advice from here:

I changed this

```
Device device = new Device(DriverType.Hardware, DeviceCreationFlags.None);
Factory factory = new Factory();
SwapChain swapChain = new SwapChain(factory, device, desc);

```

to

```
Factory factory = new Factory();
var adapter = factory.GetAdapter(0);
Device device = new Device(adapter, DeviceCreationFlags.None);
SwapChain swapChain = new SwapChain(factory, device, desc);

```

# Answer
This typically happens when calling a D3D function with an invalid parameter (e.g. a NULL pointer where not permitted). This is exactly what the SwapChain's constructor documentation says:

> `InvalidCallException` The method call is invalid. For example, a method's parameter might contain an invalid value.

You need to check one by one the parameters you provide to this function, especially in this case you need to check that the present parameters you provide are correct (see the C++ doc for those, it's providing lots of details).

In your case, as it's failing on one specific machine, you're probably asking for stuff that isn't supported by its hardware, e.g. a D3D feature level too high for the graphics chip.

It sometimes help to check the samples provided by Microsoft to check what parameters they're passing, and see the differences that could cause the issue.
> 2 votes

---
Tags: c#, directx11, sharpdx
---


# Question
Title: Shadow mapping does not work correctly using GLSL shaders
I'm a beginner in shadow mapping. I have in my scene two meshes : a cube and a floor. The scene is lighted by a single point light.

Here's for the following display the light properties :

```
lightFrustrum->setFovy(70.0f);
lightFrustrum->setAspectRatio(500.0f/500.0f);
lightFrustrum->setNearClipDistance(0.1f);
lightFrustrum->setFarClipDistance(1000.0f);
lightFrustrum->setPosition(glm::vec4(-20.0f, 10.0f, 0.0f, 1.0f));
lightFrustrum->setOrientation(glm::vec3(1.0f, -1.0f, 0.0f));
lightFrustrum->setUpVectorDirection(glm::vec3(0.0f, 1.0f, 0.0f));

```

And the depth texture dimensions :

```
width = 512
height = 512

```

And the code to load the depth texture :

```
GLfloat border[] = {1.0f, 1.0f, 1.0f,1.0f};

glGenTextures(1, &this->m_TextId);
glBindTexture(GL_TEXTURE_2D, this->m_TextId);

glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24,
    this->m_Width, this->m_Height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_BYTE, NULL);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LESS);

glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, 0);

```

But I have the strange display like below :

As you can see, there's two problems : there's on the bottom of the screen a black strip. And on the left of the correct shadow, there's an other smallest one which should not be here either.

Now if I put the light just above the cube at 0.0f, 15.0f, 0.0f with the same depth texture propertiesI have the following result :

And now the same light properties but a depth texture with a width and a height of 64.

The shadow seems to be correct now but if I keep the same depth texture properties but I put the light at position -20.0f, 15.0f, 0.0f like in the first case it looks like the first case but this time without the line strip on the bottom.

Here's in the vertex shader for the first pass (depth texture creation):

```
#version 400

layout (location = 0) in vec3 VertexPosition;

uniform mat4 MVP;

void main(void)
{
    gl_Position = MVP * vec4(VertexPosition, 1.0f);
}

```

The vertex shader for the second pass :

```
#version 400

layout (location = 0) in vec3 VertexPosition;
layout (location = 1) in vec3 VertexNormal;
layout (location = 2) in vec2 VertexTexture;

uniform mat3 NormalMatrix;
uniform mat4 ModelViewMatrix;
uniform mat4 MVP;
uniform mat4 ShadowMatrix;

out vec3 Position;
out vec3 Normal;
out vec2 TexCoords;
out vec4 ShadowCoords;

void main(void)
{
    TexCoords = VertexTexture;
    Normal = normalize(NormalMatrix * VertexNormal);
    Position = vec3(ModelViewMatrix * vec4(VertexPosition, 1.0f)).xyz;
    ShadowCoords = ShadowMatrix * vec4(VertexPosition,1.0);
    gl_Position = MVP * vec4(VertexPosition, 1.0f);
}

```

And the fragment shader for the second pass :

```
#version 400

in vec3 Position;
in vec3 Normal;
in vec2 TexCoords;
in vec4 ShadowCoords;

layout (location = 0) out vec4 FragColor;

uniform sampler2D Tex1;
uniform sampler2DShadow ShadowMap;
uniform int lightCount;

struct PointLight
{
    vec4 Position;
    vec3 La, Ld, Ls;
    float Kc, Kl, Kq;
};

struct Material
{
    vec3 Ka, Kd, Ks, Ke;
    float Shininess;
};

uniform PointLight LightInfos[10];
uniform Material MaterialInfos;

vec3 Basic_ADS_Phong_Shading(int idx, vec3 normal, vec3 lightDir)
{
    vec3 reflectDir = reflect(-lightDir, normal);
    vec3 viewDir = normalize(-Position.xyz);

    vec3 Ambient = LightInfos[idx].La * MaterialInfos.Ka;
    vec3 Diffuse = LightInfos[idx].Ld * MaterialInfos.Kd * max(dot(lightDir, normal), 0.0f);
    vec3 Specular = LightInfos[idx].Ls * MaterialInfos.Ks * pow(max(dot(reflectDir, viewDir), 0.0f), MaterialInfos.Shininess);
    vec3 Emissive = MaterialInfos.Ke;

    return (Ambient + Diffuse + Specular + Emissive);
}

vec3 getLightIntensity(void)
{
    vec3 LightIntensity = vec3(0.0f);

    for (int idx = 0; idx < lightCount; idx++)
    {
        vec3 tnorm = (gl_FrontFacing ? -normalize(Normal) : normalize(Normal));
        vec3 lightDirNorm = vec3(0.0f);

        if (LightInfos[idx].Position.w == 0.0f)
            lightDirNorm = normalize(vec3(LightInfos[idx].Position));
        else if (LightInfos[idx].Position.w == 1.0f)
        {
            vec3 lightDir = vec3(LightInfos[idx].Position) - Position;
            lightDirNorm = normalize(lightDir);
            LightIntensity = Basic_ADS_Phong_Shading(idx, -tnorm, lightDirNorm);
        }
    }
    return (LightIntensity);
}

void main(void)
{
    vec4 Ambient = vec4(LightInfos[0].La * MaterialInfos.Ka, 1.0f);
    vec4 LightIntensity = vec4(getLightIntensity(), 1.0f);

    vec4 TexColor = texture(Tex1, TexCoords);
    float shadow = textureProj(ShadowMap, ShadowCoords);

    if (TexColor != 0)
        FragColor = LightIntensity * TexColor * shadow + Ambient * TexColor;
    else
        FragColor = LightIntensity * shadow + Ambient;
}

```

So I really lost in front of this situation. Does anyone have had the same problem using shadow mapping ? Thanks a lot in advance for your help.

# Answer
1. You should set your far plane to infinity for shadows, instead of setting a far clip distance of 1000.
2. Also, for a ratio of far/near of 1000.0/0.1 you would get better precision with a far plane at infinity anyway. Check this paper out http://www.geometry.caltech.edu/pubs/UD12.pdf ("3 - Projection Matrix Precision").
> 4 votes

---
Tags: opengl, shaders, glsl, shadows, shadow-mapping
---


title: Unity: Flip Sprite Direction

text:
# Question
Title: Unity: Flip Sprite Direction
I'm toying around with the new Sprite class in Unity, and I'm trying to work out how to change the direction the sprite is facing ("flip" it). I'm sure I can most likely just scale it across the x axis by -1, but I'd just like to know if there's a new, "official" way of doing it with Sprite or SpriteRenderer. Thanks!

# Answer
> 8 votes
Looks like the "official" way is to just invert the scale across the x axis. (That's how it's done in the 2D project example, so I think it's safe to assume there's no fancier way of doing it.)

# Answer
> 4 votes
You should aim to keep the scale of your "containers" like the root of the character at (1,1,1). So I recommend having the sprite as a child of the gameobject, you don't want changing the scale of the sprite affecting the collider for example. Then flip the scale of that child.

# Answer
> 1 votes
Like others said, you can flip the x value of the local scale:

```
var direction = 1; //  or -1, depending which way you want the sprite pointing.

// Sets the local scale of the current GameObject
transform.localScale = new Vector3(direction, 1, 1);

```

(Try flipping the y value too!)

# Answer
> 0 votes
Per the Unity 4.3 - 2D Game Walkthrough at about 8:15, their implementation of the Flip() function to reverse the character sets the x scale to -1

---
Tags: unity, sprites
---


# Question
Title: Using gluUnProject to transform mouse position to world coordinates (LWJGL)?
I am programming on a LWJGL project and have been trying to figure out how to successfully use the GLU.*gluUnProject* function in order to transform a given point on the screen (mouse position) to world coordinates. I found several examples on Google and really tried hard to get it to work. I do manage to get a result vector but the values it gives me make no sense.

I initialize my scene using GL11.*glFrustum*(...) as follows:

```
public void initialize()
{
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glFrustum(-0.5, 0.5, -0.5, 0.5, 1.5, 6.5);
// left, right, bottom, top, zNear, zFar

GL11.glMatrixMode(GL11.GL_MODELVIEW);
GL11.glLoadIdentity();

GL11.glTexEnvi(GL11.GL_TEXTURE_ENV, GL11.GL_TEXTURE_ENV_MODE, GL11.GL_REPLACE);
}

```

The window has a size of 800 x 600. Here is a screenshot:

Now to find a corresponding point in the game world for a given mouse position on the screen I use the following method:

```
public void calcWorldCoordinates(float mouseX, float mouseY)
// mouseX is in the range of [0..800] and mouseY in [0..600]
{
FloatBuffer model = BufferUtils.createFloatBuffer(16);
FloatBuffer projection = BufferUtils.createFloatBuffer(16);
IntBuffer viewport = BufferUtils.createIntBuffer(16);

GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, model);
GL11.glGetFloat(GL11.GL_PROJECTION_MATRIX, projection);
GL11.glGetInteger(GL11.GL_VIEWPORT, viewport);

float viewportHeight = viewport.get(3); // = 600.0f
float y = viewportHeight - mouseY;

FloatBuffer posNear = BufferUtils.createFloatBuffer(16);
FloatBuffer posFar = BufferUtils.createFloatBuffer(16);

GLU.gluUnProject(mouseX, y, -1.5f, model, projection, viewport, posNear);
GLU.gluUnProject(mouseX, y, -6.5f, model, projection, viewport, posFar);

// ...
}

```

For mouseX = 300, mouseY = 400 I receive:

> posNear = \[x=-0.0580, y=0.0774, z=-0.6964\]
> posFar = \[x=-0.0208, y=0.0278, z=-0.6964\]

None of the three resulting coordinates makes sense to me. As far as I can tell x should be somewhere around 240 (each tile in the scene is of size 120 x 80 pixels). It should definitely be positive though and not -0.0580 or -0.0208.

I also looked at the model and projection matrix as well as the viewport size. Those are:

> model:
> 1.0, 0.0, 0.0, 0.0
> 0.0, 1.0, 0.0, 0.0
> 0.0, 0.0, 1.0, 0.0
> 0.0, 0.0, 0.0, 1.0
> projection:
> 3.0, 0.0, 0.0, 0.0
> 0.0, 3.0, 0.0, 0.0
> 0.0, 0.0, -1.6, -1.0
> 0.0, 0.0, -3.9, 0.0
> viewport: 0, 0, 800, 600

I rewrote the code several times using different implementations of other people but could not get it to work. Maybe somebody could give me a hint. What I am doing wrong?

# Answer
```
gluUnProject(float winx, float winy, float winz, FloatBuffer modelMatrix,
    FloatBuffer projMatrix, IntBuffer viewport, FloatBuffer obj_pos)

```

`winx` ,`winy` and `winz` are the screen coordinates which you want to transform back to world coordinates.

`winx` and `winy` are in this case the x and y coordinates of the mouse as returned from `Mouse.getX()` and `Mouse.getY()`. In your example you have these lines:

```
float viewportHeight = viewport.get(3);
float y = viewportHeight - mouseY;

```

The reason you may see this in tutorials is that in Windows the origin used for mouse coordinates is the top left corner of the display while openGL uses the bottom left corner, so these lines are needed to transform the Windows mouse coordinates to openGL coordinates. However LWJGL already does this for us as the origin used for `Mouse.getY()` and `Mouse.getX()` is the bottom left corner, so this is not needed.

`winz` is the depth into the screen of the point that you want to transform back to world coordinates. The near clip plane is at z=0 and the far clip plane is at z=1. If you want the depth of the object that you clicked on, (in order to find its world coordinates), you can use `glReadPixels` like this:

```
FloatBuffer z = BufferUtils.createFloatBuffer(1);
glReadPixels(x, y, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, z);

```

which reads the depth of the pixel at `x`, `y` (`Mouse.getX()`, `Mouse.getY()` in this case) from the depth buffer and stores it in `z`. Note that the time at which you call this does make a difference, for example if you clear your buffer then check for input and call this function and then render it will not work because your buffer is empty. This can actually be useful because it allows you to render the clickable objects in your world first, then check for input, followed by rendering things you would like to be able to click through, such as a semi-transparent chat interface.

Another option which may be useful is to call `gluUnProject` twice with different z values to retrieve the vector from your mouse into the screen by subtracting the two points obtained.

`modelMatrix`, `projMatrix`, and `viewport` are the modelview matrix, projection matrix, and viewport of your world. The way you are retrieving them is correct, and may work for you for now, however if you change any of these after drawing your world, for example to render a gui over part of the display, then it may fail. To prevent this you can move your calls to `glGetFloat/Integer` to directly after you setup your world matrices and viewport.

`obj_pos`, the last parameter, is where the coordinates of the transformed point are stored if `gluUnProject` does not fail (which is indicated by a return value of true). In your code you create this float buffer with a capacity of 16, although it only actually needs to have a capacity of 3.
> 6 votes

---
Tags: lwjgl, projection
---


title: Refractive glass shader

text:
# Question
Title: Refractive glass shader
I have an infinite hexagonal floor, generated by tessellating a point grid in a tessellation shader pair:

Note that this is a flat wireframe - the "shadows" are a lighting trick:

Now, I'd like to make this appear to be thick, refractive glass, but am unsure how to proceed.

The first thing that came to mind is to

1. set a uniform containing the requested "thickness" of the blocks
2. When calculating lighting, use Snell's law to calculate the optical path length a ray would take through the hex block, if it were actually as thick as the "thickness" uniform says, and sum the alpha over that length. That would give the transparency, but doesn't handle things like internal reflection / TIR, etc.

I haven't tried that yet, so I'm not sure what the visual result would be.

Ultimately, for this particular level, I'm trying to get that glass, hexagonal floor look used in Tron: Legacy during the disc battle. (See this image for an example.)

Suggestions?

# Answer
> 4 votes
This article in GPU Gems goes into depth about refraction, which can give pretty nice results

In the most basic sense

> The first step of the basic refraction technique is to render the scene geometry into a texture, skipping all refractive meshes. This texture can be used to determine which objects are visible behind the refractive objects that will be rendered in a subsequent pass. We denote this texture as S.
>
> The second step is to render the refractive meshes, looking up values from the texture S with a perturbation applied to simulate the refractive look. The perturbation can be achieved using a normal map N, where the normal-map red and green (XY) components are used and scaled by some small value to add a displacement into the projected texture coordinates. This approach is straightforward to implement in a shader:
>
> 1. fetch the texture N
> 2. use the XY components scaled by a small value (such as 0.05)
> 3. add this displacement value into the projected texture coordinates for S

The following listing shows a shader that demonstrates this approach

```
half4 main(float2 bumpUV : TEXCOORD0,
  float4 screenPos : TEXCOORD1,
  uniform sampler2D tex0,
  uniform sampler2D tex1,
  uniform float4 vScale) : COLOR
{
  // fetch bump texture, unpack from [0..1] to [-1..1]
  half4 bumpTex=2.0 * tex2D(tex0, bumpUV.xy) - 1.0;

  // displace texture coordinates
  half2 newUV = (screenPos.xy/screenPos.w) + bumpTex.xy * vScale.xy;

  // fetch refraction map
  return tex2D(tex1, newUV);
}

```

The next images illustrates these three steps

There are more advanced techniques in the same article which can achieve a much more appealing look

---

For a similar effect in Unity, You might want to have a look at The Refraction Shader wiki page

# Answer
> 3 votes
I will take the image you showed as a reference for how I imagine the effect. The algorithm I can think of is simple:

1. Render the environment into a cube map texture inorder to simulate the environment reflection.
2. Apply the cube map texture into a plane that represents the layer below the refractive floor. Don't render the plane yet.
3. Render the plane into a texture, a normal 2D texture.
4. Pass the texture to the refractive shader used to render the refractive floor.
5. Now render the refractive meshes/floor with a refraction shader.

Regarding the refraction shader, inorder to simulate the glass you can do

* Use fresnel term to simulate the reflection and refraction.
* Use the normals/normal map to do a texture fetch.

I just thought of the idea, so I didn't test it. I am sure it needs more work, Maybe I will do once I return from work.

---
Tags: shaders, glsl
---


# Question
Title: Getting invalid argument error on R32G32B32_FLOAT texture creation
```
    D3D11_TEXTURE2D_DESC texDesc;
    texDesc.ArraySize = 1;
    texDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
    texDesc.CPUAccessFlags = 0;
    texDesc.Format = DXGI_FORMAT_R32G32B32_FLOAT;
    texDesc.Width = width;
    texDesc.Height = height;
    texDesc.MipLevels = 0;
    texDesc.MiscFlags = 0;
    texDesc.SampleDesc.Count = 1;
    texDesc.SampleDesc.Quality = 0;
    texDesc.Usage = D3D11_USAGE_DEFAULT;

    D3D11_SUBRESOURCE_DATA data;
    data.pSysMem = finalData.data();
    data.SysMemPitch = width * 3 * sizeof(float);
    data.SysMemSlicePitch = finalData.size() * sizeof(float);

    HRESULT hr = device->CreateTexture2D(&texDesc, &data, &texture);

```

I just can't see what's wrong. I am absolutely certain that the vector is properly initialized, that there is three floats per pixel and that the width is the given width. What's wrong? And the vector is of type float.

I've tried zeroing out the subresource data and just setting pSysMem, but no go.

Please help.

# Answer
So, you've probably read this:

> MipLevels Type: UINT
>
> The maximum number of mipmap levels in the texture. See the remarks in D3D11\_TEX1D\_SRV. Use 1 for a multisampled texture; or 0 to **generate a full set of subtextures**.

Yay, DirectX is going to do the dirty work for once! Hah. The devil is in the details. How so? Well, it said it is going to generate a full set of subtextures. It will figure out how many subtextures are needed from your width x height to the smallest — and generate the subtextures. **But it won't fill them with anything, even though it has the 0th level source texture.**

It is going to expect you to provide `D3D11_SUBRESOURCE_DATA data[n]` from the biggest (source) mipmap to the smallest, as the runtime would tell you in your output window if you created the device in debug mode. **Yes, that means you need to prefilter as many levels as there are needed and give a proper data pointer and pitches for each of them.**

# On one unapplicable misc flag

You've heard about `D3D11_RESOURCE_MISC_GENERATE_MIPS` and wonder if it applies because you could call `ID3D11DeviceContext::GenerateMips`? Unfortunately, Direct3D requires it to be bindable as a render target **AND** a shader resource. This originates in the interesting decision to only allow for mipmap automation when a texture is used as a render target, as it is not filled by the user.

So, maybe set it as a render target even though you'll never use it in that capacity? Besides it being dirty, you're out of luck again, as **`DXGI_FORMAT_R32G32B32_FLOAT` is not a valid render target format.**

# Summary

You cannot have your cake and eat it. Prefilter your texture to as many levels as needed and then fill out the D3D11\_SUBRESOURCE\_DATA for each one of them and pass it in bulk to the `CreateTexture2D`.

**In the end, as much as it is sneaky, Direct3D did its job. It generated the subtextures. It said nothing about filling them with filtered data from your source texture.**
> 4 votes

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


# Question
Title: How to correctly handle multiple Songs in XNA?
I'm working on a (Windows-only) game in XNA, and I have multiple music tracks. I don't want to load them all into memory, but play them on demand. To properly dispose them, I have a separate ContentManager just for music and a method that looks like this:

```
    public void PlayMusic(MusicTracks trackToPlay)
    {
        if (trackToPlay == _currentlyPlayingTrack)
            return;

        MediaPlayer.Stop();
        _musicContentManager.Unload();

        Song song = null;
        switch (trackToPlay)
        {
            case MusicTracks.TitleMusic:
                song = _musicContentManager.Load<Song>("TitleMusic");
                break;
            case MusicTracks.CreditsMusic:
                song = _musicContentManager.Load<Song>("CreditsMusic");
                break;
        }

        if(song != null)
        {
            MediaPlayer.Play(song);
            MediaPlayer.IsRepeating = true;
        }
        _currentlyPlayingTrack = trackToPlay;
    }

```

(MusicTracks is an enum).

Is this the correct way to make sure I'm not using more RAM/Resources than required? Or should I be looking into XACT? To be clear, I don't need to play multiple Songs at the same time (I do need to play 1 Song and a few SoundEffects though) and I don't need any crazy effects apart from setting the Volume of the music independently from the soundeffects, which should be straight forward with MediaPlayer.Volume.

# Answer
**The code you have there appears to be just fine.**

The alternative would be to use a custom `ContentManager` that allowed you to `Dispose` of the `Song` objects directly, rather than having to go through `Unload`. See this blog post for details.

A minor nit-pick: You set `IsRepeating` after you call `Play`. *Theoretically* this is a race condition: the song could end before `IsRepeating` becomes true. So set it before you call `Play`.

---

In XNA, **`MediaPlayer` is optimised for playing background music**, whereas XACT and `SoundEffect` are for... well... sound effects. On PC it's not going to make much difference. But on mobile (for example) it can make a big difference, as it can use the dedicated audio decoder hardware.
> 2 votes

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


# Question
Title: Efficient way to output/display debugging data in a window
I'm writing a program in Visual Studio, C++ with OpenGL and for the first time, I think it will be beneficial to see some live data on top of my display/render window.

To give some scope, I'm developing a 3D world with a ball bouncing and it would be nice to see things like the current velocity and y-positions of various objects, amongst other things.

What method is a nice/effective way to display this type of information to a window? Is there any libraries, vs settings or third-party implementations that can be useful? (please excuse my naivety, I'm used to just `cout << some info`, on a console).

# Answer
> 2 votes
Personally i have created a secondary GUI Layer and have a single class (c#) that handles all draw calls to this layer

information is passed in text format along with the sending object and the class organises the data before drawing it to screen

here is an exmple of the output

https://i.stack.imgur.com/oQo44.png

# Answer
> 0 votes
AntTweakBar is nice for simple things, but C.

---
Tags: opengl, debugging, hud
---


# Question
Title: EventManager adding data to the event message
## **Some backstory:**

I decided it was time to start making a game. I've got a bachelor degree in computer sciences, but I didn't really get to code much during my studies.
I've started making a quick prototype with libgdx, checking how the library worked et al. Then at some point I decided I knew enough of the basics and that it was time to move on and start doing something more complex and flexible.

I've started wondering how organize the logic and the data, and so I found out about `Entity-Component-System` architecture. Basically my implementation is something like this:

* **Entity:** just an id (UUID).
* **Component:** data. It can be a `PositionComponent` (float x, y), `VelocityComponent` (float x, y), `RenderableComponent` (texture t), ...
* **System:** Has an update() function that runs the logic every frame, and listens to message..

I've then discovered the `EventManager`, and have been struggling in implementing it propely.
Right now, it has an evergrowing enum to identify the different types of events. I can feel it is a bad thing since every class that listesns to / receives events need to include that, but I can't figure out another way to handle it.

## **Question:**

What does this eventmanager really do? It doesn't send any message other than "hey, wake up, something you care about happened, can't tell you what tho, check it yourself".
Every type of event needs custom data to work with.

*So the question is, how to append data (of different types) to an event message?*

## **Practical example:**

I would have liked to change the `Entity-Component-System` architecture a bit. Basically Systems may require more than a component to work with.

For example the `MovementSystem` will need both `PositionComponent` and `VelocityComponent`,
`RenderSystem` will need `PositionComponent` and `TextureComponent`.

So I wanted to create another object, the `Node` to hold all the components that a `System` requires, if the `Entity` has them.

To do so I need to keep a list of `Node`s for every `System`, wich can be achived (I guess) with messages on ComponentAdded / Component events telling wich component has been added/removed and check if a node needs to be added/removed.

## **Conclusion:**

I don't know if this architecture I tried to describe is actually any good, so I'm open for any complete refactoring suggestions.
My ultimate goal is to make a game, but I'm really interested in learning design patterns and techniques aswell, so I don't mind if I'm overengineering it.
There's no design behind the game yet, so for now I just want to do something 'general'.

It's my first post here, so sorry for my excessive usage of `ThisThingIObviouslyDontKnowHowToUsePropely`.

# Answer
> 4 votes
I often see people over-engineering event systems, my advice would be to keep it simple. For a simple game an enum suffices to identify events. For games with a large amount of events from different code modules and scripting functionality it will become a burden because it is not extendable (and increases compile time).

Imagine you added a script system and I want to write an AI using your game engine. I will want to add certain events, but won't be able to, because I can't add an enum from the scripting environment in hindsight. An easy way to solve this is to add a function like `uint32_t eventType = registerEventType("PLAYER_LOOKS_AT_ACTOR")` which will hash the string name of the event to an integer, which you can use instead of the enum. You may get hash collisions, so you will either need to use a linked list here (complex) or just tell the user to use a different event name (simpler, shouldn't happen often with a good hash anyway).

Your event will then look something like this:

```
typedef struct {
  uint32_t type;
  uint32_t time;
  void     *data;
} Event;

```

Where the type of `data` is known due to the event type. You can go fancy here with language features, but you will want to avoid run-time allocation of memory, because you will create a lot of events per frame usually. Basically you want a pre-allocated, large chunk of memory somewhere that you can use to store event data of various events in and just point to that. Professional game engines will even have their own malloc implementations that just point to pre-allocated memory. Also, when communicating such data between a scripting environment and the host environment, you will pretty much end up with a C-solution anyway.

A custom event would then be able to attach data with something like `setEventData(Event*, void* data, size_t dataSize)`, which would find free memory in the pre-allocated chunk, mark it as used, copy the event data there and set the pointer in the event. The event system does not understand the contents of this data and it doesn't need to, it's just a chunk of memory. This makes it more modular and extendable.

```
Event newEvent;
newEvent.type = registerEventType("PLAYER_LOOKS_AT_ACTOR");

typedef struct {
  uint64_t actorUUID;
} PlayerLooksAtActorData;

PlayerLooksAtActorData playerLooksAtActorData;
playerLooksAtActorData.actorUUID = 0xdeadbabe; // some unique id of the actor being looked at, better to avoid pointers for this

if(setEventData(&newEvent, &playerLooksAtActorData, sizeof(playerLooksAtActorData)) {
  // on failure, not enough memory in pre-allocated chunk?
}

```

All components that want to listen to this event would now use the same hash function as the registerEventType function and need to know what the contents of the data look like (they should share the include for the struct or redeclare it):

```
void player_handleEvents(Event* event) {
  // static to only compute this once
  static uint32_t const playerLooksAtActor = getEventType("PLAYER_LOOKS_AT_ACTOR");

  switch(event->type) {
    case playerLooksAtActor: {
      PlayerLooksAtActorData* lookatData = (PlayerLooksAtActorData*) event->data;
      if(lookatData) {
        log("player looks at actor %08x.\n", lookatData->actorUUID);
      }
    }
    break;
  }
}

```

That said, there are obviously many ways to go about this. I'm just suggesting a simple but quite powerful system.

---
Tags: entity-system, events, entity-component
---


# Question
Title: How does Raycasting work in XNA Farseer and player collision?
Wanting to know how to figure out if player's bottom is colliding with object so that I could allow the player to jump. I was trying to use OnCollision but was referred to ray-casting, I looked through the Testbed of Farseer to try and understand ray-casting better but am still lost.

I know what each return for the method does but how would I use it for player collision?

In this answer the person uses this function to find out if player is in the air. Is this the best way to find out if player is colliding with the ground?

In the testbed there is a fixture called f, two vectors call p and n, and a float called fr. What do these four things do?

Example:

```
case RayCastMode.Closest:
    bool hitClosest = false;
    World.RayCast((f, p, n, fr) =>
    {
        Body body = f.Body;
        if (body.UserData != null)
        {
              int index = (int)body.UserData;
              if (index == 0)
              {
                  // filter
                  return -1.0f;
              }
        }

        hitClosest = true;
        point = p;
        normal = n;
        return fr;
    }, point1, point2);

    if (hitClosest)
    {
         DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View);
                    DebugView.DrawPoint(point, .5f, new Color(0.4f, 0.9f, 0.4f));

                    DebugView.DrawSegment(point1, point, new Color(0.8f, 0.8f, 0.8f));

                    Vector2 head = point + 0.5f * normal;
    DebugView.DrawSegment(point, head, new Color(0.9f, 0.9f, 0.4f));
    DebugView.EndCustomDraw();
    }
    else
    {
        DebugView.BeginCustomDraw(ref GameInstance.Projection, ref GameInstance.View);
        DebugView.DrawSegment(point1, point2, new Color(0.8f, 0.8f, 0.8f));
        DebugView.EndCustomDraw();
    }

break;

```

Also Were is `World.RayCast` Coming from?

**Note**

If some one has a better way of detecting collision I would love to hear it.

**EDIT: 3/7/14**

I found that `World.RayCast` is located in the testbed in the Farseer Physics XNA project, Collision Folder, Collision.cs. The RayCastInput and Output are located on lines 200, and the bool on 444.

So if there located in the engine then I should be able to call on the function when I make my own project with it.

I make a class called Ray.

I then add the following code:

```
using System;
using System.Collections.Generic;
using FarseerPhysics.Collision.Shapes;
using FarseerPhysics.Common;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Factories;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using FarseerPhysics.Collision;

namespace FarseerPhysics.TestBed.Tests
{
    public class Ray
    {
        private float angle;

        public override void Update(GameTime gameTime)
        {
            const float l = 11.0f;
            Vector2 point1 = new Vector2(0.0f, 10.0f);
            Vector2 d = new Vector2(l * (float)Math.Cos(angle), l * (float)Math.Sin(angle));
            Vector2 point2 = point1 + d;

            Vector2 point = Vector2.Zero, normal = Vector2.Zero;

            World.RayCast((f, p, n, fr) =>
            {
                Body body = f.Body;
                if (body.UserData != null)
                {
                    int index = (int)body.UserData;
                    if (index == 0)
                    {
                        return -1.0f;
                    }
                }
                point = p;
                normal = n;
                return fr;
            }, point1, point2);
        }
    }
}

```

I create this little thing but `World.RayCast` has an error:

```
An object reference is required for the non-static field, method, or property 'FarseerPhysics.Dynamics.World.RayCast(System.Func<FarseerPhysics.Dynamics.Fixture,Microsoft.Xna.Framework.Vector2,Microsoft.Xna.Framework.Vector2,float,float>, Microsoft.Xna.Framework.Vector2, Microsoft.Xna.Framework.Vector2)'

```

What have I done wrong?

# Answer
I've been looking at your code for ten minutes now and I believe I have found your mistake. The Farseer engine uses a Func\<,,,\> but you're trying to use a delegate. As far as I can tell a delegate cannot be automatically casted to a Func\<,,,\>.

Just to be on the safe side I've copy/pasted my own RayCasting code (right from a working application) so that you might even be able to figure it out if this wasn't the error.

Note that my code always returns the first collision (my own class) so you might need to modify it a bit.

```
public Collision RayCastFirst(Vector2 point_0, Vector2 point_1)
{
    Collision collision = null;
    Func<Fixture, Vector2, Vector2, float, float> get_first_callback = delegate(Fixture fixture, Vector2 point, Vector2 normal, float fraction)
    {
        collision = new Collision(fixture, point, normal);
        return 0;
    };

    // Summary:
    //     Ray-cast the world for all fixtures in the path of the ray. Your callback
    //     controls whether you get the closest point, any point, or n-points.  The
    //     ray-cast ignores shapes that contain the starting point.  Inside the callback:
    //     return -1: ignore this fixture and continue
    //     return  0: terminate the ray cast
    //     return fraction: clip the ray to this point
    //     return 1:        don't clip the ray and continue
    world.RayCast(get_first_callback, point_0, point_1);
    return collision;
}

```
> 0 votes

---
Tags: xna, c#, collision-detection, farseer-physics-engine, raycasting
---


# Question
Title: Optimal way to store coordinates of a random point in 3D space in a texture?
A quick question: there is a well-known approach to store 3d point in space in a texture as a distance between camera and an object (deferred rendering). But it implies that the object lies on a ray, cast from the camera towards that object in such and such section (UVs) of the texture. Is there any way to store a RANDOM 3d point in space in a texture with a single (mb 16-bit) depth value or less than 3 values?

# Answer
Depth maps get away with using only a single coordinate because the other two are implicit in the location of the texel within the map (UV).

If you need to scatter each texel randomly in 3D space, then you'll need to encode all three degrees of freedom into the texel value.

If you don't have 3 channels to spare, you can quantize your positions and pack them into a smaller number of channels (as low as one channel encoding all three axes).

The optimal way to do this will depend heavily on your application. For instance, if your points are clumped it may work well to express them in polar coordinates. If one axis has greater range/variability than others, you may want to devote more bits to it...

As one example, if I have a 16-bit field to work with, I can encode x into the low 5 bits, y into the middle 5, and z into the top 6 bits. This only gives 32 unique positions along the x/y axes, and 64 on the z.

Texture values encoded this way will not interpolate correctly with bi/trilinear or anisotropic filtering, so ensure you're using point sampling and doing any interpolation you need manually in the shader.
> 2 votes

# Answer
Basically what you're trying to do is called unprojecting. If you unproject a 2D point (calculated from an inverse projection matrix) you will get a ray. If you store the distance from the camera in the 16bit depth values you can quite accurately reconstruct the 3D world point.

Please see this question on StackOverflow https://stackoverflow.com/questions/3528114/whats-wrong-with-my-project-and-unproject-functions (Note that it really depends on the framework you are using if you need to transpose the matrix or not).

Another good resource is: http://myweb.lmu.edu/dondi/share/cg/unproject-explained.pdf

*(Normally I would reproduce it here so that it would be available as long as this question exists but I'm not 100% sure if the author of the PDF would allow it)*
> 1 votes

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


title: (LWJGL) Resize window content

text:
# Question
Title: (LWJGL) Resize window content
I am having a little issue with my game trying to get the screen to draw a ton larger. I am going for a retro type of feel for my game and I believe that this would help with that.

I am basically trying to take a small area (example 100x177) and draw it 9 times the original size while still keeping the nearest neighbor. The image below shows what I am trying to achieve.

(image taken from: http://forums.tigsource.com/index.php?topic=27928.0).

I have been trying to set the current render area to an FrameBuffer then draw the Frame Buffer larger on the window. I have not been able to find any example code or how I would go about doing that.

Thank you in advance for the help.

EDIT: Added sample code

This code is in the same method where I initialize OpenGL

```
    fboID = GL30.glGenFramebuffers();
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fboID);
    colID = GL11.glGenTextures();
    GL11.glBindTexture(GL11.GL_TEXTURE_2D, colID);
    GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGB, scaleWidth, scaleHeight, 0, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, (ByteBuffer)null);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
    GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
    depID = GL30.glGenRenderbuffers();
    GL30.glBindRenderbuffer(GL30.GL_RENDERBUFFER, depID);
    GL30.glRenderbufferStorage(GL30.GL_RENDERBUFFER, GL11.GL_DEPTH_COMPONENT, scaleWidth, scaleHeight);
    GL30.glFramebufferRenderbuffer(GL30.GL_FRAMEBUFFER, GL30.GL_DEPTH_ATTACHMENT, GL30.GL_RENDERBUFFER, depID);
    //GL32.glFramebufferTexture(GL30.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0, colID, 0);
    drawBuffs = BufferUtils.createIntBuffer(1);
    drawBuffs.put(0, GL30.GL_COLOR_ATTACHMENT0);
    GL20.glDrawBuffers(drawBuffs);
    if(GL30.glCheckFramebufferStatus(GL30.GL_FRAMEBUFFER) != GL30.GL_FRAMEBUFFER_COMPLETE){
        System.out.println("Framebuffer not complete!");
    } else {
        System.out.println("Framebuffer is complete!");
    }

```

And this is my render method that the game loop runs (updates at 60fps)

```
    // clear screen
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);

    // Start FBO Rendering Code
    //GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, fboID);
    // Resets the current viewport
    GL11.glViewport(0, 0, scaleWidth, scaleHeight);                 // Set viewport to be the size of the FBO
    // Clear the FrameBuffer
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
    // Actual render code!
    gameMap.render();

    // draw the texture from the FBO
    GL30.glBindFramebuffer(GL30.GL_FRAMEBUFFER, 0);
    GL11.glViewport(0, 0, scaleWidth*scale, scaleHeight*scale);
    GL11.glBegin(GL11.GL_QUADS);
    GL11.glTexCoord2f(0.0f, 0.0f); GL11.glVertex3f(0.0f, 0.0f, 0.0f);
    GL11.glTexCoord2f(1.0f, 0.0f); GL11.glVertex3f((float)scaleWidth*scale, 0.0f, 0.0f);
    GL11.glTexCoord2f(1.0f, 1.0f); GL11.glVertex3f((float)scaleWidth*scale, (float)scaleHeight*scale, 0.0f);
    GL11.glTexCoord2f(0.0f, 1.0f); GL11.glVertex3f(0.0f, (float)scaleHeight*scale, 0.0f);
    GL11.glEnd();

    // Resets the current viewport
    GL11.glViewport(0, 0, scaleWidth*scale, scaleHeight*scale);

    GL11.glMatrixMode(GL11.GL_MODELVIEW);
    GL11.glLoadIdentity();

    // let subsystem paint
    if (callback != null) {
        callback.frameRendering();
    }

    // update window contents
    Display.update();

```

I had to comment out "GL32.glFramebufferTexture(GL30.GL\_FRAMEBUFFER,GL30.GL\_COLOR\_ATTACHMENT0, colID, 0);" because it was throwing a "Function not supported" error.

Thanks

# Answer
I do this all the time with my graphics
What you should do is what you mention (render to a smaller frame buffer), then render its texture to fill the entire screen.
Perhaps you are not **Re-Setting The Viewport** every time you switch to a different frame buffer (bind the frame buffer, then set the viewport to the size of the frame buffer, then render your geometry, bind the window frame buffer, reset the viewport to match the screen resolution and finally render the frame buffer texture)
> 1 votes

---
Tags: opengl, lwjgl
---


# Question
Title: How can I provide attribute extensibility in a component-based entity system?
This question and its answers move against utilizing an entity component system where the *component* itself is just a *generic class* with an *dynamic container for the attributes/properties* of the component.

Some definitions for this thread:

* Entity = ID + collection of components
* Component = Container (`std::map<attribute_name, attribute_value>`) of attributes/properties, such as health, age, name, gender, etc.

I understand and am aware of the drawbacks (no compile-time type safety, added overhead of looking up values from the container). Nonetheless, I currently am working on/with such a system, with the following argument, which I would now like to put to the test: *data-driven design.*

If all the attributes of the component are in a dynamic container, it is very easy (in fact possible at all) to add new ones later on, outside of the source code. So you can easily script new attributes later on. And dumping/saving the state of the component is a piece of cake.

Compared to the proposal in the above mentioned thread, I also have an own class for each component, to implement some basic behavior and helper methods directly in them (but those also need to look up their values from the container).

**Example:**

My component base class has a map for all the attributes/property:

```
typedef std::map<std::string, PropertyBase*> PropertyMap;

```

So an actual component looks something like the following. In the constructor I populate the attributes I want the component to have, by adding them to the map. Later I can read and update them if needed, but always with a performance penalty, since I first have to find them in the `std::map`.

```
class Person : public ClonableComponent<Person>
{
public:
    Person(ComponentFactory* const pFactory, ComponentType type, ComponentID id, GameEntity* const pEntity)
    : ClonableComponent(pFactory, type, id, pEntity)
{
    // General
    addProperty(new Property<int>("age", PROP_INT, 0));
    addProperty(new Property<String>("gender", PROP_STRING, "unknown"));
    addProperty(new Property<String>("currentLocation", PROP_STRING, "unknown"));

    // Feelings
    addProperty(new Property<bool>("isTired", PROP_BOOL, false));
    addProperty(new Property<bool>("isHungry", PROP_BOOL, false));
    addProperty(new Property<bool>("isThursty", PROP_BOOL, false));
}

void enterLocation(GameEntity* pLocGE)
{
    if(pLocGE->hasComponent(COMP_TYPE_LOCATION))
    {
        updateProperty("currentLocation", pLocGE->getName());
        updateProperty("casinoEnteredDateTime", (int)std::time(0));
    }
}

void leaveLocation()
{
    updateProperty("currentLocation", std::string("unknown"));
}
};

```

However, that thread made me think, and I am now doubtful that my approach will work well in the long run (maintenance, scaling and performance wise) and I am therefore considering moving to an directly typed approach with no look-up overhead. At the same time I don't want to loose that data-driven extendability.

I thought of a hybrid approach: Keep all known variables as actual language variables but also add a container (std::map) for scripted/data-driven variables. Therefore I'd know that my internal access is very fast and only the later added scripted extension would have the slow look-up and the other mentioned penalties.

**Question:** What do you use / would propose as an approach for a data-driven ECS in terms of attribute storage/handling? How do you keep it extendable? Would you recommend such a hybrid approach (real variables internally, container for new, external definitions)?

# Answer
> If all the attributes are in a dynamic container, it is very easy (more correctly: possible at all) to add new ones later on, outside of the source code. So you can easily script new attributes later on.

Yes, but you can't *do* anything with new attributes added via scripts *except* via scripts without losing this "advantage." Once you need to refer to these values in source code, you should have just added a concrete field to a concrete type rather than something in a `Dictionary` or whatever.

If you want the ability for scripts to dynamically add new bits of data without recompilation (which is a very useful feature) than provide this functionality *just* to the `ScriptComponent` (or what have you) in your system. This sounds relatively identical to your "hybrid" approach anyway: I'd just caution that you shouldn't need the functionality anywhere but a component that is providing/running a script.

> And dumping/saving the state of the component is a piece of cake.

This should not be the concern of the entity/component system. This should be the concern of the reflection/content representation system you use. It's trivial to implement without dynamic "property bag" dictionaries in languages like C# with good reflection support, and it's only slightly more work to do it in something like C++ with really poor reflection support. Consequently you shouldn't use this as a strong rationale for storing component attributes in a runtime associative array.

> Would you recommend such a hybrid approach (real variables internally, container for new, external definitions)?

Basically, what I said above: don't use a runtime associative array for component attributes by default. If your scripting system needs that functionality, provide it via the components bound to the scripting system.
> 3 votes

# Answer
ECSs are somewhat complicated.

At first I used the following approach: Entities only contain a position vector and a set of components. A component contains a specific behavior and necessary data e.g. RenderComponent, PhysicsComponent etc. This is commonly referred to as ECS.

But this has some disadvantages: The data of an entity is closely entangled with the component functionality. Sooner or later a component needs to access and modify data stored in a different component type e.g. the MovementComponents needs to apply a force to the PhysicsComponents etc. So either directly access the other component via the entity, send an event causing the change in the other component or pull the needed value up into the entity. All bad solutions in my opinion. Also maintaining the lifecycle of each component type was quite a hassle.

Currently I'm using the following approach: An Entity consist of an unique id and a bag of keys and values (hash the key strings for ultimate performance ;-) ). Subsystems (e.g. physicsEngine, renderer) look for entities with property keys they can use and create components internally with the required behaviors. These components store the unique id of their entity and use it to read and modify the entities property values. You could even get rid of the entity class entirely, since it's only an id anyways and store the properties under the entity id in a global property store making the whole design more like a database. Jason Gregory calls this Property Centric Archictecture in his book Game Engine Architecture. Thief and Deus Ex used this approach.

It's trivial to inspect, store and load the game state. Easy to extend and I can create new behavior entirely in script (I'm using python for scripting - great language btw). Components are only known in their respective subsystem. I sacrificed compile time safety and OOP style data hiding sure and I might need some kind of templating mechanism to define and check properties. But for now this approach works suprisingly well.
> 0 votes

---
Tags: entity-system, entity-component, data-driven
---


# Question
Title: Should I reuse vertex buffers for multiple draw operations? Would this be more efficient?
I am constructing the game scenario and buttons using Vertex Buffers. I am making a `v_buffer` for each item, and then releasing them. I don't like my method. Should I reuse my vertex buffer for multiple draws? Why or why not?

```
v_buffer->Release();
v_bufferGrass->Release();
v_bufferMargin->Release();
v_bufferDirtGrassShadow->Release();
// ...and many more v_buffers than I don't want to maintain.

```

# Answer
> 1 votes
You can and should re-use vertex buffers when possible. It's a particularly bad idea to create and destroy vertex buffers for each object *per frame*, because the process of doing so takes a toll on both CPU and GPU resources.

You should strive to have one vertex buffer per model under normal circumstances. That means if you have a goblin character in your game, you have one goblin vertex buffer. Even if you render fifty goblins, you reuse the same vertex buffer, chaining only the world transformation every time you render with that buffer.

For some classes of object (such as purely static geometry) you can in fact pack multiple objects into one buffer, further reducing resource load.

You should create your buffers as early as you can and release them as late as is practical; for simple games, you can create them all on startup and only release them on shutdown (in practice, for larger projects, resource constraints and optimizations may make it worth your while to initialize later or release earlier, but you certainly want to be far, far away from creating/destroying buffers every frame).

You can *update* vertex buffers every frame, but make sure that when you do so you have created the buffer with the appropriate API hints that tell the GPU you're planning on doing so. This will allow it to prioritize the resource in memory appropriately.

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


# Question
Title: Data structure fo a ship like in Faster Than Light
I am wonder me, whats the best data structure for a ship like in FTL. At first I thought its easy and I need only to make a array with the rooms(Tiles). But than I noted, that I must put somewhere the doors, walls, weapons, crew and systems. And with this Aspect I don't know a clean data structure. Have someone a idea ?

If there is something unclear write it and I try to explain.

# Answer
I'd go with 2D tile map of size X / Y. It is much easier for representation and pathfinding.

Each tile would have a bunch of properties alike:

* `room_type`,
* `oxygenation_level`
* `hasFire`
* etc.

Having these it will be map editor responsibility to make sure certain rooms have proper size (e.g. 2x2). That will also give you freedom to make different sized rooms (e.g. double-packed engine room of 3x2).

Also keep a second structure for tile/tile markers (e.g. tile also stores properties for bottom and right walls):

* `wall_type_right`,
* `is_door_bottom`,
* etc.

In FTL weapons have static mounting points, so you can go with just a list and locations relative to your map, with regard to ship graphics (probably pixel coordinates).

Crew are just units living on a tile-map.

Systems are just entities that exist or not basing on existence and functioning of the rooms on the ship.
> 1 votes

---
Tags: java, data-structure
---


title: Events management using SDL 2.0

text:
# Question
Title: Events management using SDL 2.0
I wrote a simple SDL program using SDL 2.0. I have a little problem when I want to check the mouse wheel events. Actually, in the version 2.0 the flags SDL\_BUTTON\_WHEELDOWN and SDL\_BUTTON\_WHEELUP no longer exist. There is just the flags SDL\_MOUSEWHEEL. The code below check correctly the' WHEELUP' and 'WHEELDOWN' events but with the same flag.

```
while(!terminer)
    {
        while (SDL_PollEvent(&evenements))
        {
            switch (evenements.type)
            {
            case SDL_QUIT:
                terminer = true;
                break;
            case SDL_KEYDOWN:
                switch (evenements.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                    terminer = true;
                    break;
                }
                break;
                case SDL_MOUSEMOTION:
                    std::cout << "MOUSE : MOVE" << std::endl;
                    break;
                case SDL_MOUSEBUTTONUP:
                case SDL_MOUSEBUTTONDOWN:
                    std::cout << "MOUSE : BUTTON DOWN" << std::endl;
                    break;
                case SDL_MOUSEWHEEL:
                    std::cout << "MOUSE : WHEEL" << std::endl;
                    break;
            }
        }

```

But I would like to handle separately the 'WHEELUP' and 'WHEELDOWN' events. I tried several others flags in my condition but without success. Does anyone can help me, please ?

Thanks a lot in advance for your help.

# Answer
According to the SDL documentation:

> Movements to the left generate negative x values and to the right generate positive x values. Movements down (scroll backward) generate negative y values and up (scroll forward) generate positive y values.

So in your case, you could modify the code as such:

```
case SDL_MOUSEWHEEL:
    if(evenements.x < 0)
    {
        std::cout << "MOUSE : WHEEL LEFT" << std::endl;
    }
    else if(evenements.x > 0)
    {
        std::cout << "MOUSE : WHEEL RIGHT" << std::endl;
    }
    if(evenements.y < 0)
    {
        std::cout << "MOUSE : WHEEL DOWN" << std::endl;
    }
    else if(evenements.y > 0)
    {
        std::cout << "MOUSE : WHEEL UP" << std::endl;
    }
    break;

```
> 0 votes

---
Tags: opengl, sdl
---