# Question
Title: Get quaternion between two objects on sphere
In a planetary gravity environment objects are represented in the following way:

```
struct object {
    struct quaternion quat; // quaternion to represent the rotation between the object and the center of the planet
    float dist; // distance from the center of the planet
};

```

Here are the steps at which I position my player:

```
// start at center of the planet
applyQuaternion(&object.quat);
glTranslatef(0.0f, object.dist, 0.0f);
drawObject(&object);

```

Step 1, translate to center of planet:

Step 2, apply quaternion:

Step 3, translate outwards by distance value:

I am also able to get the current position of the player or enemy by using this code:

```
struct matrix initialMatrix, resultantMatrix;
glPushMatrix();
getPositionMatrix(&initialMatrix);
applyQuaternion(&player.quat);
glTranslatef32(0, player.dist, 0);
getPositionMatrix(&resultantMatrix);
playerPosition = matrixTranslationToVector(initialMatrix, resultantMatrix);
glPopMatrix();

```

Given two objects:

```
struct object player;
struct object enemy;

```

How can I get the enemy to face in the direction of the player, whilst always standing upright on the planet, using quaternions?

I want the enemy to go from this:

To this:

His feet always on the planet, and head always away from planet.

I'm able to rotate on the axis which doesn't affect the position (from first enemy diagram to second enemy diagram like so):

```
// Rotate right
Quaternion_multiply(&player.quat, Quaternion_fromAxisAngle(vect(0.0f, 0.0f, 1.0f), degreesToAngle(2)));

// Rotate left
Quaternion_multiply(&player.quat, Quaternion_fromAxisAngle(vect(0.0f, 0.0f, 1.0f), degreesToAngle(-2)));

```

So I'm unsure as to why I'd need a local orientation in addition to the quaternion I already have.

# Answer
Your task is to find the forward vector (the blue one) that is pointing towards the other player.

This vector can be approximated by finding the tangent at the player position on the shortest arc between the player and the enemy.

The tangent of the arc between the two players can be approximated using an approximated derivative (delta). So should we calculate it?

We use SLERP between P1 and P0 to find P, SLERP naturally maps to an arc, we don't need to explicitly represent an arc.

P is only a very small fraction away from P1.

```
P = SLERP( P1, P2, 0.001 );

```

Now we have two quaternions P1 and P in order to find the tangent we need to convert them to 3D vectors, in other words positions.

Once P1 and P are positions. We can now calculate `deltaP`.

The direction vector is actually the normalized version of `deltaP`

```
vec3 deltaP = normalize (Pvec - P1vec);

```

Now we have a direction vector. We only need to convert it to a rotation matrix/quaternion. In this case **you need an extra matrix or quaternion to track the local orientation**. You can assume your forward vector is forward=vec(0,0,1), up = vec(0,1,0) and vec(1,0,0) is your right vector.

Converting a direction vector to a quaternion (again you should have a reference) is little bit of work. You can find this function here.
> 1 votes

---
Tags: 3d, rotation, geometry, quaternion, sphere
---


# Question
Title: how much memory does Adreno 320 GPU provide?
I wanted to know how much memory does Adreno 320 GPU provide ? I am using Nexus 4.

I Googled about it and not able to find any details about it. Can anyone provide the details?

# Answer
> 0 votes
I suppose mobiles do not have dedicated Graphics cards (they have integrated GPUs) , so they utilize the RAM available on the device. To measure, you can try to allocate memory for textures until you run out of memory in order find an approximate limit on the VRAM available.

---
Tags: graphics, graphics-programming, gpu
---


# Question
Title: How does browserquest handle tiles above players
How does browserquest handle tiles above an player?

For example:

When the player stands in front of the tree. the player will be displayed on top of the tree.

When the player stands next to the tree, the tree will be displayed on top of the player.

When the player stands behind the tree, the tree will be displayed on top of the player.

How is this possible? If possible give an example in javascript.

# Answer
> 2 votes
Actually, i'm not sure how "browserquest" handles this. But in other 2D topdown-View games, you just have multiple layers of tiles. Mostly 2+.

In this case, the bottom of the tree is on layer 2, which will be drawn second (first layer is the grass underneath), and the top of the tree is on layer n-1, which will be drawn last.

So the drawing-order would be

* First Layer (tiles on the ground. Like grass,stones,water)
* Second Layer (tiles drawn on top of the first layer,like objects,stones,trees)
* Players/entities
* Third Layer(tiles above players. Like buildings,trees)

---
Tags: javascript
---


# Question
Title: Custom 3D Noise function incorrectly generating in Lua
I have been working on a **custom** noise generator (not Perlin on Simplex or whatever), which works fine in two dimensional space, but upon converting it into three dimensional space, it turns into a cube-ish thing. I could not figure out why, not even after many hours of looking. Here are screenshots of the two functions, 2D and 3D.

2D:

3D:

Here is the code for both.

2D:

```
local shape = {}
local deform = {}

math.randomseed(tick())

for i=1, 50 do
    for j=1, 50 do
        shape["i"..i.."j"..j]=(math.random(50)/10)-1.5
    end
end

for x=1, 50 do
    for y=1, 50 do
    local q11 = shape["i"..x-1 .."j"..y]
    local q12 = shape["i"..x-1 .."j"..y+1]
    local q21 = shape["i"..x+1 .."j"..y]
    local q22 = shape["i"..x+1 .."j"..y+1]
    if not q11 then q11=0 end
    if not q12 then q12=0 end
    if not q21 then q21=0 end
    if not q22 then q22=0 end
    local q = shape["i"..x.."j"..y]
    shape["i"..x.."j"..y]=(q+q11+q12+q21+q22)/10
    end
end

function noise(x,y)
    local q11 = shape["i"..math.floor(x).."j"..math.floor(y)]
    local q12 = shape["i"..math.floor(x).."j"..math.floor(y)+1]
    local q21 = shape["i"..math.floor(x)+1 .."j"..math.floor(y)]
    local q22 = shape["i"..math.floor(x)+1 .."j"..math.floor(y)+1]
    if not q11 then q11=0 end
    if not q12 then q12=0 end
    if not q21 then q21=0 end
    if not q22 then q22=0 end
    local lx1 = ((q21-q11)*(x-math.floor(x)))+q11
    local lx2 = ((q22-q12)*(x-math.floor(x)))+q12
    return ((lx2-lx1)*(y-math.floor(y)))+lx1
end

for i=0, 100 do
    for j=0, 100 do
        local noise = noise(i/5,j/5)
        if noise>0.5 then
        workspace.Terrain:SetCell(i,j,0,1,0,0)
        end
    end
    wait()
end

```

3D:

```
local shape = {}
local deform = {}

math.randomseed(tick())

for i=1, 50 do
    for j=1, 50 do
        for k=1, 50 do
        shape["i"..i.."j"..j.."k"..k]=(math.random(50)/10)-1.5
        end
    end
    wait()
end
    function get(i,j,k)
        return shape["i"..i.."j"..j.."k"..k]
    end
for i=1, 50 do
    for j=1, 50 do
            for k=1,50 do
                local x = math.floor(i)
                local y = math.floor(j)
                local z = math.floor(k)
                local xyz=get(x-1,y-1,z-1)
                local xYz=get(x-1,y+1,z-1)
                local Xyz=get(x+1,y-1,z-1)
                local XYz=get(x+1,y+1,z-1)
                local xyZ=get(x-1,y-1,z+1)
                local xYZ=get(x-1,y+1,z+1)
                local XyZ=get(x+1,y-1,z+1)
                local XYZ=get(x+1,y+1,z+1)
                if not xyz then xyz=0 end
                if not xYz then xYz=0 end
                if not Xyz then Xyz=0 end
                if not XYz then XYz=0 end
                if not xyZ then xyZ=0 end
                if not xYZ then xYZ=0 end
                if not XyZ then XyZ=0 end
                if not XYZ then XYZ=0 end
                local g = shape["i"..x.."j"..y.."k"..z]
                shape["i"..x.."j"..y.."k"..z] = (xyz+xYz+Xyz+XYz+xyZ+xYZ+XyZ+XYZ+g)/9
            end
            end
end

function lerp(a,b,c)
    return ((b-a)*(c))+a
end

function lerpX(a,b,c)
    return lerp(a,b,c)
end

function lerpY(a,b,c)
    return lerp(b,a,c)
end

function lerpZ(a,b,c)
    return lerp(b,a,c)
end

function noise(i,j,k)
                local x = math.floor(i)
                local y = math.floor(j)
                local z = math.floor(k)
                local xyz=get(x-1,y-1,z-1)
                local xYz=get(x-1,y+1,z-1)
                local Xyz=get(x+1,y-1,z-1)
                local XYz=get(x+1,y+1,z-1)
                local xyZ=get(x-1,y-1,z+1)
                local xYZ=get(x-1,y+1,z+1)
                local XyZ=get(x+1,y-1,z+1)
                local XYZ=get(x+1,y+1,z+1)
                if not xyz then xyz=0 end
                if not xYz then xYz=0 end
                if not Xyz then Xyz=0 end
                if not XYz then XYz=0 end
                if not xyZ then xyZ=0 end
                if not xYZ then xYZ=0 end
                if not XyZ then XyZ=0 end
                if not XYZ then XYZ=0 end
                local lx1 = lerpX(xyz,Xyz,i-math.floor(i))
                local lx2 = lerpX(xYz,XYz,i-math.floor(i))
                local ly1 = lerpY(lx1,lx2,j-math.floor(j))
                local lx3 = lerpX(xyZ,XyZ,i-math.floor(i))
                local lx4= lerpX(xYZ,XYZ,i-math.floor(i))
                local ly2 = lerpY(lx3,lx4,j-math.floor(j))
                return lerpZ(ly1,ly2,k-math.floor(k))
end

for i=0, 60 do
    for j=0, 60 do
        for k=0,60 do
            local noise = noise(i/10,j/10,k/10)
            if noise>0.5 then
                workspace.Terrain:SetCell(i,j,k,1,0,0)
            end
        end
        if true then wait() end
    end
end

```

Any help would be greatly appreciated!

# Answer
I imagine it's because you're only passing the iterators `i, j, k` to `SetCell` which will limit cell placement to `60` along all three axes, creating the outline of a cube.
> 1 votes

---
Tags: 2d, 3d, lua, noise
---


# Question
Title: Why is Euler integration sometimes preferred over RK4 even if RK4 is more accurate?
Some high quality engines such as Box2d uses the Simplistic Euler integrator instead for RK4 when Eumplectic Euler commits a global error of the order of Δt whereas, RK4 has Δtˆ4 error? RK4 is not that hard to do, right? Why would a physics engine use Euler over RK4 hence sacrificing accuracy ?

