# Question
Title: What is the recommended way to output values to FBO targets? (OpenGL 3.3 + GLSL 330)
I'll begin by apologizing for any dumb assumptions you might find in the code below since I'm still pretty much green when it comes to OpenGL programming.

I'm currently trying to implement deferred shading by using FBO's and their associated targets (textures in my case).

I have a simple (I think :P) geometry+fragment shader program and I'd like to write its Fragment Shader stage output to three different render targets (previously bound by a call to `glDrawBuffers()`), like so:

```
#version 330

in vec3 WorldPos0;
in vec2 TexCoord0;
in vec3 Normal0;
in vec3 Tangent0;

layout(location = 0) out vec3 WorldPos;
layout(location = 1) out vec3 Diffuse;
layout(location = 2) out vec3 Normal;

uniform sampler2D gColorMap;
uniform sampler2D gNormalMap;

vec3 CalcBumpedNormal() {

    vec3 Normal = normalize(Normal0);
    vec3 Tangent = normalize(Tangent0);

    Tangent = normalize(Tangent - dot(Tangent, Normal) * Normal);
    vec3 Bitangent = cross(Tangent, Normal);
    vec3 BumpMapNormal = texture(gNormalMap, TexCoord0).xyz;

    BumpMapNormal = 2 * BumpMapNormal - vec3(1.0, 1.0, -1.0);

    vec3 NewNormal;
    mat3 TBN = mat3(Tangent, Bitangent, Normal);
    NewNormal = TBN * BumpMapNormal;
    NewNormal = normalize(NewNormal);

    return NewNormal;
}

void main() {
    WorldPos = WorldPos0;
    Diffuse = texture(gColorMap, TexCoord0).xyz;
    Normal = CalcBumpedNormal();
}

```

If my render target textures are configured as:

```
RT1:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE0, GL_COLOR_ATTACHMENT0)
RT2:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE1, GL_COLOR_ATTACHMENT1)
RT3:(GL_RGB32F, GL_RGB, GL_FLOAT, GL_TEXTURE2, GL_COLOR_ATTACHMENT2)

```

And assuming that each texture has an internal format capable of contaning the incoming data, will the fragment shader write the corresponding values to the expected texture targets?

On a related note, do the textures need to be bound to the OpenGL context when they are Multiple Render Targets?

From some Googling, I think there are two other ways to output to MRTs:

1: Output each component to `gl_FragData[n]`. Some forum posts say this method is deprecated. However, looking at the latest OpenGL 3.3 and 4.0 specifications at opengl.org, the core profiles still mention this approach.

2: Use a typed output array variable for the expected type. In this case, I think it would be something like this:

```
out vec3 [3] output;

void main() {
    output[0] = WorldPos0;
    output[1] = texture(gColorMap, TexCoord0).xyz;
    output[2] = CalcBumpedNormal();
}

```

So which is then the recommended approach? Is there a recommended approach at all if I plan to code on top of OpenGL 3.3?

Thanks for your time and help!

# Answer
> 4 votes
The second approach is the new one. they will not perform differently, it is just a flexibility of naming.

Also: yes your values will be written as-is to your textures.

now, you may want to use RGB16F targets because RGB32F are taxing on the ROPs and the bus bandwidth, which medium/small-end graphic cards do NOT have. (only the high-end cards can bind full-HD 3x 128 bits render targets at \>60 FPS)

when using 16F (half floats) your values will lose precision during encoding reduction (the ROPs are operating this conversion), so careful about the range of your values (after ~32000 each step is a multi-integers jump, you don't get decimals anymore etc.)

Now, you ALSO want to reduce the number of targets to 2, by using RGBA and packing your normal as components of A of the first target and A of the second target.

Use a view-space encoding trick to store your normal in only 2 components.

This is THE resource you want to read about that: http://aras-p.info/texts/CompactNormalStorage.html

---
Tags: opengl, glsl
---


title: Animations not accepted in animator

text:
# Question
Title: Animations not accepted in animator
In the official Unity Animator State Machine tutorial video animation clips are dragged out from the assets folder into the animator and dropped.

I have a 3D model that i bought online to experiment with that comes with animations. I added a custom made animation as well. These all work well in my demo project. But when i add a animator to the assets and try to drag and drop animations onto it it doesnt work. I get a forbidden-sign as a mouse pointer. I try to add animations through the inspector but that does not work either.

The tutorials makes it seem so easy and does not talk anything about what animations can be used. What am i doing wrong?

# Answer
> 2 votes
Ok this can be a bit daunting but i'll run you through it. With the animator component you need to use the animator tab and switch between the different states via blend trees etc. Animator tab is here

You create an Idle state and assign your idle animation as shown here:

Now all you need to do is tell Mecanim to move between the difference states depending on what you're doing, in my controller script thats attached to my character when I press Forward or backward (Vertical axis 1 or -1) my code does the following(cut down for clarity):

Note where I do anim.SetBool() that sets the variables you define in the animator which tell mecanim when to switch between the animations.

```
void Start() {
  // Get the animator associated with this character
  myAnimator = transform.GetComponent<Animator>();

}

void Update() {
  // Lots of other stuff

  if(Input.GetAxis("Vertical")>0){ // Forward
    transform.position += transform.forward * speed;
        anim.SetBool ("isWalking", true);
  }

  if(Input.GetAxis("Vertical")<0){ // Backward
    transform.position += -transform.forward * speed;
        anim.SetBool ("isWalkingBack", true);
  }

  if(Input.GetAxis("Vertical")==0){
        // We're neither walking forward or back so stop animating.

        anim.SetBool ("isWalkingBack", false);
        anim.SetBool ("isWalking", false);
  }

}

```

There's a tutorial here from Unity themselves.

Trust me I really feel your pain with this its a bit of a steep learning curve but once you get your head around it things start to get a lot easier.

---
Tags: unity, animation
---


# Question
Title: overlapping 3d particles not blending nicely when at the same z
I'm working on a 3d particle emitter. It's going pretty good but I'm still having a problem with triangle sorting.

As you can see in the photos, there are some particles that are not blending properly presumably because of sorting. I do sort my quads before I draw them back to front. And they are all being drawn in a single `glDrawElements(GL_TRIANGLES...` call.

Blending is on & depth buffer is on. Depth buffer has to be on because of the other 3d objects in the scene that are sometimes in front and sometimes behind the particles.

When they're moving in a z space they're sorting better and you don't see it as much:

I'm using a sort with the following compare:

```
int compare (const void *a, const void *b) {
   Particle *ia = (Particle*)a;
   Particle *ib = (Particle*)b;

   float t = ib->distanceToCamera - ia->distanceToCamera;
   if (t<0) {
       return -1;
   }
   return (t>0);

```

}

But I think there are times when some particles have the same z and then they're not blending nicely.

One thought was to somehow force them to not be the same z. But with them moving on their own I'm not sure about that.

QUESTION - if overlapping triangles are close in z space but not equal, and still drawn back to front within the draw command, could they still overlap like this?

ANSWER - I set a break point and printed out all my structures to find that there are a ton of quads in the same z. In groups.

Using the advice from the checked answer I was able to fix it. By making sure to render the solids first and the particles last I don't need to worry about writing to the depth buffer while rendering the particles. In my game they're all like gases, smoke and air. So they all need to blend with each other and on to things deeper in the scene than them. When I start to render the particles I set:

```
glDepthFunc(GL_LEQUAL);
glDepthMask(GL_FALSE);

```

And when I'm done rendering them I return it to:

```
glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);

```

And look at the result:

What I believe was happening was that as particle triangles were drawn if they were on the same plane they were writing to the depth buffer and then the next one on that z if larger would get masked. By turning off depth mask it doesn't write to the mask as it's drawing the particles so they're not masking each other any more. Since I draw them last they don't need to mask other things.

UPDATE: Another benefit I just figured out. Now I don't have to sort the particles at all. The sort was only to make them draw properly with the depth test on. And that's no longer needed. So I have that savings as well.

# Answer
The general rule of thumb when drawing alpha polys is:

1 - Draw all solid polys first.

2 - Sort back to front if you can. The main reason for this is to ensure that the final colour produced by the blending equation is consistent frame to frame. I often don't bother with this step unless it is something provided by the engine and I can justify the extra cost with my own eyes.

I don't think that this is the meat of the solution to your problem in this particular case as it looks like you have polys that are intersecting each other and in this case there is really no perfect way of sorting them bar sorting the individual fragments in a pixel shader or using some other order independent transparency technique (but that is usually massive overkill).

3 - Set the ztest renderstate to less equal or less

4 - Don't write to the z buffer by setting the zwriteenable renderstate to false

I suspect it is this last step that you are missing. You mention needing to have the z buffer turned on so that the alpha polys don't sort incorrectly with the solid but it isn't quite that simple.

You are able to control reading from and writing to the z buffer separately from each other, and in this case you want to read i.e. do the z test so that your polys sort correctly with the existing contents of the z buffer; but you don't want to write. Not writing to the z buffer will result in the next alpha poly essentially ignoring the previous one and you should see the seams disappear.

The downside of this approach is that the colour blending equation now produces slightly incorrect results for some fragments depending on the particular situation but there isn't a straightforward solution to this and generally the results are good enough.
> 5 votes

---
Tags: 3d, ios, opengl-es2, particles, depth-buffer
---


# Question
Title: How to get plane rotation by known normal vector
I have a FPP quaternion `Camera` and `Plane` with known `normal vector`.

I want to find the orientation of this `Plane` so I can replace it to the `Camera` orientation to put the camera forward vector to a plane's normal vector.

* First **method** I tried, I don't understand `RotationAxis` and `RotationAngle`. I built a rotation matrix and applied it to the camera but it didn't behave as I wanted.
* The second **method** I tried is with method called "from\_one\_vector\_to\_another". I don't understand what the "from" vector is in my example; is it the camera's forward vector?

Here is my pseudo code:

```
Vector3 vector_from = camera->getForwardVector();
Vector3 vector_to = triangle->faceNormal;

Quat cameraQuaternion = camera->getOrientation();

Quat q = vector_from.getRotationTo(vector_to);//The method `getRotationTo` is from Ogre.
camera->setOrientation(cameraQuaternion * q);

```

Camera does not change their orientation as I expected; it changes its orientation just a little bit.

**EDIT:**

Maybe I have something wrong with my code:

```
//Quat xrot = axisToQuat(Vector3(1, 0, 0), vertical);  // disabled for now
Quat yrot = axisToQuat(Vector3(0, 1, 0), horizontal);
rot = rot * yrot;

position += velocity;

Matrix lookAt = Matrix::createLookAt
        (
            Vector3(position.x, position.y, position.z),
            Vector3(position.x, position.y, position.z-1),
            Vector3(0,1,0)
        );

view = rot.toMatrix() * lookAt;

```