# Answer
It's very probable that Erin Cato subtly justified the use of the Symplectic Euler over RK4 or another higher order integrator. The author has lots of slides and/or material (e.g. http://gamedevs.org/uploads/numerical-integration.pdf) related to the inner workings of the Box2D engine. The main reasons for why RK4 is not really needed when writing this kind of a Physics Engine are:

* ***its improved accuracy is hardly going to make any difference***
* *it does lose energy*, so, a system may seem inherently damped, whereas the Symplectic Euler, although less precise, preserves it (you can simulate stable orbiting motions of satellites around planets without having them crash into the planet)
* it performs *approximately 4x* the operations needed to update the dynamics in a single step
* in the end, **it is not more stable** (e.g. even for the simple pendulum equation, the biggest Dt you can take without having things blow up is with the Symplectic Euler) - in games you first need stability, then speed and afterwards you may start thinking about accuracy (and if it's needed at all)

***Update***

I wrote an academic paper a while ago on how to benchmark and ultimately select the "best" integrator for your needs (http://profs.info.uaic.ro/~jromai/romaijournal/arhiva/2013/2/Cioaca.pdf).

If you want to understand what are the differences between symplectic/energy conserving integrators, explicit and implicit ones, you need to look no further than to how the phase diagrams look like: http://www.acs.psu.edu/drussell/Demos/phase-diagram/phase-diagram.html . For simple oscillators (e.g. the pendulum), these are 2D plots of the angular value against the angular velocity. If the integrator preserves energy, the phase diagram will basically look like an ellipse, whereas if the integrator loses or gains energy, the phase diagram will resemble a spiral.

**Recommended reading**

To better understand what's with this stability and symplecticity fuss, one of the best web resources for viewing the effects of these implicit, explicit and semi-implicit integrators is ***here***.
> 6 votes

# Answer
While I can't speak for Erin Catto himself, the simple answer is that in many games-related physics systems a standard Euler method is preferred to a Runge-Kutta method because it is less expensive computationally, while also being sufficiently stable for games in general.

If RK4 was used the integrator would become a larger bottleneck, impacting the potential number of objects that could be simulated on a given system. This may be considered a worse side effect than potential instability when considering this is a library for general application in games.

It's also worth noting that Verlet integration is commonly used as well, especially for fluid/soft-body dynamics. I believe this might be the system used by LiquidFun, which is a fork of Box2D.

At the end of the day these are systems designed to make a product that's fun, not accurate. So, from that perspective, the increased overhead of an RK4 method may not be justifiable in the target use case.

Note: It might be worth considering the history of Box2D. It was originally written as a demonstration for a GDC presentation and thus the integrator chosen may have little to do with it's potential usage as a general library.
> 2 votes

---
Tags: box2d, physics
---


title: Spawning a Sphere and trying to move it

text:
# Question
Title: Spawning a Sphere and trying to move it
I've been trying to build upon a blog post on Gamasutra http://www.gamasutra.com/blogs/DarrelCusey/20130221/187128/Unity\_Networking\_Sample\_Using\_One\_NetworkView.php In this I would like to spawn a sphere on the server and move it about and when it moves have the movement sent to the clients. On the GUI on the server I just want 3 buttons, spawn sphere, move left and move right. Ive been able to get the sphere to spawn fine, but when I press the button to have it move left or right nothing happens. Have I thought about this too simply? Where have I went wrong or what have I not included?

```
//***New Code***
        if(GUILayout.Button ("Spawn sphere"))
        {
            Instantiate(spawnedSphere);
            Debug.Log("sphere spawned");
        }
        if(GUILayout.Button ("Move Sphere Left"))
        {
            spawnedSphere.rigidbody.AddForce(new Vector3(-5000, 0, 0));
            Debug.Log("Sphere went left");
        }
        if(GUILayout.Button ("Move Sphere Right"))
        {
            spawnedSphere.rigidbody.AddForce(new Vector3(5000, 0, 0));
            Debug.Log("Sphere went right");
        }

        //***End New Code***

```

# Answer
> 0 votes
Replacing "Instaniate(spawnedSphere)" on line 3 with "spawnedSphere = GameObject.Instantiate(spawnedSphere) as GameObject;" fixed the problem.

After instantiating spawnedSphere, I didn't change its value. So I was trying to add force to the prefab.

---
Tags: c#, unity, movement, gui
---


# Question
Title: Using RPC's for movement of an object across a network
I've been building upon http://www.gamasutra.com/blogs/DarrelCusey/20130221/187128/Unity\_Networking\_Sample\_Using\_One\_NetworkView.php At the moment when I spawn a sphere on the server it spawns on the clients aswell. On the server side I have two buttons, move left and move right. Ive been trying to get the movement to go across to the clients aswell but to no avail. The sphere moves on the server but nothing on the clients. Below is the code I have attempted, where have I went wrong with this? The debug line in SendSpherePosition outputs the spheres position perfect, but the position is not updating on the client, so is it a problem with the line below it "spawnedSphere.transform.position = spherePosition;"?

```
 if (Network.isServer && isSphereSpawned==true && closeOutExtras==false)
     {
         Debug.Log("the position of the sphere is: " + spawnedSphere.transform.position );
         //If called here sphere's continuously spawn on the client
         networkView.RPC("TellClientsToSpawnSphere", RPCMode.Others, null);
         //put this bool in just to have one spawn on the client, bad code, will need to change
         closeOutExtras = true;
     }

     if (Network.isServer && isSphereSpawned==true)
     {
         Debug.Log("the position of the sphere is: " + spawnedSphere.transform.position );
         if (lastLocalSpherePosition != spawnedSphere.transform.position)
         {
             networkView.RPC("SendSpherePosition", RPCMode.Others, spawnedSphere.transform.position);
             lastLocalPlayerPosition = spawnedSphere.transform.position;
         }
     }

 }

 [RPC]
 void SendSpherePosition(Vector3 spherePosition)
 {
     Debug.Log ("The sphere position is: " + spherePosition);
     spawnedSphere.transform.position = spherePosition;
 }

 [RPC]
 void TellClientsToSpawnSphere()
 {
     Instantiate (spawnedSphere);
 }

```

# Answer
From what I can gather from your code spawnedSphere is NOT the game object that has been spawned, but the prefab. Do this:

```
GameObject sphere;

[RPC]
void SendSpherePosition( Vector3 spherePosition )
{
    sphere.transform.position = spherePosition;
}

[RPC]
void TellClientsToSpawnSphere()
{
    sphere = Instantiate( spawnedSphere ) as GameObject;
}

```

Catch the returned GameObject of Instantiate, and that is your sphere. Move that instead.
> 0 votes

---
Tags: c#, unity, networking, movement
---


title: Dynamic Crafting Systems

text:
# Question
Title: Dynamic Crafting Systems
I have been toying with the idea of having a game that is based purely around crafting. That on its own is not much of a big deal. The way the crafting would work is the problem.

The idea I have is that there are a certain set of base materials with which the player can use to craft things. But aside from these set materials, anything goes. The player could combine the materials in any way they saw fit to create whatever they wanted. And then, with the new items the player has created, proceed to make more.

To me, this idea sounds very implausible and not able to be created. Is it actually possible?

# Answer
I'm afraid this question is going to be tagged and closed for being 'too broad', since it really is, so I will give a very general answer to a very general question.

What you are looking for is Procedural Content Generation. Procedural Content Generation is the technique of using algorithms to generate a potentially infinite content for a game. You should read the linked website for a better insight.

There are tons of techniques which are applicable for tons of different types of contents, so I can't list on the top of my head which would suit better your game. One possible technique would be using a technique akin to Genetic Programming, where you take two existing items, mix their stats somehow, and introduce some mutation for variety.

Just keep in mind that if you truly want an infinite system, you will need to give up on rigid rules such as A+B = C, and let algorithms create content in your behalf.
> 0 votes

# Answer
What would you want the players to do with the items they create?
Will they be purely cosmetic, or actually have function to interact with (other) players, npcs, or the environment?
It's certainly doable, but in the second case you're going to need some form of scripting API for the crafters to script that interaction into the item.
And yes, it has been done. Check out Second Life (and its clones) which is essentially just that, apart from being a social network of course. Everything in the world is created by its inhabitants (or in a few places by the owners/creators of Second Life, using the exact same tools).
There's even a saying among SL builders "everything starts with a cube" (a .5x.5x.5 meter plywood cube is the default building block you get when you open the build window, it can be changed and twisted into all kind of things, as well as linked with others).
It also has a decent custom scripting language, allowing interaction among objects, parts of objects, avatars, the world as a whole, etc. etc..
Will you be able to write something like that on a sunday afternoon in your bedroom? No. Can it be done? Well, it has been done so surely it can be done but it's going to take a team of skilled software engineers several months to years to put together from scratch.
> 0 votes

# Answer
It sounds like you might be overwhelmed. I would recommend you start with 6 base items, and get the crafting mechanics up and running. From there you can diagram out a crafting tree for yourself. Try taking on one thing at a time, if you plan on having Blacksmithing, Carpentry, and Cooking, for example, just take on one of those mechanics. Hopefully from there you can get a good idea of how you want your other crafting mechanics to work, and how you would want to structure your crafting tree.

Sometimes spending time with a notepad and a pen and removing yourself from a computer is the best way to let your imagination take over, while maintaining focus to get a clear idea of what items you want in your game, and how they can then be manipulated.
> 0 votes

---
Tags: java, game-mechanics
---


# Question
Title: How to load and render PhysX 3.3 heightfield
I'm trying to load a PhysX 3.3 heightmap and render it with OpenGL using glm and glfw, but so far it doesn't seem to be working. I'm basing my code on the PhysX samples, and am also using FreeImage to load the heightmap texture (which is a .TGA, the same one that comes with the PhysX Particles sample).

Here's the code where I load the texture into a PhysX heightmap, everything based on the PhysX Particles sample and the FreeImage manual:

```
PxVec3* heightfieldVertexes;
PxU32* heightfieldIndices;
heightfield:addHeightfield("particles_heightmap.tga", -10.0f, 2.0f, 2.0f, 0.3f, physicsSimulator->getInstance().createMaterial(0.9f, 0.9f, 0.001f), heightfieldVertexes, heightfieldIndices);

void PhysicsSimulator::addHeightfield(char* heightfieldTexturePath, PxReal thickness, PxReal xScale, PxReal yScale, PxReal zScale, PxMaterial *material, PxVec3*& vertices, PxU32*& indices)
{
    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;

    // check the file signature and deduce its format
    fif = FreeImage_GetFileType(heightfieldTexturePath);

    if (fif == FIF_UNKNOWN) // No signature? Try to guess the file format from the file extension
        fif = FreeImage_GetFIFFromFilename(heightfieldTexturePath);

    if ((fif == FIF_UNKNOWN) || !FreeImage_FIFSupportsReading(fif))
    {
        cerr << "Heightfield map texture could not be loaded!" << endl;

        return;
    }

    FIBITMAP *heightfieldTexture = FreeImage_Load(fif, heightfieldTexturePath);

    if(!heightfieldTexture)
    {
        cerr << "Heightfield map texture contains invalid data!" << endl;

        return;
    }

    PxU16 nbColumns = PxU16(FreeImage_GetWidth(heightfieldTexture));
    PxU16 nbRows = PxU16(FreeImage_GetHeight(heightfieldTexture));
    PxHeightFieldDesc heightfieldDesc;
    heightfieldDesc.nbColumns = nbColumns;
    heightfieldDesc.nbRows = nbRows;
    PxU32* samplesData = (PxU32*)malloc(sizeof(PxU32) * (nbColumns * nbRows));
    heightfieldDesc.samples.data = samplesData;
    heightfieldDesc.samples.stride = sizeof(PxU32);
    heightfieldDesc.convexEdgeThreshold = 0;
    PxU8* currentByte = (PxU8*)heightfieldDesc.samples.data;
    PxU32 texturePitch = PxU32(FreeImage_GetPitch(heightfieldTexture));
    PxU8* loaderPtr = (PxU8*)FreeImage_GetBits(heightfieldTexture);
    vertices = (PxVec3*)malloc(sizeof(PxVec3) * (nbColumns * nbRows));
    PxReal* UVs = (PxReal*)malloc(sizeof(PxReal) * ((nbColumns * nbRows * 2)));

    for(PxU32 row = 0; row < nbRows; row++)
    {
        PxU8* pixel = (PxU8*)loaderPtr;
        for(PxU32 column = 0; column < nbColumns; column++)
        {
            PxHeightFieldSample* currentSample = (PxHeightFieldSample*)currentByte;
            currentSample->height = pixel[FI_RGBA_BLUE];
            vertices[row * nbColumns + column] = PxVec3(PxReal(row) * xScale, PxReal(currentSample->height * zScale), PxReal(column) * yScale);
            UVs[2 * (row * nbColumns + column)] = (PxReal(row) / PxReal(nbRows)) * 7.0f;
            UVs[2 * (row * nbColumns + column) + 1] = (PxReal(column) / PxReal(nbColumns)) * 7.0f;
            currentSample->materialIndex0 = 0;
            currentSample->materialIndex1 = 0;
            currentSample->clearTessFlag();
            currentByte += heightfieldDesc.samples.stride;
            pixel += 3;
        }
        loaderPtr += texturePitch;
    }

    // free alocated memory for heightfield texture
    FreeImage_Unload(heightfieldTexture);

    PxHeightField* heightfield = mPhysics->createHeightField(heightfieldDesc);
    // free alocated memory for heightfield samples description
    //free(samplesData);
    // create shape for heightfield
    PxTransform pose(PxVec3(-((PxReal)nbRows * yScale) / 2.0f, 0.0f, -((PxReal)nbColumns * xScale) / 2.0f), PxQuat(PxIdentity));
    PxRigidActor* hf = mPhysics->createRigidStatic(pose);
    PxShape* shape = hf->createShape(PxHeightFieldGeometry(heightfield, PxMeshGeometryFlags(), zScale, xScale, yScale), *material);
    shape->setFlag(PxShapeFlag::ePARTICLE_DRAIN, false);
    shape->setFlag(PxShapeFlag::eSIMULATION_SHAPE, true);
    // add actor to the scene
    mScene->addActor(*hf);
    mActors.push_back(hf);
    // create indices and UVs
    indices = (PxU32*)malloc(sizeof(PxU32) * (nbColumns - 1) * (nbRows - 1) * 3 * 2);
    for(int i = 0; i < (nbColumns - 1); ++i)
    {
        for(int j = 0; j < (nbRows - 1); ++j)
        {
            // first triangle
            indices[6 * (i * (nbRows - 1) + j) + 0] = (i + 1) * nbRows + j;
            indices[6 * (i * (nbRows - 1) + j) + 1] = i * nbRows + j;
            indices[6 * (i * (nbRows - 1) + j) + 2] = i * nbRows + j + 1;
            // second triangle
            indices[6 * (i * (nbRows - 1) + j) + 3] = (i + 1) * nbRows + j + 1;
            indices[6 * (i * (nbRows - 1) + j) + 4] = (i + 1) * nbRows + j;
            indices[6 * (i * (nbRows - 1) + j) + 5] = i * nbRows + j + 1;
        }
    }
}

```

And here is the code where I try to render it, which is located on glfw main loop (some parts of the code where omitted for simplicity):

```
GLFWwindow* window;

int width, height;

mat4 viewMatrix;
mat4 projectionMatrix;

glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_CULL_FACE);

glfwGetFramebufferSize(window, &width, &height);
glViewport(0, 0, width, height);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
viewMatrix = lookAt(eye, center, up);;
projectionMatrix = perspective(fovy, width/(float)height, near, far);

GLuint vao;
glGenVertexArrays( 1, &vao );
glBindVertexArray( vao );

GLuint buffer;
glGenBuffers( 1, &buffer );
glBindBuffer( GL_ARRAY_BUFFER, buffer );
glBufferData( GL_ARRAY_BUFFER, sizeof(heightfieldVertexes), NULL, GL_STATIC_DRAW );
glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(heightfieldVertexes), heightfieldVertexes);

GLuint program = InitShader("heightfieldVertexShader.vert", "heightfieldFragmentShader.frag");

GLuint vPosition = glGetAttribLocation( program, "vPosition" );
glEnableVertexAttribArray( vPosition );
glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0) );

GLuint Model = glGetUniformLocation( program, "Model" );
glUniformMatrix4fv( Model, 1, GL_FALSE, modelMatrix.front());

GLuint View = glGetUniformLocation( program, "View" );
glUniformMatrix4fv( View, 1, GL_FALSE, value_ptr(viewMatrix) );

GLuint Projection = glGetUniformLocation( program, "Projection" );
glUniformMatrix4fv( Projection, 1, GL_FALSE, value_ptr(projectionMatrix) );

glDrawElements( GL_TRIANGLE_STRIP, sizeof(heightfieldIndices)/sizeof(PxU32), GL_UNSIGNED_INT, heightfieldIndices );

glfwSwapBuffers(window);
glfwPollEvents();

```

Lastly, here are the GLSL shader codes. First for the vertex shader:

```
#version 430

in vec3 vPosition;

out vec4 color;

uniform mat4 Model;
uniform mat4 View;
uniform mat4 Projection;

void main()
{
    mat4 ModelViewProjection = Projection * View * Model;

    gl_Position = ModelViewProjection * vec4(vPosition, 1.0);

    color = vec4(1.0, 0.0, 0.0, 1.0);
}

```

EDIT: I'm trying to render the heightmap in red just to check if it is ok.

And the fragment shader:

```
#version 430

in vec4 color;

out vec4 fColor; // fragment's final color

void main()
{
    fColor = color;
}

```

The results of the rendering don't show anything from the heightmap.

As it is today it's far from optimized, but the initial idea is to make it work, and after that make it fast. I think that the view and projection matrix are correct, since I can create and render a box and a plane that interact with each other with PhysX, and they seem to be right. The model matrixes are created by PhysX itself and so I'm assuming that it is correct (and it seems correct in the other actors on the scene).

Unfortunatelly my current computer is not compatible with the more recent versions of OpenGL, so I'm programming this project while I'm on college, but came home today and thought that it may be that I'm trying to pass pointers to a PxVec3 and PxU32 arrays to GLSL shaders, but I don't really know if they are meant to this... As I said, I'm also using glm, and in the case of the vec3 and vec4 array types (from glm) everything works fine. Can this be the error or I'm wrong and the PhysX types are compatible with GLSL?

Other thing that I though is that maybe it's being rendered, but on some place that my camera isn't looking at. If this is the case, is there any way that I can figure where the heightmap is being drawn?

# Answer
As pointed out by @UnholySheep, I was linking the normal PhysX libraries, but the CHECKED versions of them must be linked for the PhysX Visual Debugger to work, and all the "error" messages that show up are perfectly normal when the PVD can't connect, which was the case.
> 0 votes

---
Tags: opengl, glsl, terrain-rendering, heightmap, physx
---


# Question
Title: Component-Entity Systems Code Generation
I'm really enjoying component entity approach (I'm currently using ASH haxe, but particular language/framework doesn't really matter).

However the problem is - there're way too many elementary classes that need frequent update.

So I'd like to have something like yml config file for components and nodes, and actual classes to be generated from it. Is there any already existing solution that utilizes such codegen, or maybe some generic codegen solution that should be easy to configure for such task?

# Answer
> 1 votes
I see two options:

1) Run-time code configuration. Traditional use case would be typical scene (level) data files. Typically a custom implementation is used (could be using a well-known transport such as XML and JSON).

Disadvantages: potentially more work to implement, limited to code configuration rather than generation (scripting aside).

Advantages: run-time configuration potential (e.g. user level editing), high format flexibility.

2) Compile/build time code generation. Typically third-party solutions are used: http://en.wikipedia.org/wiki/Comparison\_of\_code\_generation\_tools

Disadvantages: typically limited to compile/build time, very coder-oriented.

Advantages: simpler to get something working, closer to code.

I only have some minor experience using T4 in Visual Studio and it seems that it works. Visual Studio is considered one of the best IDEs and there are some good T4 extensions for it as well.

This topic is very close to Domain Specific Languages design and implementation, so it might be worth exploring as well.

---
Tags: entity-system, levels, architecture, entity-component, configuration
---


# Question
Title: How can I use XNA with Visual Studio Express 2013 for Windows?
http://dev.windowsphone.com/en-us/downloadsdk

I downloaded the current version of Visual Studio to develop Windows Phone apps, but I don't know how to add XNA. I tried to install XNA, but it's not working with Visual Studio.

How can I use XNA with Visual Studio Express 2013 for Windows?

# Answer
How install XNA 4.0 on Visual Studio 2013

1. Download XNA 4.0 Refresh (Visual Studio 2013)
2. Unzip archive
3. Install DirectX from the archive
4. Install Xna Framework 4.0 Redistribution from the archive
5. Install Xna Game Studio 4.0 Platform Tools from the archive
6. Install Xna Game Studio 4.0 Shared from the archive
7. Install XNA Game Studio 4.0.vsix from the archive
> 12 votes

# Answer
An alternative to using XNA Refresh would be to use the following script to install XNA for you. It will automatically build part of VS 2010 temporarily, as I can only assume Refresh is doing, then delete it after it has installed XNA.

This script (both 64 and 32 bit versions) can be found here, and only requires Windows Powershell, which should be preinstalled on all modern Windows versions.

(Disclaimer: this is not my script, but has worked successfully for me and others in the past. Happy Coding!)
> 1 votes

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


# Question
Title: Importing skeletal animation from vertex coordinates in maya
I have files of different frames of an animation which have the vertex co-ordinates of a human skeleton in 3D space. I want to import the animation from these keyframes into maya to perform motion retargeting. Please help me get some direction in this.