I am only rotating the quaternion. Should I rotate lookAt Matrix too?

# Answer
> 1 votes
So, just to be clear; you want to orient the camera such that it is looking in the direction given by the plane's normal?

The problem with calculating a quaternion for this is that it doesn't usually represent an absolute rotation but rather a rotation through which the initial forward direction of the camera is to be rotated. So what you are looking for is a quaternion that will rotate the initial forward vector of the camera to the normal of the plane. This link will give you that answer:

https://stackoverflow.com/questions/1171849/finding-quaternion-representing-the-rotation-from-one-vector-to-another

However it is common for a camera API to have a function that will take a position and a look at and orient the camera for you. In your case this will be much more simple:

position = whatever you want it to be

look at position = position + normal

Hope I am understanding the question correctly.

---
Tags: c++, camera, rotation, quaternion
---


title: Atmospheric scattering and sky geometry

text:
# Question
Title: Atmospheric scattering and sky geometry
I'm trying to implement an atmospheric scattering in my graphics (game) engine based on the GPU Gems article: link. An example implementation from that article uses a skydome. My scene is different - I don't render a whole earth with an atmosphere which can be also visible from the space but some finite flat (rectangle) area with objects, for example a race track. In fact this is the most common scenario in many games. Now I wonder how to render a sky in such case:

1. What kind of geometry I should use: skydome, skybox or a full screen quad - then I have to move almost all calculations to the fragment shader, but I don't know if it makes sense in terms quality/performance ?
2. How to place sky geometry on the scene ? **My idea:** I have a hemisphere (skydome) geometry with radius = 1 and center in vec3(0, 0, 0) - in object space. Those vertices are sent to the atmospheric scattering vertex shader:

layout(location=0) in vec3 inPosition; Next, In the vertex shader I transform vertex this way:

v3Pos = inPosition * 0.25f + 10.0f; Uniform **v3CameraPos** = vec3(0.0f, 10.0f, 0.0f), uniform **fInnerRadius** = 10.0f, uniform **fCameraHeight** = 10.0f

Then I have correct an inner/outer radius propotion (10/10.25),right? I also send to the vertex shader a **model matrix** which sets a position of the hemisphere to the postion of the mobile camera vec3(myCamera.x, myCamera.y, myCamera.z):

```
vec4 position = ProjectionMatrix * ViewMatrix * ModelMatrix * vec4(inPosition, 1.0);
gl_Position = position.xyww; // always fails depth test.

```

The hemisphere moves together with the camera (encloses only some space around camera with radius = 1, but it also always fails a depth test.)

Unfortunately a sky color which I get is not correct:

3. What about a "sky curve"? Here is a picture which demonstrate what I mean:

How should I set a sky curve?

**Edit1 - debugging:** In the vertex shader I assigned to v3Pos position of the "highest" vertex in the hemisphere:

```
vec3 v3Pos = vec3(0.0f, 10.25f, 0.0f);

```

Now the whole sky contains a color of that vertex:

# Answer
You need to pass your tuning values through uniform data, and not vertex data.

Vertex data always complexify export pipeline, and binding (input signature).

I recommend a screen quad for the support geometry of the sky, and render it at the end of your frame, when all other objects are rendered, using a depth test operation that is supposed to fail all tests, so that only wholes are rendered. (you can use a special orthographic camera matrix for that, where you know that `1` is the deepest value, and you put your screen quad at `0.99` to avoid far clipping, for still to fail all depth tests.)

Then it will be optimal in performance, it is a classic defered rendering technique. (unfortunately with the classic antialiasing problems that we know)

You can also use a skycube or a skysphere, companies have happened to use the 3 techniques described above, so its not like there is a universal answer.
> 1 votes

# Answer
I haven't worked on this problem personally so I probably missed a lot of the nuances but I have managed a project where we implemented just this sort of scattering model. We actually did this twice, once for a forward rendered pipeline and again for a deferred lighting pipeline. In both cases we did everything in screen space with what little dynamic data we needed uploaded as shader constants, and the static data pre-calculated and encoded into 3d textures. The forward version was done as a post process step (although this caused all sorts of headaches, especially lighting alpha polys that were not represented in the depth buffer). In the deferred lighting setup we did this as part of the lighting pass with far fewer problems.

Sorry for being a bit vague but hopefully at least of some help.
> 0 votes

---
Tags: opengl, graphics-programming, graphic-effects
---


# Question
Title: Bullet3: Issue with applying force once an object is at rest
I just started using bullet and I'm having an issue where once my rigid body is at reset at the floor it won't move when I apply a force to it.

I have created a small demo to show this using the hello world example provided here.

```
for(int i = 0; i<30000; i++) // Give it a lot of time to hit the ground
{
    dynamicsWorld->stepSimulation(1 / 60.f, 10);
}

btVector3 froce(0.0, 2000.0, 0.0);
fallRigidBody->applyCentralForce(froce);// Apply a force on the Y axis

for(int i = 0; i<300; i++) {
    dynamicsWorld->stepSimulation(1 / 60.f, 10);

    btTransform trans;
    fallRigidBody->getMotionState()->getWorldTransform(trans);

    std::cout << "Frame # : " << i
        << "\t: X: " << trans.getOrigin().getX()
        << "\t, Y: " << trans.getOrigin().getY()
        << "\t, Z: " << trans.getOrigin().getZ()
        << "\n";
}

```

The result I get out of this is:

```
Frame # : 0     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 1     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 2     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 3     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 4     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 5     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 6     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 7     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 8     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 9     : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 10    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 11    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 12    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 13    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 14    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 15    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 16    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 17    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 18    : X: 0.00       , Y: 1.00       , Z: 0.00
Frame # : 19    : X: 0.00       , Y: 1.00       , Z: 0.00

```

As you can see, the object never moved.

Now if I lower the first loop from `30000` to `300` then it will move just as I expect

What am I doing wrong?

Here is the full code if anyone wants to test it out

```
#include <iostream>
#include <iomanip>
#include <btBulletDynamicsCommon.h>

int main(void)
{

    btBroadphaseInterface* broadphase = new btDbvtBroadphase();

    btDefaultCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
    btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);

    btSequentialImpulseConstraintSolver* solver = new btSequentialImpulseConstraintSolver;

    btDiscreteDynamicsWorld* dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);

    dynamicsWorld->setGravity(btVector3(0, -10, 0));

    btCollisionShape* groundShape = new btStaticPlaneShape(btVector3(0, 1, 0), 1);

    btCollisionShape* fallShape = new btSphereShape(1);

    btDefaultMotionState* groundMotionState = new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, -1, 0)));
    btRigidBody::btRigidBodyConstructionInfo
        groundRigidBodyCI(0, groundMotionState, groundShape, btVector3(0, 0, 0));
    btRigidBody* groundRigidBody = new btRigidBody(groundRigidBodyCI);
    dynamicsWorld->addRigidBody(groundRigidBody);

    btDefaultMotionState* fallMotionState =
        new btDefaultMotionState(btTransform(btQuaternion(0, 0, 0, 1), btVector3(0, 50, 0)));
    btScalar mass = 1;
    btVector3 fallInertia(0, 0, 0);
    fallShape->calculateLocalInertia(mass, fallInertia);
    btRigidBody::btRigidBodyConstructionInfo fallRigidBodyCI(mass, fallMotionState, fallShape, fallInertia);
    btRigidBody* fallRigidBody = new btRigidBody(fallRigidBodyCI);
    dynamicsWorld->addRigidBody(fallRigidBody);

    std::cout << std::fixed << std::setprecision(2);

    for(int i = 0; i<300; i++) // Give it a lot of time to follow to the ground
    {
        dynamicsWorld->stepSimulation(1 / 60.f, 10);
    }

    btVector3 froce(0.0, 2000.0, 0.0);
    fallRigidBody->applyCentralForce(froce);// Apply a force on the Y axis

    for(int i = 0; i<50; i++) {
        dynamicsWorld->stepSimulation(1 / 60.f, 10);

        btTransform trans;
        fallRigidBody->getMotionState()->getWorldTransform(trans);

        std::cout << "Frame # : " << i
            << "\t: X: " << trans.getOrigin().getX()
            << "\t, Y: " << trans.getOrigin().getY()
            << "\t, Z: " << trans.getOrigin().getZ()
            << "\n";
    }

    dynamicsWorld->removeRigidBody(fallRigidBody);
    delete fallRigidBody->getMotionState();
    delete fallRigidBody;

    dynamicsWorld->removeRigidBody(groundRigidBody);
    delete groundRigidBody->getMotionState();
    delete groundRigidBody;

    delete fallShape;

    delete groundShape;

    delete dynamicsWorld;
    delete solver;
    delete collisionConfiguration;
    delete dispatcher;
    delete broadphase;

    return 0;
}

```

# Answer
> 3 votes
I looked in this issue, and it seems that you have to call the `activate` function on the `rigidbody` after applying the force. This article does say that you `generally do not have to` but it seems that you must do it manually once it is has gone to sleep.

---
Tags: c++, physics, bullet-physics
---