Also is there any other way to retarget motion from one skeleton to other(different size) other than in maya?

# Answer
> -1 votes
I suggest looking into Collada. (.dae) It uses XML. So you can open it in any text editor. However, you need to download a plugin for maya to import and export these files. You can download those here http://sourceforge.net/projects/colladamaya/files/ Also, as for the motion retargeting, look into this http://gameware.autodesk.com/humanik/features

---
Tags: animation, skeletal-animation, maya, motion
---


title: Rendering a Voxelized Mesh

text:
# Question
Title: Rendering a Voxelized Mesh
I've been reading many papers about how to voxelize meshes using different GPU techniques, but I've ran into a problem that I'm not sure how to solve properly. I understand the process of how to convert a 3D mesh into voxels stored in a 3D texture, but I don't know a very efficient way to display the voxelized mesh after this. Many of the papers I have read gloss over this part.

The one way I can think of accomplishing this is to draw an instanced cube, one for each voxel. Each instanced cube would have texture coordinates that correspond to it's location in the 3D texture. Every instanced cube would also go through a geometry shader. If the texture's entry at the current coordinates was 0 (empty voxel), then the geometry shader simply wouldn't output any triangles.

Is this an efficient method/good idea?

# Answer
There's quite a selection of display methods for voxel data.

The most easy to grasp is certainly, one voxel=1 box, but it will leave you with a very cubic looking world.

You can also look into marching cubes (going through your grid and testing how full each set of 8 voxels is, and filling with a selection of pre-generated meshes). There are a number of related meshing techniques that will produce other smooth results.

If you want to get really fancy, you could build a shader that works as a ray-caster - trace a line from the camera to each screen pixel until you hit a voxel, and then render.
> 1 votes

---
Tags: 3d, rendering, voxels
---


# Question
Title: Do you have to rewrite Corona SDK apps for different devices?
I am using the trial windows edition of Corona, but I want to develop for iOS - the windows version only supports android, so my question is will I have to rewrite any parts of my application for iOS based devices?

# Answer
> 2 votes
You will probably have to adjust parts of your application for the different platforms, but you won't have to do much because very little will change. Technically you can directly deploy unchanged an app created for Android onto iOS using Corona, but you will probably want to tweak a lot of things in the app in order to optimize for the different platform. For starters, you may want to incorporate iOS-specific features like GameCenter.

You didn't directly ask about it but I do want to clarify, you definitely should get a Mac if you intend to deploy onto iOS. Because Corona is a cross-platform development tool, sometimes people on Windows plan to just compile for iOS on a friend's machine. That is never a good idea, and you should always be able to directly deploy onto and test on the target hardware yourself.

# Answer
> 1 votes
If you are using any features exclusive to iOS (like Game Center) then you would have to modify that code accordingly, however that is the extent of any real modifications.

In config.lua you could specify the scaling, however "letterbox" is the default and usually works the best across all devices, so you can ignore this unless you would like to use a different scaling option.

In most cases the only thing you will need to do is add the correct icon files into your project folder as these vary depending on the target platform.

# Answer
> 0 votes
If you plan to write something for multiple platforms (say Win, iOS and Android), you almost always have to change a few thing between. Usually it means reducing poly's for the case of pushing out to iOS or Android and some features of Corona may not work for mobile platforms at all so you will have to do some research to determine what those are. I am sure if you check out their forums you will see similar questions.

I know they port to multiple mobile platforms (including iOS) but you will have to purchase a license to do it. Most SDK's are the same with this.

# Answer
> 0 votes
Short Answer: No you don't.

Corona SDK automatically converts the code into an iOS or an Android app.

Just find a mac, install Corona SDK on it, run your app, build for iOS, install the app on your device, and you're good to go.

But you probably have to add the `scale = "letterbox"` string in your config.lua file. This makes the app scale perfectly across iOS and Android devices.

# Answer
> 0 votes
There are some things that you'll edit since you are building for iOS, namely the app's build.settings because iOS build settings are way different from Android, so you have to take look at it, and next is some iOS only features. And that's it. The rest, you don't have to worry about. But its better if your app can work on both OS though.

---
Tags: corona-sdk
---


title: How to approach a coloring app?

text:
# Question
Title: How to approach a coloring app?
I want to make a coloring app in unity. I don't need flood filling. THe player will select a color and click the shape to fill that color. The app will have designs as shown below:

Here the problem is, design has to be empty with black outline. One way would be to create textures using the jpg of each shape. However, there are thousands of shapes and each can be colored in about 7 colors. So, i will have to create 7 textures for each shape.Is there any way to create model with black outline so that only inner color can be changed?

# Answer
If it's loaded from an image then you probably don't need flood fill, if you can access the palette table of the image to change colors and carry the change into the new representation of the image. If you are drawing the image programmatically then you probably do need flood fill and it's often trivial to do.

If you could use vector images like SVG images this is trivial because you'd just change the inner color. For a raster image like PNG or others, if you have some way to know which bytes are the (transparent) edges, the bytes that are the black border, and the bytes which are the inside, if the image format points to a palette table, then it's trivial, one color is transparent, one color is the border, the third is the inside. Then you just change the palette value for the inside to a different color.

I think GIF images do this, the colors in an image point to a palette table of the 255 colors plus transparent so if you change the value of the color in the palette, anything referencing it is automatically changed. So if your puzzle has 40 parts, each part's interior is one palette pointer, then just change that one palette entry from white to the new color.
> 4 votes

# Answer
The one alternative that could be used in the general case (with images like these):

1. Applying the marching squares algorithm and getting a mesh for each area.
2. Simplifying the 2d-mesh in a way similar to what is described here.
3. Detecting clicks on the resulting mesh and changing it's diffuse color accordingly.
> 1 votes

---
Tags: unity, game-design
---


# Question
Title: How should I fix a graphic glitch caused by t-junctions when using greedy meshing
As you might be able to see in the following image, a "graphic glitch" occurs between triangles. I know you are able to make this less visible by enabling anti-aliasing but i was wondering if there is another way to fix this issue.

This is how my wireframe looks (not the same area):

So the problem is caused by "T-junktions". But for my case, this isn't easy to fix. This is the way I create my meshes, it works as the greedy meshing algorithm but then my own version.

First I calculate the faces for each block.

```
if(current.front){//If this block has a front face continue
    int x2 = x;
    int y2 = y;

    //while the next block in the x direction contains a front face and has equal properties, combine the faces
    while(x2 < CHUNK_SIZE && m_pBlocks[x2][y][z].front && m_pBlocks[x2][y][z].getBlockType() == current.getBlockType() && m_pBlocks[x2][y][z].getBlockData() == current.getBlockData() && AOInfoPerBlock[x2][y][z].hasEqualAO(info, FRONT)){
        m_pBlocks[x2][y][z].front = false;
        x2++;
    }
    //while the next block in the y direction contains a front face and has equal properties, combine the faces
    y2++;
    while(y2 < CHUNK_HEIGHT){
        int x3 = x;
        while(x3 < x2){
            if(m_pBlocks[x3][y2][z].front && m_pBlocks[x3][y2][z].getBlockType() == current.getBlockType() && m_pBlocks[x3][y][z].getBlockData() == current.getBlockData() && AOInfoPerBlock[x3][y2][z].hasEqualAO(info, FRONT)){
                m_pBlocks[x3][y2][z].front = false;
                x3++;
            }else{
                for(int x4 = x3-1; x4 >= x; x4--){
                    m_pBlocks[x4][y2][z].front = true;
                }
                break;
            }
        }
        if(x3 == x2){
            y2++;
        }else{
            break;
        }
    }
    if(x2 > x){//If the mesh exists out of one x block, it has gone one to far
        x2--;
    }
    if(y2 > y){//If the mesh exists out of one y block, it has gone one to far
        y2--;
    }

    if(info.f1 + info.f3 > info.f0 + info.f2) { //If this block should be flipped for the screen space ambient occlusion, render in flipped order
        /*1*/ vertPos.push_back(Vertex(x * BLOCK_RENDER_SIZE                        , y2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE , z * BLOCK_RENDER_SIZE                        , /*D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f1 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*2*/ vertPos.push_back(Vertex(x2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE   , y2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE , z * BLOCK_RENDER_SIZE                        , /*D3DXCOLOR(0.0f, 0.0f, 1.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f2 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*3*/ vertPos.push_back(Vertex(x2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE   , y * BLOCK_RENDER_SIZE                     , z * BLOCK_RENDER_SIZE                     , /*D3DXCOLOR(1.0f, 1.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f3 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*0*/ vertPos.push_back(Vertex(x * BLOCK_RENDER_SIZE                        , y * BLOCK_RENDER_SIZE                     , z * BLOCK_RENDER_SIZE                     , /*D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f0 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));

    }else{
        /*0*/ vertPos.push_back(Vertex(x * BLOCK_RENDER_SIZE                        , y * BLOCK_RENDER_SIZE                     , z * BLOCK_RENDER_SIZE                     , /*D3DXCOLOR(1.0f, 0.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f0 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*1*/ vertPos.push_back(Vertex(x * BLOCK_RENDER_SIZE                        , y2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE , z * BLOCK_RENDER_SIZE                        , /*D3DXCOLOR(0.0f, 1.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f1 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*2*/ vertPos.push_back(Vertex(x2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE   , y2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE , z * BLOCK_RENDER_SIZE                        , /*D3DXCOLOR(0.0f, 0.0f, 1.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f2 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));
        /*3*/ vertPos.push_back(Vertex(x2 * BLOCK_RENDER_SIZE + BLOCK_RENDER_SIZE   , y * BLOCK_RENDER_SIZE                     , z * BLOCK_RENDER_SIZE                     , /*D3DXCOLOR(1.0f, 1.0f, 0.0f, 1.0f)/*/color * ((1.0f - 0.8f) + (info.f3 * 0.8f) / (float)3), D3DXVECTOR3(0.0f, 0.0f, -1.0f)));

    }
    indices.push_back(index++);
    indices.push_back(index++);
    indices.push_back(index++);
    indices.push_back(index-3);
    indices.push_back(index-1);
    indices.push_back(index++);
}

```

The same thing is used for each face

# Answer
> 4 votes
Ok, given the wireframe view, it is clear that your problem is T-junctions. Remove them and the artifacts will go away. If you provide information on how you get/generate the meshes, you could get help on how to remove them as well :)

# Answer
> 0 votes
Technically, that's a gap, not an overlap. An overlap would not result in the background colour. So, two of the vertices that are supposed to be in an identical position, are not.
If you can't combine the meshes, then make sure that the values are *exactly* the same (all bits equal). That means being *very* careful of what values you store in you vertex buffers and how you modify your vertices in the vertex/hull/domain/geometry shader (to any that applies to you).

---
Tags: directx, graphics, directx11
---


# Question
Title: Method Animator.SetBool sometimes is not working (or not triggering) in Unity2D
I have trouble with Animator in Unity2d. I have a main character for my game. The character has his own animation clip for fighting. When the player touches the screen, i am starting animation. When the player touches the screen slowly (every second) - everything is working fine, but when the player touches the screen fast, the animation clip is playing about 10 times, and then nothing happens (the clip isn't playing). I've checked - the touch event is triggered normaly, may the problem is with animator. Does anyone have ideas how to fix this issue?

```
public bool UseAxisInput = false;
private Animator Anim;

// Use this for initialization
void Start () {
    Anim = GetComponent<Animator>();
}

// Update is called once per frame
void Update () {
        for (var i = 0; i < Input.touchCount; ++i)
        {
            if (Input.GetTouch(i).phase == TouchPhase.Began)
            {
                Anim.SetBool("IsFighting", true);
            }
        }
}

```

May be this is because of that at the end of my animation i have an animation event which calls the method, that stops animation.

This is my method, that is called, after the animation ends

```
public void stopFighting()
{
    Anim.SetBool("IsFighting", false);
}

```

# Answer
Use a trigger within the `Animator` instead of a boolean. Remove the `AnimationEvent` from the animation and the `stopFighting` function you created. Then, once you've changed the parameter type in the Animator you can change the code to:

```
Animator.SetTrigger("IsFighting");

```

Then once it triggers it will turn itself off after the animation state evaluates it.
> 2 votes

---
Tags: unity, animation, mecanim
---


# Question
Title: The math of normal mapping without a dot product
As far as I understand the technical details about a good normal mapping they go like this:

* everything gravitates around the concept of vertex
* the artist provides an RGB image and an UV map, the UV map maps the 3D vertexes of the object to the 2D surface of said image
* the image represents the information about 3 vectors/axis/directions, U and V, and the color in a point P of the normal map is carrying the information about the magnitude of the normal, the tangent and the bitangent
* you are basically interpolating real vertex `realV` on the 3D geometry with vertex `fakeV` that you create by interpreting the normal map and the uv map
* people that use a dot product assume that the vertex `fakeV` that you create/compute has a normal `fakeV_N` that is orthogonal to both the tangent `fakeV_T` and the bitangent `fakeV_B`, the tuple (`fakeV_N`,`fakeV_T`, `fakeV_B`) can be basically seen as a new set of cartesian axis in the local space of the vertex since they form a `90 °` angle with each other.
* Since there is an infinite amount of vectors that are orthogonal to `fakeV_N` the orientation of `fakeV_T` and `fakeV_B` is determined by the coordinates of UV values on the map

Now the part that I don't get

If you are going to say that said tuple is not orthonormal, where do you get the information about which angles the algorithm is supposed to create between each pair of vectors ? The informations that I get from the artists are the RGB at a specific point, the UV location relative to the 3D vertex on the geometry and the 2D coordinate system on the image that is the normal map, basically the values of U and V . Where do I get the accurate angles for tangent and the bitangent ?

# Answer
> where do you get the information about which angles the algorithm is supposed to create between each pair of vectors? ... Where do I get the accurate angles for tangent and the bitangent?

The tangent and bi-tangent are contained in each vertex. These values are interpolated across the surface of the primitive. At each rasterized pixel, the interpolated vectors are further refined by looking up the value of the normal map at the pixel's UV-coordinate and perturbing the interpolated normal appropriately.
> 1 votes

---
Tags: mathematics, normals, normal-mapping
---


# Question
Title: Offset during zooming to keep object within boundries
I have a simple zoom feature which lets the user zoom in and out. I'm having an issue how ever when i zoom out the object gets smaller to the point that the boundaries become broken.

The idea is the red dot stays inside the circle but the red dot never moves, its stationary in position and size.

This for example is correct because the red dot is inside the circle:

Now if i zoom out and make the circle smaller the red dot ends up outside the circle like so:

The problem i have, is i don't know how to offset the circle to keep the red dot inside of the circle regardless of zooming scale. I have a working example here: **http://jsfiddle.net/3wr885so/** if you zoom out you'll find the circle doesn't fix its offset to keep everything in the right place.

The two relevant functions I used for zooming and drawing are below:

**Zoom function**

```
function zoomObj(e){
var delta       = e.wheelDelta,
    mousePos    = {};
    mousePos.x  = e.pagex;
    mousePos.y  = e.pageY;
var range = zoom.percentVal * zoom.modifier;
if(delta == 120){         //scroll in
    var endVal = zoom.position + range;
} else {                  //scroll out
    var endVal = zoom.position - range;
}

zoom.position = endVal;
zoom.percent = (zoom.position/zoom.range) * 100;

//need to set offsets to correct for new zoom here
}

```

**Game Loop**

```
function start(){
    var radius = obj.radius/100*zoom.percent;
    if(radius < 0){ radius = 0; }
    ctx.clearRect(0,0,canvas.width,canvas.height);
    ctx.beginPath();
    ctx.arc(camera.offsetX, camera.offsetY, radius ,0,2*Math.PI, false);
    ctx.restore();
    ctx.lineWidth = 1;
    ctx.strokeStyle = 'black';
    ctx.stroke();

    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.beginPath();
    ctx.fillStyle = 'red';
    ctx.fillRect(canvas.width/2-5,canvas.height/2-5,10,10);
    ctx.stroke();

}

```

Any suggestions how i fix this problem :) ?

# Answer
> 1 votes
while zooming out, check if distance of red-dot and center of circle is more than circle's radius. (Lets call this distance, d)