# Question
Title: Scale adaption based on distance to object
I have situation illustrated on image above, name displayed over the player. Text is rendered as 3d rectangle and rotated to face camera as billboard. (I am using this article http://blogs.msdn.com/b/shawnhar/archive/2011/01/12/spritebatch-billboards-in-a-3d-world.aspx) I just want to have size of the text always the same. Are there any common approach to adaptively scale object based on distance?

# Answer
> 1 votes
Objects in 3D space are transformed using world/view/projection matrices to give positions in projection space. You should be familiar with these from using `BasicEffect`.

You can use these matrices yourself to transform a position into projection space:

```
Matrix transform = (worldMatrix * viewMatrix * projMatrix);
Vector3 modelAttachPoint = Vector3.Zero; // where you want the label, in model space
Vector3 projPosition = Vector3.Transform(modelAttachPoint, transform);

```

Projection space runs from (-1,-1) in the bottom left corner of the viewport, to (1,1) in the top right (and from 0 to 1 on the Z axis for depth).

We could use simple maths to convert our projected position into pixel coordinates. But it's even easier to just take the matrix that `SpriteBatch` uses to go from pixel coordinates to projected coordinates, and invert it.

Fortunately - that very article you linked gives us the `SpriteBatch` projection matrix:

```
Viewport viewport = GraphicsDevice.Viewport;
Matrix spriteBatchMatrix = Matrix.CreateTranslation(-0.5f, -0.5f, 0) *
    Matrix.CreateOrthographicOffCenter(0, viewport.Width, viewport.Height, 0, 0, 1);

```

And we can use it like so:

```
Vector3 pixelPosition = Vector3.Transform(projPosition, spriteBatchMatrix.Invert());

```

Of course, that position won't necessarily line up with pixel boundaries (which you want for nice, sharp text). Also it has an unnecessary Z-coordinate. So let's finish up with something you can pass into `SpriteBatch`:

```
Vector2 spritePosition = new Vector2((float)Math.Floor(pixelPosition.X),
                                     (float)Math.Floor(pixelPosition.Y));

```

(Note: code in this answer is completely untested!)

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


# Question
Title: How do I implement swipe-to-throw in Andengine?
I have a ball sprite and I apply physics to it when the user swipes on it. I'd like the ball to start moving in the direction of the swipe.

How can I do this?

# Answer
> 1 votes
I have never written code for andengine but some pseudo like this may work:
**OnTouch:** You want to get the touch position.
**OnRelease:** You want to get the release position.
Theese two points can be used to create a direction vector. (The angle in between the points).

If you want, you can also use the distance between the points as force, but most likely you would like to use know how fast the user moved his finger, and you could initialize a timer on touch and stop it on release to know how fast moved his finger, and then multiply the delta-time with some speed variable.

---
Tags: android, physics, andengine, touch, gestures
---


# Question
Title: Expandable 2d environment by spawning and controlling individual tiles
what is the best way to implement an environment that is "expandable" in every direction so that when the player moves in any direction a new row or column of tiles that can be manipulated individually is created,however as the player moves into the new created area whenever he decides to comeback, the tiles that disappeared by going off the screen are there when he comes back.

What I'm trying to do is make a new row if the player moves upwards or downwards, or make a new column if the player moves sideways. But I can control the individual tiles to make them change colors or place items. Then whenever the player advances and new tiles are created and others are moved off the screen if the player decides to come back to the area the item that was placed and color change is still there. Sorry if I'm not explaining my best, if you need a better explanation I'll be happy to give you one. Thank you.

# Answer
> 1 votes
I don't know if it'll fit in your design, but here's how I'd do something like that.

> Let's assume:
>
> * that the default colour for your not-yet-visited tiles are pink and your visited tiles are white (as per in your question).
> * that the radius the player can see is 3 tiles, excluding the one on which he is standing, so it results in a 7 by 7 square.

**I would keep track only of the things that the player has modified.**

For example, if your player starts at position `[0, 0]`, you know how to generate the radius around him, so, for instance, tiles `[-3, -3]` through `[3, 3]` are generated as *pink tiles* and displayed. Now, since the player only went on tile `[0, 0]`, you make it as a *white tile* and keep only this information in a data container (for instance a `map` or a `set`). If he places an item, you also keep that information in another container. (Or you could have your data able to keep track of both.)

Then, as your player travels, you add your data about the tiles he travelled. At the same time, when you "create" a new row or a new column, in fact, you just show temporary information that is easy to generate "on the fly" (the *pink tiles*), and then you query your data containers to check if he's already been into the "generated" tiles, and modify them accordingly.

For instance, your player goes from tile `[0, 0]` to tile `[4, 0]`. This creates 4 *white tiles* in your data container. When he steps back on tile `[3, 0]`, the column 0 has to be *re-generated*. Which you do: all the generated tiles will be *white tiles*, but since you know you'll display tiles `[0, 3]` through `[0, -3]` (the whole column the player can now see), you'll query your data container and see that you have to put the tile at `[0, 0]` as a *white tile*. You'll also query you *items container* to see if he placed an item on one of these tiles.

Here is why I'd do it like that:

* You don't need to keep track of stuff you don't need (if you had to keep your infinite map in memory, it would end up taking a lot of memory).
* If your map becomes very large, you can easily partition your data into smaller containers.

# Answer
> 1 votes
The technique I use is to create a method of being able to (re)generate the map at any point.
I generally use simplex noise to create 2D height maps and the like (you could, for example, layer multiple noise maps with varying frequencies to emulate height, flora, terrain type/biomes, danger/savagery etc etc (obviously I have an rpg/fantasy game bias but they're just examples and the technique can be modified and used for just about anything)).
The advantage of this is that you can generate terrain on demand at any point in the 'world' and know that it will 'connect' with any previously generated sections of the world.
Track only the changes to the environment and apply them on regeneration.

---
Tags: java, 2d, architecture, sprites, software-engineering
---


title: How to spin an object on its own axis?

text:
# Question
Title: How to spin an object on its own axis?
I'm trying to spin up my own 3D vector graphics engine, so I'd like to do this without an existing library. And I don't seem to be able to find the math for the correct approach in rotating an object around its own axis.

I can definitely do x/y/z rotations around a chosen point with values pt.x pt.y and pt.z. But I am unsure of how to make them unique to the object's orientation, so they are always being expressed in relation to the monitor (not even the environment yet, just the screen).

So which mathematical concept am I supposed to be applying here?

# Answer
> 2 votes
You're going to have tons of questions regarding 3D math so I recommend you get the book Essential Math for Game Programmers, the 2nd Ed. I bought a copy myself and was reading it last night before bed.

http://essentialmath.com/book.htm

For your specific question you can use a rotation matrix to represent your object's orientation. You can concatenate this matrix with other transformations in order to update or apply additional transformations.

For example, if you build a matrix that will apply a small rotation about the x axis and apply this transformation to your objects orientation matrix, the orientation matrix will be rotated around the x axis by this amount. If you just want your object so spin about the x axis it should be translated to the origin before a rotation is applied, then translated back to it's original translation. This will prevent your object's translation from being rotated as well.

---
Tags: rotation, python, pygame
---


title: Repeat or wrap texture (DirectX 9)

text:
# Question
Title: Repeat or wrap texture (DirectX 9)
Sure there's something I'm missing about wrap/repeat textures in D3D 9. I've tried setting the sampler in the shader, i.e. :

```
sampler DiffuseSampler =
sampler_state
{
    Texture = <DiffuseMap>;

    MipFilter = NONE;
    MinFilter = POINT;
    MagFilter = POINT;

    AddressU = WRAP;    // Repeat on X
    AddressV = WRAP;    // Repeat on Y.
};

```

, and I've also tried doing it in code before I render the object:

```
device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0, D3DSAMP_ADDRESSU, D3DTADDRESS_WRAP);
device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0, D3DSAMP_ADDRESSV, D3DTADDRESS_WRAP);
device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
device->SetSamplerState(D3DVERTEXTEXTURESAMPLER0, D3DSAMP_MIPFILTER, D3DTEXF_NONE);

```

I thought there might be something screwy with my texture coordinates too, so I hard coded them to be 0.0, 0.0 on the left and 2.0, 2.0 bottom right. I expected x 2 repeat but got a similar result to the screenshot, with the texture top left and then what looks like clamp across the rest of the image.

What mistake have I made here? (Note that the screenshot isn't the 0.0, 0.0 -\> 2.0, 2.0 experiment I did, it's the general case I get as I'm panning my image around).

# Answer
The problem here is that you are setting a sampler for the vertex shader stage (D3DVERTEXTEXTURESAMPLER0 means the first slot) but you want to use it in your pixel shader. You should change it to null.
> 1 votes

---
Tags: textures, directx
---


# Question
Title: Problem calculating normals for heightmaps
So far I have been using normal avering to calculate the normals for my vertices in my heightmap, with good graphical result (see picture), however it is terribly slow. With a incresing image size the calculation time increases exponationally.

So I wanted to try implementing this algorithm insteed, but it isn't going very well. I have tried to trow around the variables a bit and tried diffrent combinations but nothing seems to work. Something that seems to be recurring is this shadow line pattern i get everywhere (the picture is a bit dark but i hope you can see the pattern).

My best guess to why this isnt working is because the algorithm isnt taking 2 of the neighboring vertices in to account in the calculation (See picture, blue is vertice we are trying to calculate normal for, green is the ones used in algorithm, red isnt used)

However, this algorithm seem to pop up in alot of places so that makes me think it has to be rigth. So im not sure if im doing it wrong somehow or if the algorithm is wrong. I was hoping some of you guys had runed in to the same problem and could give me some tips to what might cause this problem.

This is my translation of the algorithm im using

```
int cols = hmInfo.terrainWidth;
int rows = hmInfo.terrainHeight;

#define height(x, y)  hmInfo.heightMap[(y*cols) + x].y
XMVECTOR normal;
for(DWORD y = 0; y < rows; ++y)
{
    for(DWORD x = 0; x < cols; ++x)
    {

        float sx =  height( x < cols-1 ? x+1 : x, y) - height(x ? x-1 : x, y);
        if (x == 0 || x == cols-1)
              sx *= 2;

        float sy =height( x , y < rows-1 ? y+1 : y)- height(x, y ?  y-1 : y);
        if (y == 0 || y == rows -1)
            sy *= 2;

        normal=  XMVectorSet(-sx , 2.0f,  sy , 0.0f);
        normal = XMVector3Normalize(normal);

        tempSubset.vertices[y*cols+x].normal = XMFLOAT3(XMVectorGetX(normal),XMVectorGetY(normal), XMVectorGetZ(normal));

    }
}

```

PS. Seeing how it works with normal averaging im fairly sure that all other parts of the program is working fine DS.

# Answer
> 1 votes
turns out you have to be careful with your macros

```
#define height(x, y)  hmInfo.heightMap[(y*cols) + x].y

```

The y on the end was replaced by the macro

Working version

```
#define height(a, b)  hmInfo.heightMap[(b*cols) + a].y

```

Im supprised how this compiled and even worked without breaking

---
Tags: directx, graphics-programming, heightmap, normals
---


title: Ice sliding physics

text:
# Question
Title: Ice sliding physics
I am trying to implement ice sliding physics on a plane for my game. There are a lot of N64 games that implemented them perfectly well, like Banjo-Kazooie, Super Mario 64, Zelda: OoT and MM, etc.

Here is an example: http://youtu.be/p2D4Y4tMOas?t=19s

Looked up everywhere and I can't find a guide for it. Anyone knows how to do this? Thanks.

# Answer
> 2 votes
The very simple version is reducing the velocity of the player by a set amount (when he isn't holding down any controls) on normal terrain, and reducing it *less* on ice.

You can also go for the physics approach, which is more complicated, but will result in more realistic results.

**Crash Course - Physics**

The player has a mass. Ice (and other surfaces) has a friction coefficient. Multiply the coefficient by the mass of the player to get a scalar force. Apply the force in the opposite direction of the player's motion.

Force = Mass * Acceleration. Divide force by mass to get the acceleration of the player. Multiply acceleration by time (seconds) to get change in velocity.

---
Tags: 3d, physics, movement
---


# Question
Title: How to create a grid based on random shapes?
How to create a "grid" using actionscript like the image below?

Basically you have an area of 1100x615 which should be filled with shapes that could be rotated and scaled...

Collision detection perhaps or something less cpu intensive for flash (as3) to manage?

# Answer
**(1)** You may be able to adapt an algorithm used for creating word clouds.

Here's one example algorithm, based on Wordle's strategy. This works by choosing a start position/size/orientation for each object (generally starting with the biggest/most important ones), and trying to place it there. If it collides with an already-placed object, move it incrementally along a spiral expanding outward from the start position, and try again until you find a valid placement or you run out of places on the canvas.

This trial-and-error approach is slow, so you'll want a good way to accelerate your collision tests (some ideas at the links above), and possibly do the work in the background - say by generating level 2 off-screen while the player works on level 1.

**(2)** Another approach would be to use a force-directed graph to make objects jostle each other out of the way until a locally optimal spacing is found. Doing this with irregularly-shaped objects is nontrivial though. Once again this is a time-intensive iterative process, although you might be able to show it to the player before it's fully settled, turning the jello-like bobbing of the objects into an element of your game's style.

**(3)** A more experimental method would be to break your play space into polygonal cells (say, using a Voronoi tesselation), then assign an object to each cell. You then try to fit each object within its cell confines as best you can by rotating & scaling within tolerances. This is likely to produce more gaps than either option above, but has the advantage that it can be done in one pass without massive iteration, or collision tests between two arbitrary shapes.
> 5 votes

---
Tags: algorithm, actionscript-3, random, grid
---


title: Build unity like Transform class

text:
# Question
Title: Build unity like Transform class
I am building a Unity-like Transform class.

This is my header file:

```
#include "Common.h"

struct Transform
{
public:
        Transform();
        void Translate(float x, float y, float z);
        void Translate(const glm::vec3 &dir);
        void SetPosition(const glm::vec3 &pos);
        void SetYPosition(const float &pos);
        void Rotate(float x, float y, float z, bool world = true);
        void Rotate(const glm::vec3 &dir, bool world = true);
        void SetRotation(const glm::vec3 &rot);
        void Scale(const glm::vec3 &scale);
        void Scale(float x, float y, float z);
        const glm::vec3& GetScale();

        const glm::vec3& GetPosition();
        const glm::vec3& GetRotation();
        void LookAt(glm::vec3 targetPosition);

        glm::mat4 GetWorldMatrix();

        glm::vec3 Up();
        glm::vec3 Right();
        glm::vec3 Forward();

        glm::mat4 GetOrientation();
        glm::mat4 GetTranslation();
        glm::mat4 GetScaling();

        void NormalizeAngles();
private:
        glm::vec3 m_Position, m_Rotation, m_Scale;
        glm::mat4 m_Translation, m_Orientation, m_Scaling;

        bool m_NeedUpdate;
};

inline Transform::Transform()
{
        m_Scale = glm::vec3(1,1,1);
        m_NeedUpdate = true;
}

...

inline void Transform::Translate(float x, float y, float z)
{
        m_Position += glm::vec3(x,y,z);
        m_NeedUpdate = true;
}

inline void Transform::Translate(const glm::vec3 &dir)
{
        m_Position += dir;
        m_NeedUpdate = true;
}

inline void Transform::SetRotation(const glm::vec3 &rot)
{
        m_Rotation = rot;
        m_NeedUpdate = true;
}

inline void Transform::Rotate(float x, float y, float z,bool world)
{
        if(world)
                m_Rotation += glm::vec3(x,y,z);
        else
        {
                //TODO
                m_Rotation += glm::vec3(x,y,z);
        }

        m_NeedUpdate = true;
}

inline void Transform::Rotate(const glm::vec3 &rot,bool world)
{
        if(world)
                m_Rotation += rot;
        else
        {
                //TODO
        }
        m_NeedUpdate = true;
}

...

inline const glm::vec3& Transform::GetRotation()
{
        return m_Rotation;
}

...

```

And this is my C++ file:

```
#include "Transform.h"

static const float MaxVerticalAngle = 89.0f; //must be less than 90 to avoid gimbal lock

void Transform::NormalizeAngles()
{
        m_Rotation.y = fmodf(m_Rotation.y, 360.0f);
        //fmodf can return negative values, but this will make them all positive
        if(m_Rotation.y < 0.0f)
                m_Rotation.y += 360.0f;

        if(m_Rotation.x > MaxVerticalAngle)
                m_Rotation.x = MaxVerticalAngle;
        else if(m_Rotation.x < -MaxVerticalAngle)
                m_Rotation.x = -MaxVerticalAngle;
}

void Transform::LookAt(glm::vec3 targetPosition)
{
        if((targetPosition - m_Position) == glm::vec3(0,0,0)) return;
        glm::vec3 direction = glm::normalize(targetPosition - m_Position);
        m_Rotation.x = asinf(-direction.y)* RadToDeg;
        m_Rotation.y = -atan2f(-direction.x, -direction.z)*RadToDeg;

        NormalizeAngles();
        m_NeedUpdate = true;
}

glm::mat4 Transform::GetOrientation()
{
        if(m_NeedUpdate)
        {
                m_Orientation = glm::rotate(m_Rotation.x, glm::vec3(1,0,0));
                m_Orientation = glm::rotate(m_Orientation, m_Rotation.y, glm::vec3(0,1,0));
                m_Orientation = glm::rotate(m_Orientation, m_Rotation.z, glm::vec3(0,0,1));
        }

        return m_Orientation;
}

glm::mat4 Transform::GetTranslation()
{
        if(m_NeedUpdate)
        {
                m_Translation = glm::translate(m_Position);
        }
        return m_Translation;
}

...

```

I have problems implementing the rotation correctly (the //TODO commented part). Currently rotation is only working in world orientation, but I would like to select whether orientation should be in world or in local orientation. Also translation currently works in world space, it also should be selectable whether to translate in local orientation or in world orientation.

How can I make my translation and rotation operations operate on local coordinates?

# Answer
> 4 votes
Local versus world is just a matter of the order in which you compose transforms. For instance, when using row-vector math, multiplying the current local-to-world transform by a new transform on the left will perform the new transform in local space, since it will be equivalent to doing the new transform followed by the old local-to-world transform. Multiplying by the new transform on the right will perform it in world space, since it will be equivalent to doing the old local-to-world followed by the new transform. If using column-vector math, the order is the other way around.

---
Tags: opengl, transformation, glm
---


title: How can I reuse animated meshes?

text:
# Question
Title: How can I reuse animated meshes?
When creating meshes, I made a mesh class and then used that one as base model and redrew that same mesh for each instance of an object with that mesh. (For eaxmple, one rock mesh, many rock objects.) This is good for saving memory.

Now I'm trying to do this for dynamic models. I have implemented an MD5 animation and I can't really use the same method, because different instances of the same model may be in different stages of the animation.

Is there a similar design pattern that works for animated meshes and which will let me avoid creating a mesh per instance?

# Answer
> 3 votes
You can still have the same single mesh just with different bones matrices (prepared for different animation frames of meshes instances) and do the transformations in shader. For that you need to decouple mesh from animated bones.

So that you can still redraw same mesh several times, just changing the meshes position AND bones matrices between drawcalls. From shaders perspective position uniforms are the same as bones matrices uniforms - both transform vertices in some way.

**Will that work for MD5anim joints?**

That will work irregardless of skeleton composition because in the end skeleton bones/joints get converted into matrices that affect vertices in shader. Shader do not care how these matrices were generated.

P.S. In fact I have just converted my testbed tool from using MD5 joints into LW bones without touching vertex/matrix code. Just had to change the order of rotation/offset for matrix generation.

---
Tags: game-design, animation, design-patterns, skeletal-animation
---


# Question
Title: Why OpenGL X and Z axis got inverted sometimes?
I'm having some troubles with my game code. I'm developing a **Voxel Engine** and everything is fine, but sometimes (like 30% of times) when I build and run my project, the X and Z axis got inverted (I know it because the model position and Camera motion), and I dont know why this is hapenning.

May this is a bug on my graphic card, or my code is broken is some place? If so, any clue where to start looking for?

Here are two pics to show what i'm saying, I didnt made any change in code, just compiled twice and got it like this:

Here are my settings:

**Compiler:** VS 2013 Express **PC:** Dell Inspiron R14 **SO:** Windows 8 **Graphics Card:** NVIDIA GT 630M and Intel HD Graphics 4000 **Libs:** GLFW 3.0.4, GLEW 1.10, GLM 0.9.5.2 **OpenGL Context:** 4.0

# Answer
> 1 votes
I found the main problem. My Camera rotation didnt got an yAxis clamp, so when I build my project and click on it, the mouse position was different and sometimes made the yAxis be 180 or -180, which caused the issue.

A simple clamp solved it:

```
yAxis = glm::clamp(yAxis, -90.0f, 90.0f);

```

Thanks for those who help me out!

---
Tags: opengl, glfw
---


# Question
Title: Vertical Scrolling In Tile Based XNA Platformer
I'm making a 2D platformer in XNA 4.0. I have created a working tile engine, which works well for my purposes, and Horizontal Scrolling works flawlessly, however I am having great trouble with Vertical scrolling.

I Basically want the camera to scroll up (world to scroll down) when the player reaches a certain Y co-ordinate, and I would also like to automatically scroll back down if coming down, and that co-ordinate is passed. My biggest problem is I have no real way of detecting the direction the player is moving in using only the Y Co-ord.

Here Is My Code Code For The Camera Class (which appears to be a very different approach to most camera classes I have seen).

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace Marvin
{
    class Camera : TileEngine
    {
        public static bool startReached;
        public static bool endReached;

        public static void MoveRight(float speed = 2)
        {

            //Moves The Position of Each Tile Right
            foreach (Tile t in tiles)
            { if(t!=null) { t.position.X -= speed; } }

        }

        public static void MoveLeft(float speed = 2)
        {
            //Moves The Position of Each Tile Right
            foreach (Tile t in tiles)
            { if(t!=null) { t.position.X += speed; } }

        }

        public static void MoveUp(float speed = 2)
        {
            foreach (Tile t in tiles)
            { if(t!=null) { t.position.Y += speed; } }

        }

        public static void MoveDown(float speed = 2)
        {
            foreach (Tile t in tiles)
            { if(t!=null) { t.position.Y -= speed; } }

        }

        public static void Restrain()
        {
            if(tiles.Last().position.X<Main.graphics.PreferredBackBufferWidth-tiles.Last().size.X)
            { MoveLeft(); endReached = true; }
            else
            { endReached = false; }

            if(tiles[1].position.X>0)
            { MoveRight(); startReached = true;}
            else
            { startReached = false; }
        }
    }
}

```

Here is My Player Code for Left and Right Scrolling/Moving

```
        if (Main.currentKeyState.IsKeyDown(Keys.Right))
        {
            Camera.MoveRight();

            if(Camera.endReached)
            { MoveRight(2); }
            else
            {
                if(marvin.GetRectangle().X!=Main.graphics.PreferredBackBufferWidth-(marvin.GetRectangle().X+marvin.GetRectangle().Width))
                { MoveRight(2); Camera.MoveLeft(); }
            }

        }

        if(Main.currentKeyState.IsKeyDown(Keys.Left))
        {
            Camera.MoveLeft();

            if(Camera.startReached)
            { MoveLeft(2); }
            else
            {
                if(marvin.GetRectangle().X!=Main.graphics.PreferredBackBufferWidth-(marvin.GetRectangle().X+marvin.GetRectangle().Width))
                { MoveLeft(2); Camera.MoveRight(); }
            }

        }

        Camera.Restrain();

        if(marvin.GetRectangle().X>Main.graphics.PreferredBackBufferWidth-marvin.GetRectangle().Width)
        { MoveLeft(2); }

        if(marvin.GetRectangle().X<0)
        { MoveRight(2); }

```

And Here Is My Player Jumping/Falling Code which may cause some conflicts with the vertical camera movement.

```
        if (!jumping)
        {
            if(!TileEngine.TopOfTileCollidingWith(footBounds))
            { MoveDown(5); }
            else
            {
                if(marvin.GetRectangle().Y != TileEngine.LastPlatformStoodOnTop()-marvin.GetRectangle().Height)
                {
                    float difference = (TileEngine.LastPlatformStoodOnTop()-marvin.GetRectangle().Height) - (marvin.GetRectangle().Y);

                    marvin.SetRectangle(marvin.GetRectangle().X,(int)(marvin.GetRectangle().Y+difference));
                    armR.SetRectangle(armR.GetRectangle().X,(int)(armR.GetRectangle().Y+difference));
                    armL.SetRectangle(armL.GetRectangle().X,(int)(armL.GetRectangle().Y+difference));
                    eyeL.SetRectangle(eyeL.GetRectangle().X,(int)(eyeL.GetRectangle().Y+difference));
                    eyeR.SetRectangle(eyeR.GetRectangle().X,(int)(eyeR.GetRectangle().Y+difference));
                }
            }
        }

        if (Main.currentKeyState.IsKeyDown(Keys.Up) && Main.previousKeyState.IsKeyUp(Keys.Up) && TileEngine.TopOfTileCollidingWith(footBounds))
        { jumping = true; }

        if(jumping)
        {
            if(TileEngine.LastPlatformStoodOnTop()>0 && (TileEngine.LastPlatformStoodOnTop() - footBounds.Bottom)<120)
            { MoveUp(5); }
            else
            { jumping = false; }
        }

```

All player code I have tried for vertical movements has failed, or caused weird results (like falling through platforms), and most have been a variation on the method I described above, hence I have not included it. I would really appreciate some help implementing a simple vertical scrolling into this game, Thanks.

# Answer
> 1 votes
I would rather compare the difference between the player and the camera. This is a very simple check:

```
Vector2 playerInRelationToCamera = playerPosition - cameraPosition;

```

then if the distance from camera to player is larger than, say a third of a screenheight, then you can move the camera closer:

```
if(playerInRelationToCamera.Length() > screenHeight/3)
{
  cameraPosition += playerInRelationToCamera / 10;
}

```

Would this work for you?

# Answer
> 0 votes
To detect the direction where your character is moving, just compare the character's current position with its position in the previous game loop update:

```
enum VerticalDirection { Up, Down, Stationary }

VerticalDirection GetDirection(Vector2 previousPosition, Vector2 currentPosition)
{
   if (previousPosition.Y == currentPosition.Y)
   {
      return VerticalDirection.Stationary;
   }
   if (previousPosition.Y > currentPosition.Y)
   {
      return VerticalDirection.Down;
   }
   return VerticalDirection.Up;
}

```

Issues like you described (falling through platforms) might be caused by missed collisions. This can happen if the difference between the character's current and previous position is too big to be detected by your collision detection method.

---
Tags: xna, platformer, scrolling
---


# Question
Title: How to figure out a users earnt exp based upon calculating the difference by user and player by x?
How would I figure out a users earnt EXP based upon calculating the difference by user and player by x using this format?

If the user is 60 levels less than me, I would get 0 exp (as that's just bullying).

If the user is within 21 and 59 levels less than me, I would get 1 exp.

If the user is less than 20 levels of mine, I would get 2 exp.

If the user is the equal level they would get 3 exp, however if the user is within my level, and 20 above me I would get 4 exp.

If they were between 21 and 40 levels above me I would get 5 exp

If they were 41 and 60 levels above me I would get get 6 exp

and if they were 61+ levels above me I would get 7 exp

So I'm looking to do something like this -

How would it structure if I wanted to make it (player being me, and the user is the opponent)

```
if( $PLAYER->level is more than 60 of $USERS->level )
{
$earn = 0;
}
elseif( $PLAYER->level is between 21 and 59 more than $USERS->level )
{
$earn = 1;
}
elseif( $PLAYER->level is between 1 and 20 more than $USERS->level )
{
$earn = 2;
}
elseif( $PLAYER->level == $USERS->level )
{
$earn = 3;
}

```

I know in SQL they have a between operator, but I cannot seem to find a a PHP one and/or figure out a solution to display what I intend to do above.

Is it possible to do what I intend? Or do I need to find a new solution?

# Answer
> 1 votes
It looks like you might be better off with some formula:

```
// keep the sign separate
int sign = enemyLevel > playerLevel ? 1 : -1;
// Calculate the xp as 1 xp per 20 level differences
// Ensures that no negative xp is given
int givenExp = math.min(0, 3 + (sign * math.floor(math.abs(enemyLevel - playerLevel)/20.f)));

```

What this does is clamp each 20 levels to 1 xp. Everything is rounded down, so 39 levels would be the same as 20 levels, but 40 levels would give another xp.

To make things simple, I removed the sign and added it later, but you could handle negative and positive level differences separately if you want. At least to me, it seems like taking down a mob 20 levels higher than you would be a feat worth more xp.

# Answer
> 0 votes
"`x` between `a` and `b`" is equivalent to satisfying both `a <= x` and `x <= b`. In your case, `x` is the difference between the two levels and `a` and `b` the particular bounds you want to test against.

I would recommend that you define a boolean function `between(x,a,b)` that evaluates the between-ness of a value against a range.

All you've got to do then is phrase your conditionals in the form "`x` between `a` and `b`", like `between($PLAYER->level - $USERS->level, 21, 59)` to determine whether the signed difference between the player level and user level is between 21 and 59.

---
Tags: rpg, php, mathematics
---


# Question
Title: How should I start with Android development? I am basically a PHP HTML JAVASCRIPT developer
I am a PHP developer wanting to learn Android game programming.

I tried java with ADT and android SDK, but I found Java confusing because of its complex Object-Oriented structure.

I've heard we can develop mobile games with PhoneGap or Appcelator using HTML5 and JS. I know both of those very well, so I'd ratehr not use Java.

What tool or language should I start my Android game development in?

# Answer
In my own case, I found it extremely valuable to develop my game using (almost) pure JavaScript, using Dojo to facilitate some more mundane tasks (event publish/subscribe, browser sniffing, DOM manipulation) as well as adopt its AMD design methodology.

Apart from this, I've written my own sound, graphics, sprite and network-packet modules, and linked the game client to a node.js game-server (actionHero, to be specific). My own model is client/server, which differs from your mileage. I wanted to include that here to illustrate that HTML5 game development is entirely in the realm of "possible", if you're structured and using technologies available to you to make your development tasks simpler.

In terms of pure JavaScript, check out http://mobile.smashingmagazine.com/2012/10/19/design-your-own-mobile-game/ ... it seems to be most of what you're looking for. I don't have experience with PhoneGap other than to suggest to continue to look into it, as it seems to be the right direction to go for your intended platform.

The trade-off of going the HTML5/JS/PhoneGap (cross-platform capability at reduced performance) route over the Java/Android SDK (better performance, but limited to Android devices) route is fairly obvious, but is also worth mentioning here.
> 1 votes

---
Tags: android, javascript, html5, corona-sdk
---


title: Homeworld style orbital camera concept

text:
# Question
Title: Homeworld style orbital camera concept
So I spent some time thinking of how I'm going to make a camera similar to what's used in Homeworld (a 3D space RTS, in which your camera can be rotated around your units to look at them from any angle or distance). I'm relatively new to game development so building a camera from scratch is something I've never even conceptualized.

What I came up with that I think could work is having an invisible object as the camera's look-at point. When you pan the camera at the edges, the object moves with the camera just in the opposite direction on some axes. When you zoom there is a min and max distance the camera can translate from and to this object. When you focus on a selected unit, this object moves to the coordinates of that selected unit, forcing the camera to look at it and translate based on the min-max distance, and when you orbit the camera it will orbit around this object.

This seems great to me unless someone has an easier or more efficient method?

# Answer
I would suggest creating an arc-ball camera. This is a camera that can orbit around the point-of-interest and change its distance from the point-of-interest (basically zooming in and out).

By simpling changing the location of the point-of-interest you get panning for free ;).

Have a look at this code snippet: http://roy-t.nl/index.php/2010/02/21/xna-simple-arcballcamera/

(disclaimer: link to my own blog)

Edit: added full code so it wont be lost.

```
public class ArcBallCamera
{

    public ArcBallCamera(float aspectRation, Vector3 lookAt)
        : this(aspectRation, MathHelper.PiOver4, lookAt, Vector3.Up, 0.1f, float.MaxValue) { }

    public ArcBallCamera(float aspectRatio, float fieldOfView, Vector3 lookAt, Vector3 up, float nearPlane, float farPlane)
    {
        this.aspectRatio = aspectRatio;
        this.fieldOfView = fieldOfView;
        this.lookAt = lookAt;
        this.nearPlane = nearPlane;
        this.farPlane = farPlane;
    }

    /// <summary>
    /// Recreates our view matrix, then signals that the view matrix
    /// is clean.
    /// </summary>
    private void ReCreateViewMatrix()
    {
        //Calculate the relative position of the camera
        position = Vector3.Transform(Vector3.Backward, Matrix.CreateFromYawPitchRoll(yaw, pitch, 0));
        //Convert the relative position to the absolute position
        position *= zoom;
        position += lookAt;

        //Calculate a new viewmatrix
        viewMatrix = Matrix.CreateLookAt(position, lookAt, Vector3.Up);
        viewMatrixDirty = false;
    }

    /// <summary>
    /// Recreates our projection matrix, then signals that the projection
    /// matrix is clean.
    /// </summary>
    private void ReCreateProjectionMatrix()
    {
        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, AspectRatio, nearPlane , farPlane);
        projectionMatrixDirty = false;
    }

    #region HelperMethods

    /// <summary>
    /// Moves the camera and lookAt at to the right,
    /// as seen from the camera, while keeping the same height
    /// </summary>
    public void MoveCameraRight(float amount)
    {
        Vector3 right = Vector3.Normalize(LookAt - Position); //calculate forward
        right = Vector3.Cross(right, Vector3.Up); //calculate the real right
        right.Y = 0;
        right.Normalize();
        LookAt += right * amount;
    }

    /// <summary>
    /// Moves the camera and lookAt forward,
    /// as seen from the camera, while keeping the same height
    /// </summary>
    public void MoveCameraForward(float amount)
    {
        Vector3 forward = Vector3.Normalize(LookAt - Position);
        forward.Y = 0;
        forward.Normalize();
        LookAt += forward * amount;
    }

    #endregion

    #region FieldsAndProperties
    //We don't need an update method because the camera only needs updating
    //when we change one of it's parameters.
    //We keep track if one of our matrices is dirty
    //and reacalculate that matrix when it is accesed.
    private bool viewMatrixDirty = true;
    private bool projectionMatrixDirty = true;

    public float MinPitch = -MathHelper.PiOver2 + 0.3f;
    public float MaxPitch = MathHelper.PiOver2 - 0.3f;
    private float pitch;
    public float Pitch
    {
        get { return pitch; }
        set
        {
            viewMatrixDirty = true;
            pitch = MathHelper.Clamp(value, MinPitch, MaxPitch);
        }
    }

    private float yaw;
    public float Yaw
    {
        get { return yaw; }
        set
        {
            viewMatrixDirty = true;
            yaw = value;
        }
    }

    private float fieldOfView;
    public float FieldOfView
    {
        get { return fieldOfView; }
        set
        {
            projectionMatrixDirty = true;
            fieldOfView = value;
        }
    }

    private float aspectRatio;
    public float AspectRatio
    {
        get { return aspectRatio; }
        set
        {
            projectionMatrixDirty = true;
            aspectRatio = value;
        }
    }

    private float nearPlane;
    public float NearPlane
    {
        get { return nearPlane; }
        set
        {
            projectionMatrixDirty = true;
            nearPlane = value;
        }
    }

    private float farPlane;
    public float FarPlane
    {
        get { return farPlane; }
        set
        {
            projectionMatrixDirty = true;
            farPlane = value;
        }
    }

    public float MinZoom = 1;
    public float MaxZoom = float.MaxValue;
    private float zoom = 1;
    public float Zoom
    {
        get { return zoom; }
        set
        {
            viewMatrixDirty = true;
            zoom = MathHelper.Clamp(value, MinZoom, MaxZoom);
        }
    }

    private Vector3 position;
    public Vector3 Position
    {
        get
        {
            if (viewMatrixDirty)
            {
                ReCreateViewMatrix();
            }
            return position;
        }
    }

    private Vector3 lookAt;
    public Vector3 LookAt
    {
        get { return lookAt; }
        set
        {
            viewMatrixDirty = true;
            lookAt = value;
        }
    }
    #endregion

    #region ICamera Members
    public Matrix ViewProjectionMatrix
    {
        get {return ViewMatrix * ProjectionMatrix; }
    }

    private Matrix viewMatrix;
    public Matrix ViewMatrix
    {
        get
        {
            if (viewMatrixDirty)
            {
                ReCreateViewMatrix();
            }
            return viewMatrix;
        }
    }

    private Matrix projectionMatrix;
    public Matrix ProjectionMatrix
    {
        get
        {
            if (projectionMatrixDirty)
            {
                ReCreateProjectionMatrix();
            }
            return projectionMatrix;
        }
    }
    #endregion
}

```
> 2 votes

---
Tags: camera, orbit
---


# Question
Title: Calculate turn rate between xy and target xy on a moving sprite with variable speed
My First question on here so be kind...

I am writing an aerodrome simulator in as2, I need to calculate a turn rate between 2 points so that the aircraft turns nicely. I have tried a few things but the maths forums on this type of subject use complex calculations and I struggle to understand them. I need an answer in a more variable specific format.

I have the XY of both tile and target, the speed of tile and the distance of target from the tile.

I use vector math, with frame time calculations to move the tile. I already have a good calculation for shortest turn i.e. left right.

I need to calculate the turn rate required to go from point a to point b in a nice fluid motion and turn the tile/aircraft in a nice fashion.

Any help would be much appreciated.

# Answer
> 3 votes
As hinted by user concept3d, it is difficult to help you without further details about your implementation approach. I'm going to give it a shot nevertheless, but that means that I have to make some assumptions that may or may not be true for your code. In any event, I hope that the following is general enough that you can adapt it if necessary.

The first assumption I'm making is that you really only need to get the plane to the target point, and it doesn't matter to you at which angle it arrives there. My suggestion is to understand the curve the plane is supposed to take as a segment of a larger circle. The following is thus an idea how to construct that circle and how to use it to calculate a turn rate.

Let's recap the situation. You have a plane in flight, i.e., with a current direction and a current speed and you want it to reach a certain destination. Assuming we're talking about 2D, this situation essentially looks like this:

We can understand this then in terms of points and vectors like so: the plane's current position **p** is a `(x,y)` point, its direction is given by a two-dimensional vector, its speed by a scalar (potentially encoded as the length of the direction vector, but maybe not), and the destination **t** is another `(x, y)` point.

In this image, the current directional vector is drawn in blue, and the vector between **p** and **t** is drawn in red:

Let's call the angle between the two *alpha* (α). You can easily compute it using the dot product between the red and the blue vector.

Now, I want to find a circle so that both **p** and **t** lie on the circle's circumreference so that the plane can get from **p** to **t** by simply flying along the circle.

There are many different circles that have that both **p** and **t** lying on their circumreference, but they all have something in common: the distance from the circle's center point **c** must be the same for **p** as for **t**. This is because the distance between every point on the circumreference to the center is exactly the radius of the circle, and so it must also be for **p** and **t**.

So we know that the center point of our circle is equally far away from **p** and from **t**. But that means that it has to be somewhere on a line that is perpendicular to the red vector and intersects it halfway, like so:

But what would be a good point to pick? We know that we could theoretically use any point on that center line and draw a circle around it that would go through **p** and **t**, so which one should we use?

Well, since we want a *smooth* transition from the current position to the target point, we want to have a circle that won't make our plane change course abruptly when it enters the circle. At first, new direction given by the circle should at first differ only very slightly from the current direction of flight.

In order to achieve this, we are going to pick the circle for which the blue directional vector that represents the plane's *current* direction touches the circle tangentially in **p**.

But how do we construct that circle? How do we know where we have to place **c** on the horizontal split line? Or, equivalently, how big do we have to make the radius **r**? (Make sure you understand that the latter question about the radius is actually equivalent to knowing where to place **c** on the horizontal split line.)

First, we note that the radius **r** is perpendicular to the blue directional vector, i.e., the angle between the two is 90 degrees. Then we note that there's another 90 degree angle, namely between the red vector and the horizontal split line on which **c** lies. That means the **r** is the hypotenuse of a right-angled triangle.

It becomes a bit clearer if we rotate that triangle so that **r** is horizontal and the right angle is at the top.

So we already know two of the angles in that triangle, the right angle at the top, and the one at the corner **p** which is `90° - α`. Since the sum of all angles in a triangle is `180°`, we can calculate the angle at **c**:

```
right_angle + angle_at_p + angle_at_c = 180°
                           angle_at_c = 180° - right_angle - angle_at_p
                           angle_at_c = 180° -     90°     - (90° - α)
                           angle_at_c =       90°          -  90° + α
                           angle_at_c = α

```

Oh, sweet! The angle at **c** is actually just `α`.

And we also know another thing: we know the length of the red line in the triangle. Well, not yet, but we can compute it. Remember that in the original picture the red line is the vector from current position **p** to the target position **t**. Therefore all we have to do is compute the length of that vector and divide it by two: |**t** \- **p**| / 2.

Of course, this is done with the formula: `sqrt((tx - px) ^ 2 + (ty - py) ^ 2) / 2`

Now, with that knowledge and a little trigonometry we can easily calculate what we're actually after: the length of **r**. For that, we remember that sine of an angle is defined as the ratio of the length of the side that is opposite that angle to the length of the hypotenuse.

```
sin(α) = red_line / r

```

Therefore we have `r = |t - p| / 2sin(α)`.

Okay. That's pretty good.

Now, the next thing we're interested in is how long the arc is that the plane has to fly from **p** to **t** if it follows the circle. That's actually not that difficult to compute. We've just seen that the angle at **c** in the lower triangle is equal to `α`. And the upper triangle is pretty much the same as the lower triangle, just mirrored. So the angle at **c** in the upper triangle is also `α`, which gives us a total angle of  for the full arc.

As we know, the length of the full circumreference of a circle is `2πr`. But here, we don't want to fly around the full circle (2π) but only along the length of the arc (2α). Thus we get as the length to fly:

```
flight_length = 2αr
              = 2α|t - p| / 2sin(α)
              =  α|t - p| / sin(α)

```

So with this computation, we know two things now:

1. The total arc distance our plane has to fly from **p** to **t** (`= flight_length`)
2. The total angle it has to turn along the way (`= 2α`)

That's pretty much all you need. The only thing that's missing is how to marry that with the plane's current speed.

Let's assume that speed is given as pixels per tick. Since we know the total flight length of the turn, we can calculate how many ticks it is going to take our plane to make this turn. Dividing the total turn angle by that number tells us how much the plane has to turn in each tick.

Thus to go from **p** to **t** in a smooth turn can be done by adjusting the plane's direction through a small rotation every tick. And with the above we know everything we have to know to compute the amount of that rotation.

As user Yos233 has already pointed out, the circle approach might give you awkward results in some situations, depending on the relative location of the current and target and position together with the current flight direction. But you can always find a way to reduce such special cases to the above method. For instance, if the target is so far away that you'd end up with a giant circle, you could add some code that uses an intermediate auxiliary target point that is much closer. This should be chosen so that the direction of the plane when it reaches the auxiliary target is so that it can simply fly straight on from there in order to reach the actual destination.

But I would suggest trying out the above method with some easy cases first and see if you like it. If you then need help with the special cases too, I suggest you simply post a new question here.

# Answer
> 1 votes
One easy way to do this is the following algorithm that is executed each tick:

```
if (the target is straight ahead) then
    keep flying straight on
else
    rotate a little bit towards the target

```

It's easy to see that this algorithm works... but we have to talk about what "a little bit" means. Certainly, there's a maximum angle you want your plane to turn in a single tick, or else the flight will look unnatural. Imagine the plane doing a 90° jump from one tick to the next. That would probably not look very convincing.

So you could either define a constant `MAX_TURN_ANGLE` which you simply find by testing what works for you; or you make the maximum turn angle a function of the plane's current speed, so that it must take wider turns when it's flying very fast. Again, you could test whatever looks best in your opinion; for now I assume that you can somehow determine the maximum angle your plane can turn.

But then we have to ask ourselves: does it always make sense to do the maximum turn possible?

I think the answer to that one is *no* because it won't always lead to very graceful turns. Imagine the target is 90° to the right with respect to the current flight direction, and quite a bit away. There are two extreme ways how to turn:

1. Turn as quickly as possible and then fly the rest of the way in a straight line.
2. Fly a very loooong arc that will make you reach the target before you fly straight again.

(The second variation is what my other answer produces.)

But perhaps the actually best way to do it is somewhere in the middle: first fly a graceful turn and then do the rest in a straight line.

Here's one idea how to implement that:

1. Compute the angle between the current direction and a straight line to the target
2. Have a factor between `0` and `1`
3. Multiply the angle from 1. with the factor.
4. If the result is smaller then the maximum turn angle, use it for the turn; else use the maximum turn angle.

You could play with the factor in step 2. and see what gives good result. Maybe something around 0.5 would be a good starting point, but you could also make it a function of the distance to the target: if it's far away, use a higher value, if it is already quite close, use a smaller value.

As a matter of fact, I think this factor should be what determines the maximum turn angle: obviously the greatest possible angle between the current direction of flight and the target is 180° -- so you should should pick a factor that even in that extreme case leads to a maximum turn angle that still looks believable.

There's one more thing though that we have to pay attention to: since we're using a maximum turn angle, it means that there is a "smallest circle" that our plane can fly. That is, if we wanted our plane to fly a circle, the diameter of that circle would be directly dependent on how much the plane can rotate maximally in every tick.

As a consequence, if the target destination lies inside that smallest circle, i.e., is closer than the diameter of the smallest circle, we can never reach it with the above method. In such a case, the best strategy is *to fly in the opposite direction*, i.e., away from the target. That is to as quickly as possible increase the distance between the plane and its target so that it is no longer inside the "smallest circle". Once it is outside, we will fall back to the standard method above.

# Answer
> 0 votes
If I were you, I would use a simple algorithm to point the aircraft at the target. You can use a `turnrate` variable to keep track of how quickly it is turning. This is something I am using in my project.

Within the update method, calculate the projected heading a few seconds in the future. If the projected heading has not passed the target heading, increase the turn rate (up to a maximum). If the projected heading is beyond the target heading, reduce the turn rate.

---

The reason I highly suggest you do this is because the mathematics for constructing and following a curve between two points is very complicated. It has to be to handle all of the special cases that you might encounter. Like, what happens when your target is much further east than north, but your plane is heading north? You couldn't construct a circle between the points in a way that works.

If you would like me to go into further detail in a second answer I will, but only at the abstract level. I have no idea how you would implement it in your program.

# Answer
> 0 votes
I would look into using a Bezier Curve. You can have easy curves like you show above, or more complex curves (even nested) using Bezier splines. The algorithms are pretty straightforward and explained well on Wikipedia :)

---
Tags: 2d, rotation, direction
---


# Question
Title: How do I create a player movement system in Farseer?
My group of students is helping produce a a 2D platformer. We tried making a pixel-based collision system which fell through. Now I am trying this physics engine on for size and see new ways to create and control my player. Like the obvious circle body player:

I was using a different type of player movement system like this XNA video example.

What system would work for a player that needs to be able to jump and move in mid-air (as in the above link), and can run up slopes like the circular body example?

I guess that the circular body can be made to do anything, but would like community input.

# Answer
> 4 votes
Please take my answer as "the *right* way to do this", not necessarily the "good for a student project" way.

**Rigid body physics are entirely inappropriate for modeling "walking" behaviour.**

Rigid body physics are good for handling things like bouncing and friction. Which are things you want to avoid in a typical platformer. There is no "right shape" that will make a satisfying platformer character on its own.

---

Basically you need to not be afraid to take matters into your own hands and "override" the physics engine. Rather than working with impulses and forces, like you might for typical physics bodies, you should manually control your player's position and velocity. (Sounds scary, but it's perfectly ok to do.)

I recommend: Before the physics step, set the velocity to an appropriate value using typical platformer movement mechanics. After the physics step, modify the position to correct any unplatformerly behaviours (I find it best to "snap" the player object onto the ground, rather than relying on physics - which can cause the player to "skip" off the ground).

The actual shapes you use are then fairly irrelevant.

Obviously this is a fair bit more work, and you have to be able to deal with the 2D geometry calculations. But the results are markedly better.

---

**Here's how I do it:**

My initial attempts used a diamond shape, which is advantageous because it only has one point of contact with the ground to worry about (similar benefits to using a circle, only better). I ignore/cancel collisions with this point in the physics engine (if they're with a ground surface) - because I handle them myself by snapping it to the ground in my "fix-up" step.

(The "weight" effect of the player in that video is done manually too. Without it, this works better with static level geometry.)

More recently I have taken to using a "hovering rectangle". Rather than snapping to the ground, I snap some distance above it. The rectangle body provides collision detection with the walls and ceiling, while the hover behaviour handles the floor.

I'm actually exploring doing away with the rigid body entirely, because I'm working on movements like wall jumping, etc. And, again, rigid bodies aren't well suited for simulating these kind of human movements.

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


# Question
Title: How can I get a pointer to a resource via a base type handle without dynamic_cast?
I'm building my own pet engine and after struggling with how to handle resource ownership for a while, I came across this question and specifically Josh and Sean's responses (as well as Sean's blog on shared\_ptr), which really made a whole lot of sense to me. So I went ahead and implemented my own similar system, and so far it's working great except for one minor snag - what do I do when I need to access a resource of a derived type when the handle only refers to the base type?

Say for instance I have a Material class that keeps a list of handles to textures it needs for rendering:

```
class Material
{
public:
    void SetTexture(int textureSlot, const Handle<Texture>& texture);
private:
    SomeContainer<Handle<Texture>> m_textures;
};

```

Then I grab a handle to a texture from my texture library, set it to the material, and everything works great:

```
Handle<Texture> fnorbTexture = TextureLibary::GetResource("fnorb.tga");
fnorbMaterial->SetTexture(0, fnorbTexture); // fnorbtastic!

```

But what happens now when I have a RenderTarget class that derives from Texture?

```
class GraphicsSystem
{
public:
    void SetRenderTarget(int slot, Handle<RenderTarget> renderTarg);
    // Other stuff
};

Handle<Texture> renderTarg =
    TextureLibrary::PleaseGiveMeARenderTarget(width, height, flags);

// ERROR: Can't cast Handle<Texture> to Handle<RenderTarget>!
graphicsSystem->SetRenderTarget(0, renderTarg);
// ... Render stuff to render target ...

// Set the current render target back to the standard frame buffer
graphicsSystem->SetRenderTarget(0, kNullHandle);
// Now use the render target as a texture
superAwesomeBlorgomaticPostEffectMaterial->SetTexture(0, renderTarg); // OK!

```

Or maybe:

```
Handle<RenderTarget> renderTarg =
    RenderTargetLibrary::PleaseGiveMeARenderTarget(width, height, flags);

graphicsSystem->SetRenderTarget(0, renderTarg); // OK!
// ... Render stuff to render target ...

// Set the current render target back to the standard frame buffer
graphicsSystem->SetRenderTarget(0, kNullHandle);
// Now use the render target as a texture
// ERROR: Can't cast Handle<RenderTarget> to Handle<Texture>!
superAwesomeBlorgomaticPostEffectMaterial->SetTexture(0, renderTarg);

```

Possible solutions, and my thoughts on each:

Borrow a render target resource as a `Handle<RenderTarget>`, and in `Material::SetTexture()`, pass it using `reinterpret_cast<const Handle<Texture>&>`.

* Compiles and probably works, but looks ugly and I feel dirty afterwards.

Or: Borrow a render target resource as a `Handle<Texture>`, and rewrite `SetRenderTarget` to take a `const Handle<Texture>&` instead. Then:

* When I dereference the handle, use `dynamic_cast` to cast the pointer to a `RenderTarget*` as necessary.

+ RTTI is "Bad" TM, which is to say that it very often gets disabled (along with C++ exceptions, etc.) in game applications due to unnecessary overhead, particularly on consoles. Plus resorting to `dynamic_cast` feels like I'm "doing it wrong," architecturally speaking.
* I know it's a `RenderTarget`; it was when I created it, and if it weren't, I wouldn't be passing it to `SetRenderTarget` in the first place! `reinterpret_cast`!

+ Do I REALLY know? If I'm wrong, then I'm casting something else to something it's not, and I can't even check if it's `nullptr` if I'm wrong. Also, again, I'd like to avoid casts if possible. But I don't entirely disagree with the logic here...
* Implement a lightweight homegrown alternative to RTTI, and use that instead.

+ I've seen this done in one or two engines, but it sounds like some fairly heavy-duty wheel-reinventing...
* Don't derive `RenderTarget` from `Texture`; instead, add a flag that says whether a `Texture` is a `RenderTarget` or not. If it's not, then `SetRenderTarget` will simply fail.

+ Potentially lots of excess baggage added to the `Texture` class. (What's another pointer to an `ID3D11RenderTargetView` among friends?) Doesn't sound like it scales very well.
* Derive `RenderTarget` from `Texture`, but add a virtual method to `Texture` called `GetRenderTarget()` that normally returns `nullptr` but is overridden in `RenderTarget` to return `this`. Similar to the flag method above, but without the excess baggage.

+ Feels like a poor man's `dynamic_cast`. Again, doesn't scale well (add a new method for each derived class that needs it?). But if my `RenderTarget` scenario is maybe the only case I actually need something like this, I'm beginning to feel like maybe this solution isn't so bad...

Or maybe: Add another `SetTexture()` method to `Material` that takes a `const Handle<RenderTarget>&` instead?

* Again, scaleability. And this almost certainly complicates the implementation...

Or finally: Somehow make a handle to a derived type automagically compatible with a handle to its base type (without say, deriving `Handle<RenderTarget>` from `Handle<Texture>`)? I feel like theoretically this might be possible, but I can't seem to wrap my head around it at the moment. Template metaprogramming magic?

Wow, this got a lot longer than I thought it would. Is there a better solution that I'm just missing? Or is one of the above a good enough answer? Feel free to tear apart my arguments if they're flawed. I feel like I'm vastly overthinking this...

# Answer
> 3 votes
> But what happens now when I have a RenderTarget class that **derives** from Texture?

I highlighted the problem with your design.

A `RenderTarget` is not a `Texture`. It *has* a `Texture`. The `RenderTarget` is just a view (either literally as in `ID3D11RenderTargetView` in Direct3D or as an FBO in OpenGL) into a `Texture`. There's some potential issues with flags when creating a texture in some APIs and whether it can later be wrapped as a render target, but that's a data issue, not a type system issue.

You can use code like:

```
Handle<RenderTarget> rt = ...;
Handle<Texture> tex = rt->GetBackingTexture();

```

The `RenderTarget` class would have something like this at a minimum:

```
class RenderTarget : public Resource {
  Handle<Texture> m_BAckingTexture;
  CComPtr<ID3D11RenderTargetView> m_RenderTargetView;

public:
  const Handle<Texture>& GetBackingTexture() const { return m_BackingTexture; }
};

```

Now you can create `RenderTarget` resources from any compatible `Texture` resource and you can retrieve the original `Texture` from any `RenderTarget`. There is no need to "convert" one to the other because they are entirely separate objects.

As (almost) always, prefer aggregation over inheritance. *has-a*, not *is-a*.

---
Tags: c++, resource-management
---


# Question
Title: How do I make a curved surface out of rectangular blocks?
For a *Peggle*-like game, I want to make blocks that follow a curve, like this:

The blocks would then disappear as the ball hits them.

I managed to draw some horizontally, but I'm having trouble making them follow a path:

How do I do this? Do I need to create *Box2D* objects with custom vertices?

# Answer
Given a "root" curve, here's how you might generate block vertices.

The root curve is in the middle, in black. Its control points are shown with red `X`s.

*In short*: I made a Bézier and sampled it (at a configurable rate). I then found the perpendicular vector of the vector from each sample to the next, normalised it, and scaled it to to a (configurable) half-width, first to the left, then inversely to the right. Then drew it.

Stuff you could add to this:

---

Here's my code. It's written in Lua (for the LÖVE game framework), but I think it's readable for anyone.

```
local v = require "vector"

-- A function that makes bezier functions
-- Beziers have start point     p0
--              control point   p1
--              end point       p2
local function makeBezierFunction(p0,p1,p2)
    return function (t)
        local pow = math.pow
        return pow( (1-t),2 ) * p0
               + 2 * (1-t) * t * p1
               + pow(t,2) * p2
    end
end

love.graphics.setBackgroundColor(255, 255, 255)
function love.draw()
    local line = love.graphics.line
    local colour = love.graphics.setColor

    -- Bezier sampling parameters
    local nSegments = 10
    local segIncr = 1/nSegments

    -- Bezier definition: Start (`p0`), control (`p1`) and end `p2`) point
    local p0 = v(100,100)
    local p1 = v( love.mouse.getX(), love.mouse.getY() )
    local p2 = v(500,100)
    local controlPoints = {p0,p1,p2}
    local bez = makeBezierFunction(p0,p1,p2)

    -- Sample the bezier
    for i=0,1-segIncr,segIncr do
        colour(0, 0, 0)
        local x1,y1 = bez(i        ):unpack()
        local x2,y2 = bez(i+segIncr):unpack()
        line(x1,y1,x2,y2)

        -- Find left and right points.
        local center = v(x1, y1)
        local forward = v(x2, y2) - center
        local left = center + forward:perpendicular():normalize_inplace() * 10
        local right = center - forward:perpendicular():normalize_inplace() * 10

        -- Draw a line between them.
        line(left.x, left.y, right.x, right.y)

        -- Find *next* left and right points, if we're not beyond the end of
        -- the curve.
        if i + segIncr <= 1 then
            local x3, y3 = bez(i+segIncr*2):unpack()
            local center2 = v(x2, y2)
            local forward2 = v(x3, y3) - center2
            local left2 = center2 + forward2:perpendicular():normalize_inplace() * 10
            local right2 = center2 - forward2:perpendicular():normalize_inplace() * 10

            -- Connect the left and right of the current to the next point,
            -- forming the top and bottom surface of the blocks.
            colour(0, 0xff, 0)
            line(left.x, left.y, left2.x, left2.y)
            colour(0, 0, 0xff)
            line(right.x, right.y, right2.x, right2.y)
        end
    end

    -- Draw an X at the control points
    for _,p in ipairs(controlPoints) do
        local x,y = p:unpack()
        colour(0xff,0x00,0x00)
        line(x-5,y-5, x+5,y+5)
        line(x-5,y+5, x+5,y-5)
    end
    -- Draw lines between control points
    for i=1,#controlPoints do
        colour(0xff,0x00,0x00, 100)
        local cp1 = controlPoints[i]
        local cp2 = controlPoints[i+1]
        if cp1 and cp2 then
            line(cp1.x, cp1.y
                ,cp2.x, cp2.y)
        end
    end
end

```

If you'd like to play with it: Get LÖVE and put the above code into `main.lua` in its own directory. Put `vector.lua` from the `HUMP` library in the same directory. Run it as `love <that-directory>` from a command line.

Move the mouse around! The middle control point is set to the mouse location:
> 14 votes

---
Tags: collision-detection, box2d, geometry, curves
---


title: SDL sprite animation problem

text:
# Question
Title: SDL sprite animation problem
I'm currently drawing my character from a single file, and my sprite class handles it taking the file path as an argument. Now, I need to add a simple animation, cycling between two frames. The problem is that I have the other animation frame in another file, not in the same file as the first frame. How can I handle the animation without loading and unloading the two files and without merging the files into one?

# Answer
If you want to keep it with your current system, you should make a Sprite class with an array of frames (SDL\_Surface/etc) that you load at the beginning of the game. Have the renderer choose the correct image based on time or some other constraint. Also, I'd advise you use sprite sheets as there is less overhead and they are generally easier to work with (More encapsulated). And definitely do not load/unload the files during run-time as that would be a huge slowdown.
> 2 votes

# Answer
As CobaltHex said, using a sprite sheet would make this much less complicated, and can speed up your program overall. By creating two different SDL\_Rect objects that correspond to the coordinates and dimensions of the two animation sprites you want to use, you can create two options for your what you want a character/entity to look like.

After that, simply using a timer and implementing a switch statement or if-else statement can create a neat looping animation, perhaps for an idle animation, or for a running animation, etc. Take this advice with a little caution though: I'm using this method in my game, and I'm a total newbie to the gamedev community, so I'm sure there are better methods out there.

```
int initialTime;

while(!flag)
{
    initialTime = SDL_GetTicks();
    int phase = (initialTime/250)%16; //16 divisions, each .25 seconds long
    if(phase%2 == 1) /*apply surface #1*/;
    else /*apply surface #2*/;
}

```

So, technically, you could have 16 frames in our idle animation, or change around the length of each frame, whatever you want.
> 1 votes

---
Tags: animation, sprites, sdl, file
---


# Question
Title: problem adding bumpmap to textured gluSphere in JOGL
I currently have one texture on a gluSphere that represents the Earth being displayed perfectly, but having trouble figuring out how to **implement a bumpmap** as well. The bumpmap resides in `"res/planet/earth/earthbump1k.jpg".`Here is the code I have for the regular texture:

```
    gl.glTranslatef(xPath, 0, yPath + zPos);
    gl.glColor3f(1.0f, 1.0f, 1.0f); // base color for earth

    earthGluSphere = glu.gluNewQuadric();

    colorTexture.enable(); // enable texture
    colorTexture.bind(); // bind texture

    // draw sphere...
    glu.gluDeleteQuadric(earthGluSphere);
    colorTexture.disable();

// texturing
public void loadPlanetTexture(GL2 gl)
{
    InputStream colorMap = null;

    try
    {
        colorMap = new FileInputStream("res/planet/earth/earthmap1k.jpg");
        TextureData data = TextureIO.newTextureData(colorMap, false, null);
        colorTexture = TextureIO.newTexture(data);
        colorTexture.getImageTexCoords();
        colorTexture.setTexParameteri(GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
        colorTexture.setTexParameteri(GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);
        colorMap.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
        System.exit(1);
    }
    // Set material properties
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MAG_FILTER, GL2.GL_LINEAR);
    gl.glTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_MIN_FILTER, GL2.GL_NEAREST);

    colorTexture.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_S);
    colorTexture.setTexParameteri(GL2.GL_TEXTURE_2D, GL2.GL_TEXTURE_WRAP_T);
}

```

How would I add the bumpmap as well to the same gluSphere?

# Answer
> 2 votes
For widely used tangent-space normal mapping you'll need to generate tangent-space transform for the sphere and do the lighting calculation in glsl. You can bind the normal map texture into a different texture unit by using glActiveTexture().

---
Tags: java, textures, jogl
---


title: Mouse Speed in GLUT and OpenGL?

text:
# Question
Title: Mouse Speed in GLUT and OpenGL?
I would like to simulate a point that moves in 2D. The input should be the speed of the mouse, so the new position will be computed as following

```
new_position = old_position + delta_time*mouse_velocity

```

As far as I know in GLUT there is no function to acquire the current speed of the mouse between each frame. What I've done so far to compute the delta\_time as following

```
void Display()
{

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glColor3f(1.0f, 0.0f, 0.0f);
    static int delta_t, current_t, previous_t;
    current_t = glutGet(GLUT_ELAPSED_TIME);
    delta_t = current_t - previous_t;
    std::cout << delta_t << std::endl;

    previous_t = current_t;
    glutSwapBuffers();
}

```

Where should I start from here? (Note: I have to get the speed of the mouse because I'm modeling a system)

---

Edit: Based on the above code, `delta_time` fluctuates so much

```
34
19
2
20
1
20
0
16
1
1
10
21
0
13
1
19
34
0
13
0
6
1
14

```

Why does this happen?

# Answer
> 1 votes
You're right in that you'll need the time delta between the current and previous frame. You also need to store current and previous positions of the mouse, and this happens to be pretty easy with GLUT.

```
int px = 0;
int py = 0;

void MouseMotion( int x, int y )
{
  int dx = x - px;
  int dy = y - py;

  // Do something with dx and dy
  // ...

  px = x;
  py = y;
}

void PassiveMouseMotion( int x, int y )
{
  px = x;
  py = y;
}

int main( void )
{
  // ...

  glutMotionFunc( MouseMotion );
  glutPassiveMotionFunc( PassiveMouseMotion );

  glutMainLoop( );
}

```

`px` and `py` are the x and y locations (in pixels) of the mouse. The origin should be top left of the screen with y pointing down and x pointing to the right (IIRC).

Note that changes in the mouse position (`dx` and `dy`) are only recorded in my example code when a mouse button is held down. I am sure you can modify this to your specific needs.

---
Tags: opengl, mouse, glut
---