if so happened, move the circle in direction of V vector ( V = red-dot.position - circle.position\`) for x unit. (x= d-circle's radius).

# Answer
> 0 votes
I didn't read your code but I think what you're looking for is something like this:

```
var currentZoom, //The zoom %
circleCenterX, circleCenterY, // The circles center for viewing
dotX, dotY // The dots center for vieweing

function zoomInOrOut(delta) // To zoom out use a negative value
{
  if (delta < 0 && currentZoom <= 1.0) return;
  // Constraint - offsetX^2 + offsetY^2 has to be <= circleRadius^2
  var oldZoom = currentZoom,
  offsetX = circleCenterX - dotX,
  offsetY = circleCenterY - dotY;
  currentZoom += delta;
  ratio = currentZoom / oldZoom;

  circleCenterX = dotX + offsetX * ratio;
  circleCenterY = dotY + offsetY * ratio;
}

```

---
Tags: mathematics, javascript, camera, html-canvas
---


# Question
Title: Determine wheter an octree node needs to be continue
For collision detection (moving vs. non-moving) in my current project, I decided to implement an octree approach after the preselection.

The only collision detection I'm currently using is a AABB-vs.-AABB collsion detection. Now, if this detection returns `true` for two objects `(n, m)`, I want to subdivide the AABB into eight smaller axis-aligned boxes, and so on. (Octree)

Implementing the subdivision itself is now problem for me, but I'm stuck at the following: **How can I determine whether a node needs to be divided further, or whether further subnodes are unnecessary?**

Since I got objects of various complexity (a model with ca. 1500 vertices vs. a cube with 8), I can't simply check for the amount of vertices inside an octant.

What ways are there to determine whether a subdivision is necessard? Or am I even using a wrong approach any something else might work better?

**Edit:** I now think that an octree might be the wrong approach. What would be the best way to check for a more exact collision detection after an AABB collision detection returns true?

# Answer
> 2 votes
If you are looking for precise mesh collision detection then you need to compare each pair of faces that are in the same cube in the 3d grid. You are right about avoiding an octree. Build a 3d grid that contains both objects an populate it with faces and check faces that are in the same cubes in the grid for intersection.

Please realize this is a slow (computationally intensive) process and therefore using a low-poly representative mesh for collision testing is recommended vs. using the high poly mesh which should only be used for rendering and may slow down collision testing extensively.

---
Tags: collision-detection, octree
---


title: Linear movement over a Bézier curve

text:
# Question
Title: Linear movement over a Bézier curve
Is it possible to get a constant speed movement over a Bézier curve when its points are not kept symmetrical ?

Here white square (almost) moves at constant speed. (red and green squares are control points)

Here travel time is much longer in the green part than in the red part. (control points moved)

Curve generation and white square movement is defined as follows :

```
    public void Update(...)
    {
        // White square movement
        _timeline += 0.01f;
        if (_timeline >= 1.0f)
        {
            _timeline = 0.01f;
        }
        _timelineVector2 = GetBezierPoint(_timeline, _p0, _p1, _p2, _p3);
    }

    // Also used for generating curve
    public static Vector2 GetBezierPoint(float t, Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
    {
        float cx = 3 * (p1.X - p0.X);
        float cy = 3 * (p1.Y - p0.Y);

        float bx = 3 * (p2.X - p1.X) - cx;
        float by = 3 * (p2.Y - p1.Y) - cy;

        float ax = p3.X - p0.X - cx - bx;
        float ay = p3.Y - p0.Y - cy - @by;

        float Cube = t * t * t;
        float Square = t * t;

        float resX = (ax * Cube) + (bx * Square) + (cx * t) + p0.X;
        float resY = (ay * Cube) + (@by * Square) + (cy * t) + p0.Y;

        return new Vector2(resX, resY);
    }

```

# Answer
> 0 votes
There is a simple approximation you could apply here. Lets say the movement pace you want is 1.0 units per frame. You start with `t = 0` and a `stepSize = 1.0`

Lets say the function `getBezierPoint(t)` returns a position on the bezier, now you do a binary search like approximation:

```
desiredStepSize = 1.0; // How much we move each frame / second ... some other time unit
acceptableError = desiredStepSize / 20.0; // How much can we deviate from the desired speed

currentT = 0.0; // Where do we start on the bezier (t = 0)
tStepSize = 0.01; // How much we guess the change in t needs to be

actualStepSize = 0; // The distance between the current position and the next one

  function compute_t_step_size_from_guess()
  // Make tStepSize big enough if needed

  actualStepSize = distance(getBezierPoint(currentT),
                              getBezierPoint(currentT + tStepSize));
  while (actualStepSize < desiredStepSize);
  {
    tStepSize *= 2.0;
    actualStepSize = distance(getBezierPoint(currentT),
                              getBezierPoint(currentT + tStepSize));
  }

  deltaT = 0.5 * tStepSize;
  // Fine tune with binary search
  while ((actualStepSize < desiredStepSize - acceptableError
          ||
          actualStepSize > desiredStepSize + acceptableError )
  {
    if (actualStepSize < desiredStepSize) tStepSize += deltaT;
    else tStepSize -= deltaT;

    deltaT *= 0.5;
  }
}

```

This runs very fast and gets really accurate results. You can use it to compute the next position for nearly perfect linear velocity (it doesn't take the arc into account). You can vastly improve the speed by fine tuning some things, for instance, increasing the size during the growth phase by `* (1 + acceptableError / desiredStepSize )`, then binary searching between the the current approximation and `1 / (1 + acceptableError / desiredStepSize )`.

---
Tags: xna, beziers
---


# Question
Title: Making sprites move in oppsite direction of vector
I have a sprite that moves from the bottom left of the screen to the top right. What I want to know is how would i make it turn around and go in the opposite direction, and continue this loop.

I tried negating the direction of the vector but that doesnt work.

This what i have right now:

```
public void create() {
    // Game Initialization
    v = new Vector2(Gdx.graphics.getWidth() - 0, Gdx.graphics.getHeight() - 0);
    v.nor();
    v.scl(100);

    spriteBatch = new SpriteBatch();
    bug = new Sprite(new Texture("EnemyBug.png"));
    bug.setSize(50, 85);
    bug.setOrigin(0,0);//Gdx.graphics.getHeight() / 5, Gdx.graphics.getHeight() / 5);
    bug.setPosition(1,1);//Gdx.graphics.getWidth() - 50, Gdx.graphics.getHeight() - 50);
    bug.rotate(v.angle());

    rotDeg = 5;
}

@Override
public void render() {
    // Game Loop

    Gdx.gl.glClearColor(0.7f, 0.7f, 0.2f, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    spriteBatch.begin();

    if(bug.getX() >= (int)(Gdx.graphics.getWidth() - 100) && bug.getY() >= (int)(Gdx.graphics.getHeight() - 100)){
        turn = !turn;
    }
    else if(bug.getX() <= 50 && bug.getY() <= 50){
        turn = !turn;
    }

    if(!turn){
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    bug.draw(spriteBatch);
    spriteBatch.end();
}

```

# Answer
You have a translate function outside of the if statement.

```
    .
    .
    .
    if(!turn){
        bug.translate(v.x * Gdx.graphics.getDeltaTime(), v.y * Gdx.graphics.getDeltaTime());
    }
    else{
        bug.translate(-(v.x * Gdx.graphics.getDeltaTime()), -(v.y * Gdx.graphics.getDeltaTime()));
    }

    bug.draw(spriteBatch);
    spriteBatch.end();
}

```
> 1 votes

---
Tags: java, libgdx
---


title: Yield and loading textures

text:
# Question
Title: Yield and loading textures
I have a need to dynamically load textures from the player's filesystem. WWW provides the functionality I need, but I can't get the example code to compile.

"yield www" causes my code to not compile. Here, the code is short:

```
    private List<Texture> LoadTextures (String prefix, int numTextures)
    {
        List<Texture> textures = new List<Texture> ();
        for (var i = 0; i < numTextures; i++ )
        {
            var www = new WWW(prefix + i);
            yield www;
            textures.Add(www.texture);
        }
        return textures;
    }

```

Why doesn't yield work here, like the code sample on the Unity docs suggests?

EDIT:

In response to Lasse:

```
    private IEnumerable<Texture> LoadTextures (String prefix, int numTextures)
    {
        for (var i = 0; i < numTextures; i++ )
        {
            var www = new WWW(prefix + i + ".png");
            yield return www.texture;
        }
    }

```

The above compiles, but I now get this error:

> You are trying to load data from a www stream which has not completed the download yet. You need to yield the download or wait until isDone returns true.

It's as if it is not even yielding. What gives? The file does exist in this directory. I tried prepending "file:///" but that didn't do anything. Do I need to provide an absolute path, or is relative OK?

# Answer
> 3 votes
The code in the link you pasted seems to be UnityScript code. In C# yield works a bit differently than it does in UnityScript, which works like in javascript. Yield reference docs.

You are probably looking for this code.

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public string url = "http://images.earthcam.com/ec_metros/ourcams/fridays.jpg";
    IEnumerator Start() {
        WWW www = new WWW(url);
        yield return www;
        renderer.material.mainTexture = www.texture;
    }
}

```

Then adapting that you could do something like this:

```
using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {

    List<Texture> textures;
    List<string> urls;
    bool done = false;

    void Start() {
        StartCoroutine("LoadTextures");
    }

    IEnumerator LoadTextures() {
        foreach(var url in urls)
        {
            WWW www = new WWW(url);
            yield return www;
            textures.add(www.texture);
        }
        done = true;
        yield break; // May be unneeded
    }
}

```

Note: I have not used this myself, so the code might not be working. I am not currently able to test it out.

Also, if you try to load external (local on the computer) files that are not assets, Unity itself does not support that. You need to load the files by some other means, like System.IO.

EDIT: Apparantly you can with "file://", but it needs to be absolute path I guess. You can try to find the absolute path with help of .net and Path class.

---
Tags: c#
---


# Question
Title: Why bother with a separate normal matrix, if there is never non-uniform scaling on the view matrix?
I am updating one of my shaders to a version of OpenGL/GLSL that doesn't automatically provide `gl_NormalMatrix` (for educational purposes; I'm not ripping out working code for the sake of it). Therefore, I need to compute my own normal matrix on the CPU and pass it in.

I understand that a separate normal matrix is used to avoid issues with non-uniform scaling affecting the direction of normals. However, I've noticed that in my code I never perform *any* scaling let alone a non-uniform one. So, I'm tempted to use the upper left 3x3 sub-matrix for transforming my normals and calling it a day (perhaps normalising them to allow for uniform scaling).

My program assumes that every mesh it loads is already at the correct size, with no scaling required.

Will I soon run into something that requires scaling (uniform or otherwise), or is there another reason for using a separate normal matrix that I haven't realised?

# Answer
You're not missing anything.

The normal matrix exists *in case* the upper-left 3x3 of your regular model-view transformation is unsuitable for transforming normals (that is, contains non-uniform scale or other craziness).

If you know the upper-left 3x3 is always suitable for use in the transformation of normals, there's no reason to bother with a separate "normal matrix."

Most applications of 3D graphics for games can use the upper-left 3x3 just fine. It's broader, more general 3D graphics uses that more often have a need for a distinct normal matrix.
> 7 votes

---
Tags: opengl, 3d, matrix, graphics-programming
---


# Question
Title: How to cleanly serialize/de serialize a Dictionary whose values are of a derived class using c# newtonsoft json
I am working on and entity component system and I am storing entities as a JSON file. Components are stored in an entity as a Dictionary of components. I am using newtonsoft's JSON library.

After much frustration I managed to serialize a dictionary that would store objects derived from Component using the ItemTypeNameHandling attribute

Component class:

```
 class Component
{
    protected String name;
    public String Name { get { return name; } }
}

```

Example of a derived component:

```
[JsonObject(MemberSerialization.OptIn)]
class Position : Component
{
    [JsonProperty(Required = Required.Always)]
    public int x = 50;
    [JsonProperty(Required = Required.Always)]
    public int y = 20;

    public Position() { this.name = "position"; }
}

```

Entity class with Dictionary:

```
class Entity
{
    ...
    [JsonProperty(Required = Required.Always, ItemTypeNameHandling = TypeNameHandling.Objects)]
    private Dictionary<String, Component> components = new Dictionary<String, Component>();
    ...
}

```

However I am not satisfied with how the JSON looks. I get this:

```
"components": {
"position": {
  "$type": "Project_Citrus.Engine.Components.Position, Project Citrus",
  "x": 50,
  "y": 20
 },
"health": {
  "$type": "Project_Citrus.Engine.Components.Health, Project Citrus",
  "HP": 100
 }
}

```

I want to be easily able to edit my JSON files to create new content. Having to put "$type": "..." makes it seem rather cumbersome and having someone who is not familiar with my object library would have a tough time adding new components. Is there some way to create something like below and still be able to de serialize and de serialize using the component name? Here's an example of what I would like to have.

```
"components": {
"position": {
  "x": 50,
  "y": 20
 },
"health": {
  "HP": 100
 }
}

```

# Answer
After a few hours of work I found I could create a custom converter by extending **JsonConverter**. I used this answer to help me out.

I got my output to look like:

```
  "components": [
     {
       "name": "position",
       "x": 50,
       "y": 20
     },
     {
      "name": "health",
      "HP": 100
     }
   ]

```

I added my converter as an attribute to the dictionary like so:

```
[JsonProperty(Required = Required.Always), JsonConverter(typeof(DictionaryComponentConverter))]
    private Dictionary<String, Component> components = new Dictionary<String, Component>();

```

I then did the same to the Component class though I created a new converter ComponentConverter:

```
[JsonObject(MemberSerialization.OptIn), JsonConverter(typeof(ComponentConverter))]
class Component
{
    protected String name;
    public String Name { get { return name; } }
}

```

It's not how I want the code too look like in the end, Im going to try to clean it but heres how my converters look like:

**DictionaryComponentConverter**:

```
class DictionaryComponentConverter : JsonConverter
{

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartArray)
        {
            // Load JArray from stream
            JArray jArray = JArray.Load(reader);

            // Create target object based on JObject
            List<Component> target = new List<Component>();

            // Populate the object properties
            serializer.Populate(jArray.CreateReader(), target);
            Dictionary<String, Component> dictionary = new Dictionary<string, Component>();
            foreach (Component comp in target)
                if (!dictionary.ContainsKey(comp.Name))
                    dictionary.Add(comp.Name, comp);
            return dictionary;
        }
        return new Dictionary<string, Component>();
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is Dictionary<String, Component>)
        {
            Dictionary<String, Component> components = (Dictionary<String, Component>)value;
            writer.WriteStartArray();
            foreach (KeyValuePair<String, Component> entry in components)
            {
                serializer.Serialize(writer, entry.Value);
            }
            writer.WriteEndArray();
        }
        else
        {
            writer.WriteStartObject();
            writer.WriteEndObject();
        }
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(Dictionary<string, Component>).IsAssignableFrom(objectType);
    }
}

```

**ComponentConverter**:

```
class ComponentConverter : JsonConverter
{
    protected Component Create(Type objectType, JObject jObject)
    {
        if (jObject["name"] != null)
            if (jObject["name"].ToString() == "position")
            {
                return new Position();
            }
            else if (jObject["name"].ToString() == "health")
            {
                return new Health();
            }

        return new Component();
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        Component target = Create(objectType, jObject);

        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        if (value is Position)
        {
            Position position = (Position)value;
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteValue(position.Name);
            writer.WritePropertyName("x");
            writer.WriteValue(position.x);
            writer.WritePropertyName("y");
            writer.WriteValue(position.y);
            writer.WriteEndObject();
        }
        else if (value is Health)
        {
            Health health = (Health)value;
            writer.WriteStartObject();
            writer.WritePropertyName("name");
            writer.WriteValue(health.Name);
            writer.WritePropertyName("HP");
            writer.WriteValue(health.HP);
            writer.WriteEndObject();
        }
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(Component).IsAssignableFrom(objectType);
    }
}

```
> 3 votes

# Answer
There is no one right answer. I open with that because I know there are many who disagree with what I'm about to say. I do use NewtonSoft for JSON serializing and deserializing, but from a somewhat different angle.

After much experience with apis and file formats, I've settled on the approach of designing the file format (or network message format, in some cases) *completely separately* from any runtime objects. I never want to just "serialize my object graph".

I implement the loader and saver as separate code that operates using the public APIs of the runtime objects and relatively generic JSON/XML/Whatever readers and writers. The loader and saver of course can become a relatively thick bundle of code, full of loops and run-on paragraphs.

*But!* it is extremely testable, so that bundle is quite safe, if you have reasonable unit tests.

This approach becomes especially valuable when dealing with backward compatibility and versioning, new fields (sometimes beyond a simple "default value"), working around quirks of earlier implementations or even external tools that read and write this file format, and so on, in a highly flexible manner. Again, unit tests & TDD are a perfect fit here for defining and enforcing the desired behavior.
> 2 votes

---
Tags: c#, entity-system, component-based
---


# Question
Title: Getting around limitations posed by float in space game
I'm working on a procedurally generated game set in outer space. As in the real world, the game universe will be pretty much 99% empty, with planets/stars/solar systems etc... being *very* far apart.

For example at the beginning of the game, you will pretty much be stuck in the solar system you spawn in, as even flying from planet to planet will take a very long time. Flying from one solar system to another will be theoretically possible, however it would take days of IRL time without obtaining the in-game equivalent of a warp-drive.

I realize with all the thousands of planets/stars etc... they can't all be updated 60 times per second, and I can deal with that. Let me describe my problem.

Okay, so lets say 1 meter is 16 pixels.

```
Earth diameter      =  12,756,000 meters
Earth diameter      = 204,096,000 pixels
Earth circumference = 640,861,440 pixels

```

Okay, that's... still arguably manageable. Obviously there wouldn't be an `earth.png`, it could be procedurally rendered. But it gets worse:

```
Distance from earth to sun =   149,600,000,000 meters
Distance from earth to sun = 2,393,600,000,000 pixels

```

So if we define earth as our arbitrary origin, and we travel to the sun in our ship:

```
int main()
{
    //        Distance to sun:
    //        2393600000000
    float X = 2383695718491;
    std::cout << X << "\n";

    X += 6;
    std::cout << X << "\n";
}

```

This outputs:

```
2.3837e+012
2.3837e+012

```

That's the correct amount of zeroes, but now over 4 million pixels of precision is lost, and that's a big deal. And of course, the distance to the sun is tiny compared to the distance to the nearest star.

For the purpose of the game universe, I will decrease the distances just to make travel a little less boring, but this is still clearly impossible by only using x and y variables.

**How should I handle these huge distances?**

UPDATE: Just to clarify, I realize that earth is unimaginably huge and there's no way I'd be able to fill it with meaningful content. GTA V's map is about 100 square miles, and that's less than .00000005% percent of earth's surface. So my planets will definitely be *significantly* smaller than this, however the issue with huge distances remains.

# Answer
The best way to get around these types of limitations is to move the world, rather than move the player and camera.

**Strict Method**

Keep your camera and player at (0,0) if you're using 2D or (0,0,0) is you're using 3D.

When you calculate the input to move your player, instead of moving them, move all the objects in the environment. When the objects get some appreciable distance away from the player, disable them.

You will need to have a system implemented that keeps track of the distance so you know when to activate an object and set its position/orientation in the world.

**Hybrid Method**

Similar to the above method, but instead of moving the environment and never moving the player. You move the player around the environment as normal, but after a certain distance from the origin you move everything based on an offset.

You would calculate this offset by the distance of the player from the origin, and then move all objects by this offset (so all relative distances stay the same). You activate/deactivate objects during this time as needed, similar to strict method.

**Other Ways**

If you're doing this by scratch and not forced by an API/Engine to use floats for keeping track of translation data, you could opt for a data type with more precision such as double or decimal (note that using the decimal datatype is considerably slower than float/double).
> 1 votes

# Answer
Kerbal Space Program used to have the same issue, and called it the Kraken.

They solved by moving the bubble around the player it has a radius of 2.5 kilometers outside of which all objects end up "on rails" where the orbit is fixed and large jumps ahead are easily calculated.

That can be done using the patched conics orbit model. Essentially it means that all objects are only in the sphere of influence of a single celestial body which reduces the problem to the solved 2 body problem.
> 1 votes

---
Tags: c++, 2d, floating-point
---


# Question
Title: In a Sonic-esque platformer, how to tell if the chracter is upside-down or not?
In a Sonic-esque platform game, how do you know if the player's character is currently upside down? Let's say the character is running to the left:

At a certain point the character will begin to supposedly run on the ceiling. How do I keep track of this since the chracter is touching both the ceiling and the floor of the tunnel?know

I need some way to know where the character's feet are positioned, keep track of it and allow this to change when the character is moving fast across curved surfaces.

# Answer
While the character is running, mark the surface that he's running on as the active running surface. As long as the speed does not reduce to 0 (or reduced, depending on your mechanics), you're on the same surface, no matter if the head touches another surface.
To detect where you go next, if your surface is stored as a grid, store last grid cell that you walked, as well as the current grid, and by checking the local neighbourhood (say 3x3 grid cells) around the current grid cell, you can figure out where the feet should be positioned next, and you can also derive the velocity, etc from that.
> 2 votes

# Answer
You could have two collision sensors: one just under the character's feet and one just over it's head. Then it would be a matter of checking the positions of both sensors when they are both triggered and if the foot sensor is higher than the head sensor then you know that the body is upside down.
> 0 votes

# Answer
You can use the dot product of a world up vector with an up vector relative to the player. If both of these vectors are normalized, you're results will be between 1 and -1. With 2d vectors the dot product is calculated by taking the product of the x components and adding them to the product of the y components.

Given the vectors `A = (x,y)` and `B = (X,Y)`. The dot product is `x*X + y*Y`. So, if the world up vector is (0, 1), we can see that:

if player up vector is (0, 1), then the dot product of the up vectors is 0\*0 + 1\*1 = 1, and, if the player up vector is (0, -1), then the dot product is 0\*0 + -1\*1 = -1. This tells us the player is upside down. If the player is standing on the side of a wall (1, 0), perpendicular to the world up vector. Then the dot product is 1\*0 + 0\*1 = 0.

So, to recap, if the dot product is 1, the player is up right, as the dot product approaches 0, the player becomes more and more perpendicular to the world, and is perpendicular with the result is 0. As the dot product turns negative, then player's head starts angling towards the ground, and the player is completely upside down when the dot product is -1.
> 0 votes

---
Tags: physics, platformer
---


# Question
Title: Static evaluation function for Checkers using Minimax
I have correctly implemented Minimax for my checkers AI till depth of 3 ( well at least that is what I think ). However I am confused on evaluating my game boards at depth 3 with heuristics. Currently I just check ( no of blacks - no of reds ) for my heuristics but then it gives duplicate values ( Tie Breaker ) for most of the game boards. I researched and found that in that case we can assign values to each position on the game board ( found on this link here here and add it to the heuristic. But how is it implemented exactly and how are those board values chosen? And do I have to apply it for each of my recursion or just at the top level for all the branch nodes?

here is my code.

```
    int MaxMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
    {
        if (depth == 0)
        {
            return StaticEvaluationFunction(currNode,depth);
        }
        else
        {
            depth--;
            int v = -10000;
            List<TreeNode> allPossRedMoveNodes = gameBoardScript.createNewRedBoardsFromCurrent(currNode.getCurrentBoard());
            TreeNode bestNode = null;
            foreach (TreeNode RedNode in allPossRedMoveNodes)
            {
                int v1 = MinMove(RedNode, depth, pathNodes);
                if (v1 > v)
                {
                    v = v1;
                    bestNode = RedNode;
                }
                //if the heuristic is equal then add the board piece values to the current heuristic ( I AM NOT SURE IF THIS IS CORRECT )
                else if( v1 == v)
                {
                    v1 += RedNode.getBoardMove().getMovedToPiece().getTieBreakerValue();
                    v = v1;
                }
            }
            return v;
        }
    }

    int MinMove(TreeNode currNode, int depth, List<TreeNode> pathNodes)
    {
        if (depth == 0)
        {
            return StaticEvaluationFunction(currNode, depth);
        }
        else
        {
            depth--;
            int v = 10000;
            List<TreeNode> allPossBlackMoveNodes = gameBoardScript.createNewBlackBoardsFromCurrent(currNode.getCurrentBoard());
            TreeNode bestNode = null;
            foreach (TreeNode BlackNode in allPossBlackMoveNodes)
            {
                int v1 = MaxMove(BlackNode, depth,pathNodes);
                if (v1 < v)
                {
                    v = v1;
                    bestNode = BlackNode;
                }
                //when priorities are equal
                else if (v1 == v)
                {
                    v1 += BlackNode.getBoardMove().getMovedToPiece().getTieBreakerValue();
                    v = v1;
                }
            }
            return v;
        }
    }

    private int StaticEvaluationFunction(TreeNode node, int depth)
    {
        return node.getHeuristic(); // Black - Red count at the last depth
    }

```

# Answer
The duplicate values are to be expected, since you're only "counting the wood". Augment your heuristic to include additional features, for example you might count the average distance to the center, or the number of pieces that are en prise. Usually these additional features would be worth a fraction of the value of a piece.

The evaluation is applied at the maximum depth of the search tree, and propagated up. It's not needed at higher levels in the search tree, at least until you add other features to the search (ie; alpha-beta pruning).
> 0 votes

---
Tags: algorithm, ai, board-game
---


# Question
Title: Issue implementing proper collision in XNA Game Studio 4.0
I am building a game in XNA 4.0, where a player moves about a 2 dimensional (vertical perspective) map consisting of blocks. My issue is creating proper collision between the payer and the blocks (basic game physics.) The player moves more than 1px per frame, so .Intersects() just isn't enough, I need physical contact collision that can function in a gravity environment. The current version I currently have is a piece of garbage and only works occasionally.

Basically, all that the collision system needs to do is stop gravity when the player lands on a block, and provide some decent physics when the player hits blocks (movement in that direction ceases). The idea behind my current solution is to move the next Position around until it finds a clear spot, but it doesn't work well. I have an idea why, just have no idea how to do it properly.

I know there must be a better way to do this. What would be the best method of making this kind of collision work properly?

Thanks

# Answer
> 0 votes
This does the job perfectly, you just need to sort through a few syntax errors. http://go.colorize.net/xna/2d\_collision\_response\_xna/

# Answer
> 0 votes
A couple of things I have found that have helped players in the past with collision : Prevent the game object from moving before it collides.

By checking for a collision, and preventing movement, you won't have to worry about a game object lapping into another. When your collision check is flagged (game object will hit another game object) you then handle the set of instances that can occur. In this case it sounds like the desired effect would be the character landing on a block.

When your collision check is flagged, initialize your character's y location to be on the said block, creating the appearance of him landing on the block, and preventing him from passing into the block (flagging the collision check to lock him in place). Once this is achieved you can set a grounded property to true on the game object, to indicate that gravity does not apply to it until another scenario sets his grounded property to false.

There are many collision detection examples on stack, and plenty of tutorials out there, but if you need a code base to pull from, feel free to use my code as a reference : https://github.com/shroeder/GameRPG/tree/LukesBranch/Game/Game. Collision detection can be found by searching for //character movement in the game class.

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


# Question
Title: OpenGL: I only see one square instead of a cube / giving information to vertex shader
I am new to OpenGL and tried to follow this tutorial. I use C# and OpenTK. So I translate the C++ Code from the Tutorial:

My C#-Code:

```
            /* Hintergrundfarbe */
            GL.ClearColor(0.0f, 0.0f, 0.4f, 0.0f);

            /* Fragments weiter hinten werden automatisch zuerst gerendert */
            GL.Enable(EnableCap.DepthTest);
            GL.DepthFunc(DepthFunction.Less);

            /* Vertex Array Object */
            GL.GenVertexArrays(1, out vao);
            GL.BindVertexArray(vao);

            /* GLSL Shader laden */
            shaderProgram = LoadShaders("vs.glsl", "fs.glsl");

            /* Matrizen */
            MatrixID = GL.GetUniformLocation(shaderProgram, "MVP");
            Projection = Matrix4.Perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
            View = Matrix4.LookAt(new Vector3(4, 3, -3), new Vector3(0, 0, 0), new Vector3(0, 1, 0));
            //Matrix4 Model = new Matrix4(1.0f);
            MVP = View * Projection;

            /* Vertices */
            var vertices = new Single[]
            {
                -1.0f,-1.0f,-1.0f,
                -1.0f,-1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f,
                 1.0f, 1.0f,-1.0f,
                -1.0f,-1.0f,-1.0f,
                -1.0f, 1.0f,-1.0f,
                 1.0f,-1.0f, 1.0f,
                -1.0f,-1.0f,-1.0f,
                 1.0f,-1.0f,-1.0f,
                 1.0f, 1.0f,-1.0f,
                 1.0f,-1.0f,-1.0f,
                -1.0f,-1.0f,-1.0f,
                -1.0f,-1.0f,-1.0f,
                -1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f,-1.0f,
                 1.0f,-1.0f, 1.0f,
                -1.0f,-1.0f, 1.0f,
                -1.0f,-1.0f,-1.0f,
                -1.0f, 1.0f, 1.0f,
                -1.0f,-1.0f, 1.0f,
                 1.0f,-1.0f, 1.0f,
                 1.0f, 1.0f, 1.0f,
                 1.0f,-1.0f,-1.0f,
                 1.0f, 1.0f,-1.0f,
                 1.0f,-1.0f,-1.0f,
                 1.0f, 1.0f, 1.0f,
                 1.0f,-1.0f, 1.0f,
                 1.0f, 1.0f, 1.0f,
                 1.0f, 1.0f,-1.0f,
                -1.0f, 1.0f,-1.0f,
                 1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f,-1.0f,
                -1.0f, 1.0f, 1.0f,
                 1.0f, 1.0f, 1.0f,
                -1.0f, 1.0f, 1.0f,
                 1.0f,-1.0f, 1.0f
            };

            /* Farben */
            var color = new Single[]
            {
                0.583f,  0.771f,  0.014f,
                0.609f,  0.115f,  0.436f,
                0.327f,  0.483f,  0.844f,
                0.822f,  0.569f,  0.201f,
                0.435f,  0.602f,  0.223f,
                0.310f,  0.747f,  0.185f,
                0.597f,  0.770f,  0.761f,
                0.559f,  0.436f,  0.730f,
                0.359f,  0.583f,  0.152f,
                0.483f,  0.596f,  0.789f,
                0.559f,  0.861f,  0.639f,
                0.195f,  0.548f,  0.859f,
                0.014f,  0.184f,  0.576f,
                0.771f,  0.328f,  0.970f,
                0.406f,  0.615f,  0.116f,
                0.676f,  0.977f,  0.133f,
                0.971f,  0.572f,  0.833f,
                0.140f,  0.616f,  0.489f,
                0.997f,  0.513f,  0.064f,
                0.945f,  0.719f,  0.592f,
                0.543f,  0.021f,  0.978f,
                0.279f,  0.317f,  0.505f,
                0.167f,  0.620f,  0.077f,
                0.347f,  0.857f,  0.137f,
                0.055f,  0.953f,  0.042f,
                0.714f,  0.505f,  0.345f,
                0.783f,  0.290f,  0.734f,
                0.722f,  0.645f,  0.174f,
                0.302f,  0.455f,  0.848f,
                0.225f,  0.587f,  0.040f,
                0.517f,  0.713f,  0.338f,
                0.053f,  0.959f,  0.120f,
                0.393f,  0.621f,  0.362f,
                0.673f,  0.211f,  0.457f,
                0.820f,  0.883f,  0.371f,
                0.982f,  0.099f,  0.879f
            };

            /* Vertex Buffer Object */
            GL.GenBuffers(1, out vbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length), vertices, BufferUsageHint.StaticDraw);

            /* Color Buffer Object */
            GL.GenBuffers(1, out cbo);
            GL.BindBuffer(BufferTarget.ArrayBuffer, cbo);
            GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length), color, BufferUsageHint.StaticDraw);

            GL.Viewport(0, 0, Width, Height);
            Console.WriteLine("Spiel geladen\n");
        }

        protected override void OnRenderFrame(FrameEventArgs e)
        {
            base.OnRenderFrame(e);

            /* Bildschirm loeschen */
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);

            /* Shader benutzen */
            GL.UseProgram(shaderProgram);
            GL.UniformMatrix4(MatrixID, false, ref MVP);

            /* 1. Attribut */
            GL.EnableVertexAttribArray(0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);

            /* 2. Attribut */
            GL.EnableVertexAttribArray(1);
            GL.BindBuffer(BufferTarget.ArrayBuffer, cbo);
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);

            /* Zeichnen */
            GL.DrawArrays(PrimitiveType.Triangles, 0, 12 * 3);
            GL.DisableVertexAttribArray(0);
            GL.DisableVertexAttribArray(1);

            /* Szene anzeigen */
            GL.Flush();
            SwapBuffers();
        }
    }
}

```

And the shaders: Vertex:

```
#version 330 core

layout(location = 0) in vec3 vertexPosition_modelspace;
layout(location = 1) in vec3 vertexColor;
out vec3 fragmentColor;
uniform mat4 MVP;

void main()
{
    gl_Position =  MVP * vec4(vertexPosition_modelspace,1);
    fragmentColor = vertexColor;
}

```

Fragment:

```
#version 330 core

in vec3 fragmentColor;
out vec3 color;

void main()
{
    color = fragmentColor;
}

```

The problem: At cameraposition 4, 3, -3 I see nothing:

At cameraposition -3, -3, 0 I see a square:

But the result of the tutorial is this:

Maybe it is because the compiler does not know that three floats of the array are one triangle?

I also do not realy understand how to give information to the vertex shader. Therefore I have seen something like this:

```
var posAttrib = GL.GetAttribLocation(shaderProgram, "position");
            GL.EnableVertexAttribArray(posAttrib);
            GL.VertexAttribPointer(posAttrib, 2, VertexAttribPointerType.Float, false, 5 * sizeof(Single), IntPtr.Zero);

            var colAttrib = GL.GetAttribLocation(shaderProgram, "color");
            GL.EnableVertexAttribArray(colAttrib);
            GL.VertexAttribPointer(colAttrib, 3, VertexAttribPointerType.Float, false, 5 * sizeof(Single), new IntPtr(2 * sizeof(Single)));

```

But in the tutorial they do it like this:

```
/* 1. Attribut */
            GL.EnableVertexAttribArray(0);
            GL.BindBuffer(BufferTarget.ArrayBuffer, vbo);
            GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);

            /* 2. Attribut */
            GL.EnableVertexAttribArray(1);
            GL.BindBuffer(BufferTarget.ArrayBuffer, cbo);
            GL.VertexAttribPointer(1, 3, VertexAttribPointerType.Float, false, 0, IntPtr.Zero);

```

But I don't understand why they use GL.BindBuffer(); again?! Or rather why they do this every frame / update?!.

So why I can't see a cube? What I do wrong?

EDIT: new screenshot:

# Answer
> 3 votes
You have this code:

```
GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length), vertices, BufferUsageHint.StaticDraw);

```

This tells OpenGL to only upload as many bytes as there are elements in the array. That's why you see only small portion of the data on screen. You need to tell OpenGL how many bytes you actually want to buffer.

```
GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length * sizeof(Single)), vertices, BufferUsageHint.StaticDraw);

```

And of course, you need to do that for both buffers.

I like to use OpenTK's Vector3 struct for passing data to the GPU, as it is designed to work well with OpenGL.

```
var vertices = new Vector3[] { new Vector3(-1,-1,0), new Vector3(0,1,0), new Vector3(1,-1,0) } // 3 vertices to form a single triangle
GL.BufferData(BufferTarget.ArrayBuffer, new IntPtr(vertices.Length * Vector3.SizeInBytes), vertices, BufferUsageHint.StaticDraw);

```

> I also do not realy understand how to give information to the vertex shader.I have seen something like this \[block of code\] But in the tutorial they do it like this \[block of code\]

The 5th parameter for the GL.VertexAttribPointer defines a stride of the data array you are buffering to the GPU. This is used to determine if there is additional data in the buffer that opengl does not need to worry about, so it can be skipped. You can use this to get the correct stride of the array with OpenTK:

```
int stride = BlittableValueType.StrideOf(vertices)

```

But in this case where you only have an array of vertex positions, you don't need stride, and 0 can be passed to the function.

Also the 6th parameter for the GL.VertexAttribPointer defines an offset of where to look for the correct data value. Because the array only holds vertex positions, zero is given because no offsetting is needed. If you combined the two values in a single array, then you would need to add `sizeof(Single) * 3` as offset for the color if it is defined in the array after every vertex position.

> But I don't understand why they use GL.BindBuffer(); again?! Or rather why they do this every frame / update?!.

When you are not using Vertex Array Objects (VAO), and if you are using multiple buffers for drawing, you need to bind the buffers every frame. This is because OpenGL is a state machine and the buffers currently bound will be used when you issue a draw command. A buffer needs to be bound when you set shader's attribute pointers, or when you are buffering some data in to it.

Of course in this case where you only need to draw the single mesh, you don't need to bind the buffers every frame. But in most OpenGL applications you don't draw a single meshes.

---
Tags: c#, opengl, c++, opentk
---