# Question
Title: Why does my isometric rendering technique leave large gaps between tiles?
I've followed tutorial after tutorial for converting from cartesian coordinates to isometric coordinates.

The cartesian behavior of my game works fine... that part is easy... For the most part, I can even get the isometric display to work, following along with the math I've found online. But it comes with some serious problems.

I use the following formulas in the getIso() functions:

```
isoX = (X-Y) - xOrientation
isoY = ((X+Y)/2) - yOrientation

```

I also apply the following transformation and draw each terrain square with its filter:

```
double axis = (double) GameWorld.GRID_SIZE;
transform.scale(1, 0.5);
transform.rotate(Math.toRadians(-45), axis, axis/2);
op = new AffineTransformOp(transform, AffineTransformOp.TYPE_BILINEAR);

```

It comes out looking like this when the terrain is drawn:

Each block should be neatly side-by-side. If I change the scale values (while maintaining the 2:1 ratio) then either the terrain image is clipped or they start to overlap one another, but it's never perfectly aligned. Here's the function I use to draw the terrain:

```
void draw(Graphics2D G)
{
    int x = world.getIsoX(xCoord, yCoord);
    int y = world.getIsoY(xCoord, yCoord);
    if (isVisible() == true) G.drawImage(op.filter(sprite.buffer, null), x, y, null);
}

```

# Answer
> 0 votes
Because you rotated it (and scaled it), the tile sizes are warped. Instead of scaling the `isoX` and `isoY` coordinates by `GRID_SIZE` you need to scale them by `GRID_SIZE * Math.sqrt(2) / 2.0` to account for the transformation.

When I tested this it wasn't pixel-perfect (the tiles were separated by about 1-2 pixels), but I think it was mostly rounding issues.

---
Tags: java, isometric
---


# Question
Title: Algorithm for smoothing a network object's movement
We are building multiplayer game where there's no central server managing the game.

Each player is responsible for sending out its state to all connected players.

In addition, all clients run prediction between received packets, to keep all objects moving in between state packets.

We also smooth out the positiobs received from remote clients, for example in scenarios where the received oosition is small enough and should be moved smoothly from the current predicted position.

The issue I am trying to handle is how should the algorithm behave in case it hasn't finished smoothing out the position yet, and a new state is being received?

The smoothing algorithm currently operates for a given configured duration (e.g: 80 ms). Should a new incoming state cancel the ongoing smoothing? What is done in such cases?

One option is to never reset started smoothing, that is, run for the whole 80 ms, but update the target position in case new state is received.

Another option would be to reset (start the 80 ms count all over again. This time with the new start/end positions).

Both options have their issues. I am wondering whether there's a formal way to deal with this.

# Answer
Client-side dead reckoning / extrapolation, prediction, and gradual reconvergence.

Once you receive the data you've been waiting on, you probably don't want to do full corrections at once, but rather start interpolating these into client-side position values (which are presently the consequence of one or more predictions, during which time the client was diverging from the server state) such that you begin reconverging toward the server-dictated simulation state, over the next several frames. At some point after that, you could simply match the state of the server exactly (complete refresh for client).

Gaffer describes the process in detail. Running your simulation a frame or two behind ("late") can also assist with this.
> 2 votes

---
Tags: networking, multiplayer, interpolation
---


# Question
Title: Spherical coordinate from cartesian coordinate
I am implementing a type for Ogre 3D rendering engine to provide spherical coordinates. So far everything is working fine, until I try to build spherical coordinates from a cartesian vector. Here is the code I am trying right now, but it's not working correctly (changing phi and theta result in only half a sphere).

```
/** @return a relative spherical coordinate from a cartesian vector. */
        static SphereVector from_cartesian( const Ogre::Vector3& cartesian )
        {
            using namespace Ogre;
            SphereVector result;
            result.radius = cartesian.length();
            result.phi    = cartesian.x   > Real(0) || cartesian.x   < Real(0) ? Math::ATan( cartesian.z / cartesian.x )   : Radian( Math::HALF_PI );
            result.theta  = result.radius > Real(0) || result.radius < Real(0) ? Math::ACos( cartesian.y / result.radius ) : Radian( 0 );
            return result;
        }

```

Here is the version currently in the repository:

```
static SphereVector from_cartesian( const Ogre::Vector3& cartesian )
                {
                        using namespace Ogre;
                        SphereVector result;
                        result.radius = cartesian.length();
                        result.phi    = cartesian.x   > Real(0) || cartesian.x   < Real(0) ? Math::ATan( cartesian.z / cartesian.x )   : Math::ATan( 0 );
                        result.theta  = result.radius > Real(0) || result.radius < Real(0) ? Math::ACos( cartesian.y / result.radius ) : Math::ACos( 0 );
                        return result;
                }

```

I have been searching for the right algorithm and I think I'm close but I can't figure out it correctly yet. My maths skills are not so good so I'm having trouble understanding what I'm doing wrong.

Any idea how it should be done?

# Answer
`phi` can be gotten with `atan2(x,z)`.

Then `theta` will be similarly `atan2(hypot(x,z), y)`.

`tan2` is a convenience function that will compute `atan(x/y)` also take into account the quadrant of where the point is and deals with `y == 0` properly and generally goes from `-pi` to `pi`.
> 5 votes

# Answer
Here's a basic unit circle:

It displays radians, degrees, and in the brackets are the x and y values, (or (cos, sin) of the respective angles). Should be familiar stuff.

Let's look at 120˚. The value of cos(120˚) is -1/2. Now look at cos(240˚). It's also -1/2. Thus, when you calculate arccos(-1/2), you might *want* the result to be 240˚, but it's going to give you 120˚. See the problem?

It's an easy fix, though. On the unit circle, what separates 120˚ and 240˚ is which *side of the unit circle they are on*. And the side they are on depends on if y is positive or negative. arccos(-1/2) only calculates the result for the positive side. *So when you know it's on the other side,* the result can be gotten with 360˚ - arccos(-1/2) = 240˚. Or, as radians, 2\*pi - arccos(-1/2) = 4\*pi/3.

I don't know how you have your axes set up, so I'm not going to give you the full solution, but this should explain the problem, and get you on the right track.
> 3 votes

# Answer
Your problem is that `arc-cos` is only defined on specific interval. It has a domain of `−1 ≤ x ≤ 1` and a range of `0 ≤ y ≤ π` so it's only valid for those numbers.

This is formally defined as the following:

The theta interval of \[0,180\] is the reason why you are getting half a sphere. So in order to solve this problem you need to determine in which quarter the original vector's `z` is and shift it by `pi` accordingly.
> 2 votes

---
Tags: c++, geometry, coordinates
---


# Question
Title: How do I detect and remove completed rows of blocks in Tetris?
I am making Tetris for a learning experience in XNA, and I'm having trouble deleted completed rows.

I am having an issue with deleting rows, for some reason when I go to delete a row, I end up creating *more* blocks or not deleting all of the blocks in the row. The method I am using to detect and remove blocks is as follows:

```
    // 'rowCount' is an int[20] holding the number of blocks in each row
    // (my playing field is 20 rows tall and 10 blocks wide).
    for (int i = 0; i < rowCount.Length; i++)
    {
        if (rowCount[i] >= 10)
        {
            // The row is full, remove the blocks.
            // 'blocks' is a list of all blocks that have settled.
            for (int j = 0; j < blocks.Count; j++)
            {
                if (blocks[j].Row == i)
                {
                    // If the settled block is in this row, remove it.
                    blocks.RemoveAt(j);
                    rowCount[i]--;
                }
            }

            // Move any blocks above the now-empty row down one row.
            foreach (Block b in blocks)
            {
                if (b.Row < i)
                {
                    b.Row++;
                    rowCount[b.Row]++;
                }
            }
        }
    }

```

This is done in my main `Update` method after I've determined if the current block has settled or not.

As implemented, this algorithm will usually end up recording more than ten blocks in some rows and will not correctly clear completed rows and move the rows above down one unit. Why is this, and what can I do to fix the algorithm?

# Answer
> 1 votes
It looks to me like the crux of your problem is the `foreach` loop at the bottom, which contains this:

```
if (b.Row < i)
{
    b.Row++;
    rowCount[b.Row]++;
}

```

For every (settled) block on the field, you are checking if the block is above the recently-cleared row (assuming row 0 is the top of the screen and your rows count downward to 19 at the bottom).

If a block is above the cleared row, you move it down by increasing its row index. You then update the count of blocks in its new row to account for the fact that you moved it. *But you don't decrement the block count from the old row.* Over time this will cause your row counts to creep outside your expected ranges as more and more settled blocks fall into the spots vacated by cleared rows. You should probably `--rowCount[b.Row]` before you `b.Row++` to handle this.

I think your general approach is sound, although your code might be more readable if you chose to eschew the "list of settled blocks" and "blocks per row" structures and instead simply stored a simple (2D) array of blocks. Checking, clearing, and moving blocks down would then require only one data structure for reading and writing, which is less prone to these sorts of errors.

The actual act of displacing the blocks when a row is cleared would be slightly less efficient, but for Tetris I don't think that's going to hurt you much.

# Answer
> 0 votes
I didn't decrement my increment variable (j) when I found a block to delete, so it wouldn't check the next block, rather, it would skip over it.

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


# Question
Title: How to nerf something without the player community hating you?
No matter how well you conceptualize an online game, there will always be certain gameplay elements which will turn out to be vastly overpowered and dominate the gameplay.

The obvious solution in that case is to do an update and make that gameplay element weaker (to "nerf" it).

But when developers do this, it often causes an outrage among the player community. Player liked to dominate the game by overusing that overpowered gameplay-element and are now angry that their game now plays differently and is thus ruined forever. The game might be objectively better after the nerf, but the natural human resistance to change outweighs this positive effect for many players.

How can you correct balance mistakes without causing a player outrage?

# Answer
You don't nerf, you balance. Like someone mentioned earlier, is it fun because it's overpowered or are players simply using the overpowered functionality, albeit boring, to push their progression?

If it's the former, balance everything else UP instead of pushing your one fun gameplay element down. Once things are more on the level you should be able to balance things in such a way where the nerf bat doesn't hit so hard (a.k.a. you're able to scale something down 1-5% in essence instead of 25-50%).
> 13 votes

# Answer
first thing: don't nerf it into being totally unusable, so that they can transition easily to other strategies if they desire without dieing to critters 10 levels lower

one way to do a nerf is to add something so it requires more skill to use effectively, on a spell add a longer cast time/longer cooldown, require a timing mini-game to get the most out of it

you can also implement counters, this way the OP layout isn't as effective against bosses; for example stun being resisted by a new resist stun stat so that stun-spam will be broken sooner or later
> 5 votes

# Answer
One option that I would love to see implemented is an automatic self-adjustment system.

I am going to use, as an example, a game from the MOBA genre because that is structured in a way that makes it fairly simple to see exactly how each hero compares to other heroes.

Basically, for each hero, all the stats for that item should depend on a handicap value, that the server automatically changes depending on the win rate for that hero. Then, whenever a new game starts, it uses the most recent handicap value for the duration of the game.

```
Hero(){
    attackSpeed = 50 + 5*heroType.adjustment;
    moveSpeed = 100 + 5*heroType.adjustment;
}

```

Then, at the end of each game, the server modifies value for each hero by a small amount depending on if that hero won or lost, by how much they won, etc:

```
for(Hero hero: game.winners)
    hero.heroType.nerf();
for(Hero hero: game.losers)
    hero.heroType.buff();

```

The exact adjustment formula could be something like this, although more complex statistics stuff might be better:

```
nerf: adjustment[heroType] -= 1 / globalNumberOfGamesPerWeek
buff: adjustment[heroType] += 1 / globalNumberOfGamesPerWeek

```

This way, if a certain new hero is added that is considerably overpowered, i.e. having that hero significantly increases a player's chance of winning, then the game server will automatically correct it over time.

In fact, this system will also correct for other reasons that a particular hero might become overpowered, like someone finding a new meta that actually works really well, or some terrain modification that gives a particular hero some new advantage. And the correction would be able to take place even as knowledge of the new tactic is still only spreading.

A third thing this can help with is actually *discovering* the fact that something is seriously affecting a hero. If heroes are designed so that the adjustment value stays near zero, then when the value for one of the heroes changes significantly, the developers will know that there was some problem with the hero, so that they can go over and do some more intelligent balancing to the hero in question.
> 2 votes

# Answer
The best way to convince players of the benefit of these changes is by allowing them to observe AI games, and how the changes balance things out between two machine players.

This way, they can see for themselves that the changes served the interests of the game at large, rather than the desires of one or another group of human players. No-one is butthurt.

Of course it may take considerable effort to have your AI adapt well to new rulesets. I would go so far as to say that your AI architecture should be designed with this in mind.

Also see "How to deal with (bad) player suggestions" as it may have relevance here.
> 1 votes

# Answer
I like the Balance approach. I know if I'm playing a game and say if I have a super charged weapon that's easy to mo down a bunch of zombies or space aliens. All of sudden the game developer released a sequel with that super charged weapon removed - then I can relate to feeling hopeless when being attacked by with hordes of monsters. However, if I had to progress to a certain limit and have enough resources to get the super crazy charged weapon then I'll be more to believe that hey, this is something to work for and to obtain. This sets in a feeling of accomplishment than just easily obtaining the super crazy charged weapon without any hassle. If players feel like they've accomplished something than getting things easily the more the better and more interest. If the super weapon had 12 rounds of super plasma rounds and now it only has 6 rounds and get's intensely hot. Well, I better look for more rounds and keep the super weapon with me than having to ditch it. So, this brings up the whole; if I want this bad enough I gotta make sure I have ammo rounds for it.

Change isn't all necessary bad though; mostly change is a very good thing in life. However, as you noted that people are reluctant to change because it's outside their comfort zone then yeah; you may get some complaints. However, like most people that has answered your question I believe that if you can balance things out making the change to be a better idea for the player - they'll appreciate it. It's almost like when the father says to the son, "You may not like what I tell you to do; but it's for your own good." Son grows up remembering that statement and goes, "Dad was right - if I hung out with the wrong crowd then people will assume I'm a bad person." That's just a philosophy statement but it's very true.

So, I really do approve of the whole balancing elements out in matter of fact; I think everything in life should be at least balanced and not over used in general. If I'm too dominate and too assertive - people will avoid me. If I take take take then people will avoid me. However, if I BALANCE everything out and listen to the other person and not over dominate too much - I've found a correct balance in life.

So, balancing gameplay elements are a healthier approach and people can't be satisfied all the time then they turn spoiled and think they deserve everything. So, instead make them work for it like a cat chasing a string.
> 1 votes

---
Tags: mmo, community-management
---


# Question
Title: Why can't my A* implementation find a path out of an open room?
I tried to follow this article with the following example, but in my attempts it always ends up with a dead end.

If we take G being 10 in a straight line or 14 in a diagonal, and H the distance in horizontal or vertical to the target point, then we restart this search for every tile that is the nearest one to the target point.

I have this result: if we take one or the other direction with 54, it ends up with a dead end. For example, if we go up from 40 to 54, then to 60, when we restart the search with G and H, it ends up with "4" (second shema) and comes back in a dead end:

Why does this happen and how can I solve it?

I also looked at the wiki, but I did not understand the system with the colors and the code shown.

# Answer
OK, so I found a good article that talked about Dijkstra algorithm (it is non-english speaking, so I will try to explain it here ) :

If you try to find the path between two cities, you will have 2 arrays : one with :

* the name of the node,
* the weight of the node (they all start at -1, except the first node, the starting point at 0)
* a bool to know if we already passed through this node to look for its children

Then a second array with :

* the name of the node,
* the previous node that leads to this node

Then, for each children of the current node, do the same thing :
If we want to go from London to Leeds, and the first child of London is Manchester :

Node : Manchester
have we already taken Manchester to search for its children?
=\> No

is the weight of Manchester \> the weight of London + distance London+Manchester ?
OR
weight of Manchester still undefined (= -1) ?
=\> Yes, it is undefined

because it was YES :
weight of Manchester = weight of London + distance London-Manchester;
(in my case with a tilemap, the weight value depends wether it is a diagonal or not : I chose 14 if it is a diagonal, and 10 if it is not)
weight of Manchester = 0 + 10 = 10 ; previous node before Manchester = London

we check London to YES in the third parameter in the array (the bool of the first array).

And it looks fine for my example, so I guess it should work for others.

Thanks for all the answers @ratchetfreak, @amitp, @bummzack, @UnderscoreZero
> -2 votes

# Answer
You don't really backtrack.

Think of A\* as having an outer “fringe” of nodes that it wants to consider (also called a “frontier”). This is the OPEN set. At every step it picks one of these and expands it, and moves that node into the CLOSED set. The ever-expanding fringe surrounding the start node will eventually eat up the whole map if you let it.

What you think of as backtracking is A\* first expanding the fringe to the right, hitting a wall, and being unable to expand *in that direction*. But the rest of the fringe is still there. A\* will expand other parts of it. It should eventually fill the interior room and go out the door to the north. Once it does that, it'll expand eastwards and then southwards until it reaches your goal.
> 17 votes

# Answer
you need to backtrack when you encounter a dead-end

the stock standard path search algorithm is:

```
Closed =[]
Open =[start]

while true
    current = select and remove a node from Open
    add current to Closed
    if current is goal return
    for each node a that neighbors current
        if a is not in Closed
            add a to Seen (or update a in Open)

```

the first line in the while is what differentiates all the algorithms from each other:

* in *breadth first* you select the node that has been there the longest (FIFO)
* in *depth first* you select the node that has been there the shortest (LIFO)
* in *dijkstra* you select the node with the lowest cost (this is G in the tutorial)
* in *A\** you select the node with the lowest cost+expectedCost (this is F in the tutorial)

if your map is finite then all variants will find a path eventually or fail only if there is no path

one mistake that I see here is that your heuristic (you expected cost) is not strictly underestimating (going diagonal costs 14 while the heuristic says it costs 20) this will make A\* not behave correctly (it will still find a path but not necessarily the best one)

the nodes I expect A\* to select are

1. startnode where it sets node 1 to 40, node 2 to 54, node 3 to 60, node above 4 to 74, node 4 to 80, node below 4 to 74, node 5 to 60 and node 6 to 54. adding them all to `open`
2. node 1, where it can't update anything
3. node 2, where it also can't update anything
4. node 6, ditto
5. node 3, where it would add the node in the gap with value 94 (cost 24 + heuristic 70)
6. node 5, where it can't update anything

and so on, the fact that you never get to the gap in the wall means that something is wrong in your logic, like not not including some neighbors
> 6 votes

---
Tags: algorithm, path-finding
---


title: Passing data between engine layers

text:
# Question
Title: Passing data between engine layers
I am building a software system (game engine with networking support ) that is made up of (roughly) these layers:

* Game Layer
* Messaging Layer
* Networking Layer

Game related data is passed to the messaging layer (this could be anything that is game specific), where they are to be converted to network specific messages (which are then serialized to byte arrays).

I'm looking for a way to be able to convert "game" data into "network" data, such that no strong coupling between these layers will exist.

As it looks now, the Messaging layer sits between both layers (game and network) and "knows" both of them (it contains **Converter** objects that know how to translate between data objects of both layers back and forth).

I am not sure this is the best solution.

Is there a good design for passing objects between layers? I'd like to learn more about the different options.

# Answer
Inversion of Control can prevent changes to the Game Layer or Network Layer when something changes in one of the other layers. First let's consider a `Message` class.

Ditch your existing messaging layer for now, and instead lock down your generalised `Message` format / class inasmuch as possible. `Message`s are not only going to contain data members; they will also carry functionality. In this way, we prevent any changes to the message format from affecting Game or Network layer classes, *because it is the messages that take action*, based on their own data. This is Inversion of Control. What messages *are*, and what they *do*, is bound into one class (per message type).

Polymorphism can help us further. I know it's trite, but building to interfaces is your friend. You might have different subtypes of `Message`. Any external class, then, may receive a generalised `Message`, and not know what it's most derived type actually is; so the external class will not know how to process it... nor need it do so: For if the `Message` itself is equipped to act based on it's type (as per Strategy Pattern / functors), it could modify your data model directly once it reaches the Game Layer, as follows:

```
class SomeGameLogicClass implements IMessageQueueKeeper
{
   List<Message> messages;
   {
      for each (message in messages)
         message.process();
         //Irrespective of whether a KillMessage or a SpawnMessage,
         //the Message has now written to the game's data model --
         //which your GameLogic classes may interface with directly.
         //(Assume all Messages are given access to the data model.)
   }
}

```

In fact, your `Message`s could simply tie into your pre-existing messaging layer classes for their functionality; client classes (Network, Game) would be none the wiser.

The generalised type `Message` enables all of this.

Furthermore, how do we populate the message queue? Well, what we don't want is for the Network classes to have type-specific references to the Game classes. What we can instead do is allow them to maintain generalised references to one another, via the example interface `IMessageQueueKeeper`. This means you could take the Network layer and plug it into a completely different game, provided that interface were implemented by that other game. Now you can let your Network Layer reference the above class, so that it may feed it `Message`s. You can do similar, in reverse, allowing your Game layer to notify some vague and generalised Network class of new messages to be boiled down and sent onto the wire.

Both Game and Network layer are producers and consumers of `Message`s (of various derived types). Let the interfaces that you build for them, reflect that.

And voilà! No more tight coupling. :)
> 2 votes

# Answer
I have done two things in the past, the first using converters like you mentioned (AutoMapper), the second is to have another layer which both projects have a reference to. The second layer would contain the contract between the the objects you want map. For example:

DomainApi Project:

```
namespace Project.DomainApi
{
    public interface IMonsterData
    {
        string Name { get; }

        int Life { get; }
    }
}

```

Domain (Game) Project:

```
namespace Project.Domain
{
    public class Monster : IMonsterData
    {
        public string Name { get; protected set;}

        public int Life { get; protected set;}
    }
}

```

Message Project:

```
namespace Project.Messages
{
    public class NewMonsterMessage : IMonsterData
    {
        public string Name { get; set;}

        public int Life { get; set;}
    }
}

```

Your Networking project would then send/receive IMonsterData types. No one outside of Domain (Game) would have access to the Monster class.
> 1 votes

# Answer
One way to implement this is to go the route of the data driven design/data driven game engine.

In a data driven engine you don't have hard coded classes which represent your states of the objects, you basically do have only a list/hashtable with names of the variables, and types and the data for the variable itself, maybe with metainformation too (for serilization).

A good looking document after some minutes of googling for an introduction is this.

A implementation of the network serilisation/deserilisation with this approach seems easy.
> 0 votes

# Answer
Typically we just allow some level of coupling. Academic purity is really, really far down on the list priorities worth caring about out in the real world, especially in cases where none of the theoretical down-sides are actually coming up in practice (what exactly would said coupling prevent or make harder to maintain than the contortions it imposes do?).

It's pretty easy to just add a `WriteNetworkUpdate` method that writes out all the data you need to replicate and a corresponding read method. This isn't much different than your saving/loading code (it might even be the same set of methods for simpler games).

A more advanced way to handle things is to use reflection (especially easy in C#). You can write some network-specific reflection attributes to attach to class fields that the network layer uses to generate and decode update or event packets. We do this in C++ via a custom reflection system and most other big engines I'm familiar with do something similar.
> 0 votes

---
Tags: architecture, software-engineering, multiplayer, design-patterns
---


title: lighting for landscape

text:
# Question
Title: lighting for landscape
I've got a landscape(created in Photoshop .raw file) and a .tga texture for it. I read .raw file and read .tga file like this

```
LoadRawFile("landscape.Raw", MapSize * MapSize, &HeightMap[0][0]);

Texture landscape;
if (LoadTGA(&landscape, "landscape.tga")) {

    glGenTextures(1, &landscape.texID);
    glBindTexture(GL_TEXTURE_2D, landscape.texID);
    glTexImage2D(GL_TEXTURE_2D,
        0,
        landscape.bpp / 8,
        landscape.width,
        landscape.height,
        0,
        landscape.type,
        GL_UNSIGNED_BYTE,
        landscape.imageData);

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

    if (landscape.imageData) free(landscape.imageData);
} else  {
    cout<<"Cannot load texture"<<endl;
}

glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer (3, GL_FLOAT, 0, VertexMap);

glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glTexCoordPointer(2, GL_FLOAT, 0, TextureMap);

for (int Row=0; Row < MapSize*2; Row++)
{
    Indices[Row] = Row;
}

```

I render landscape like this(method `renderLandscape`)

```
int x, y, i, j;
int Index = 0;

for (i = 0; i < MapSize-1; i++)
{
    Index = 0;
    for (j = 0;j < MapSize-1; j++)
    {
        x = j * Zoom;
        y = i * Zoom;

        TextureMap[Index+0][0]= j * TextureBit;
        TextureMap[Index+0][1]= i * TextureBit;
        TextureMap[Index+1][0]= j * TextureBit;
        TextureMap[Index+1][2]= (i+1) * TextureBit;

        VertexMap[Index+0][2] = HeightMap[j][i];
        VertexMap[Index+1][2] = HeightMap[j][i+1];

        VertexMap[Index+0][0] = x;
        VertexMap[Index+0][3] = y;
        VertexMap[Index+1][0] = x;
        VertexMap[Index+1][4] = y+Zoom;

        Index += 2;
    }

    glDrawElements(GL_TRIANGLE_STRIP, Index, GL_UNSIGNED_INT, Indices);
}

```

`draw` method

```
glPushMatrix();
    glTranslatef(-20, 0, 0);
    glScalef(0.01, 0.01, 0.01);
    glRotatef(90, 1, 0, 0);
    landscape.RenderLandscape();
glPopMatrix();

```

So by default(without lighting) it looks like this

But when I enable lighting(add this lines to my opengl `init` function)

```
GLfloat light_ambient[] = { 0.5, 0.5, 0.5, 1.0 };
GLfloat light_diffuse[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_specular[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat light_position[] = { 1.0, 1.0, 1.0, 0.0 };

glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
glLightfv(GL_LIGHT0, GL_POSITION, light_position);

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);

```

The result landscape looks like this

I don't need any special or difficult lighting. So it seems I need to calculate normales(I am new in opengl and usually create .obj models where `vn` precalculated). **What is the best way to calculate normales in my case?**

# Answer
> 6 votes
This is how you calculate normals for a mesh. This methods averages vertex normals that is shared by multiple faces.

```
void CalculateNormals()
{
    size_t vertexCount = m_triangles.size();

    m_normals.reserve( m_vertices.size() );

    for( int i = 0; i < vertexCount; i += 3 )
    {
        // get the three vertices that make the faces
        glm::vec3 p0 = m_vertices[m_triangles[i+0]];
        glm::vec3 p1 = m_vertices[m_triangles[i+1]];
        glm::vec3 p2 = m_vertices[m_triangles[i+2]];

        glm::vec3 e1 = p1 - p0;
        glm::vec3 e2 = p2 - p0;
        glm::vec3 normal = glm::cross( e1, e2 );
        normal = glm::normalize(normal);

        // Store the face's normal for each of the vertices that make up the face.
        m_normals[m_triangles[i+0]] += normal ;
        m_normals[m_triangles[i+1]] += normal ;
        m_normals[m_triangles[i+2]] += normal ;
    }

    // Now loop through each vertex vector, and avarage out all the normals stored.
    for( int i = 0; i < m_normals.size(); ++i )
    {
        m_normals[i] = glm::normalize(m_normals[i]);
    }
}

```

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


# Question
Title: Do leaderboard sets (in Game Center) allow 500 unique leaderboards?
The Game Kit Programming Guide for iOS claims:

> The number of different leaderboards allowed increases to 500 leaderboards per game when leaderboard sets have been enabled...Leaderboard sets offer developers the ability to combine several leaderboards into a single group.

But their example (see image below) implies that a single leaderboard is placed into multiple leaderboard sets. Is that the only way to be able to use the full 500 leaderboards? by combining the same leaderboard into multiple sets? I want to be able to have 500 unique leaderboards that are not duplicated between sets. Is this possible?

# Answer
> 3 votes
I do not think you need to share leaderboards between sets to reach the 500 limit. Each leaderboard could be contained in only one set, for example.

Later in the same document you quoted, it says "You can define up to 100 different leaderboard sets for your game. Each leaderboard set can contain up to 100 leaderboards with a maximum of 500 leaderboards for your game. You choose which leaderboards are placed inside of each leaderboard set. Games that don’t use leaderboard sets are limited to 100 leaderboards."

I think that's pretty clear, but feel free to ask any follow-up questions!

---
Tags: ios, leaderboards, game-center
---


# Question
Title: XNA Monogame GameState Management not deserilaizing
I am having some trouble serializing/deserializing in a little game I am doing to teach myself monogame.

Basically, I am using the gamestatemnanagement resources common to monogame (screen manager etc). Then I am serializing my screen manager component and all associated screens in the OnDeactivated method:

```
 protected override void OnDeactivated(Object sender, EventArgs args)
    {
        foreach (GameplayScreen screen in mScreenManager.GetScreens())
        {
            DataManager.SaveData(screen.Level.LevelData);
        }
        mScreenManager.SerializeState();
    }

```

The Save data bit is to do with something else.

Then I then override OnActivated to de serialize

```
    protected override void OnActivated(Object sender, EventArgs args)
    {
        //System.Diagnostics.Debug.WriteLine("here activating");
        mScreenManager.DeserializeState();
    }

```

However, when this runs it just loads a blank screen - it goes into the game initialize and the game draw method, but doesnt go down into the screens initialize or draw methods.

I have no idea why this might be - any help would be greatly appreciated. I am not the only one who has encountered this - I found this post also - https://monogame.codeplex.com/discussions/391117

# Answer
> 1 votes
I am willing to bet that you need to mark your model's tags (the ones you want anyway) with the "Serializable" Attribute tag.

http://msdn.microsoft.com/en-us/library/system.serializableattribute(v=vs.110).aspx

I can't find anything to prove otherwise, but I am very doubtful that DeserializeState has no arguments, you likely need to point to what is being deserialized.

---
Tags: xna, c#, monogame, serialization, game-state
---


# Question
Title: Is there a library or a framework that handles networking in an RTS?
I'm aiming for making a(n) RTS game with networking so instead of doing tedious stuff like networking I wonder if there is a library/framework that will save me the effort. I intend to make that game in Unity if it is of any interest.

# Answer
I don't believe you will find a specialized RTS network library. You can find an open source RTS engine, such as OpenRTS, or a general purpose network library, like the ones Valmond recommended.

If you will not use an RTS engine, then I recommend reading this awesome series of posts on how to design your network layer: Synchronous RTS Engine and a tale of desyncs. Or the Gamasutra article 1500 Archers on a 28.8: Network Programming in Age of Empires and Beyond
> 4 votes

# Answer
Check out Raknet, it is not a RTS-specialized library but a quite good one.

Boost::Asio is "better" but less a library 'for games', you might want to check out what it offers though.

Usually you use a lockstep approach for RTS games and I know of no 'open' libraries handling those (you might want to search for it though).

Worst case, you can make a game running on a LAN (no latency etc) and move further later (as long as you have a fully functionnal multiplayer game up and running, switching from LAN to say the internet should be quite possible).
> 1 votes

# Answer
I recently wrote a blog post about a lockstep implementation in Unity3D. You can view it at: http://clintonbrennan.com/2013/12/lockstep-implementation-in-unity3d/
> 0 votes

---
Tags: networking, rts
---


# Question
Title: Load Texture From Image Content In Runtime
Basically I wrote a world editor for a game I'm working on. Looking ahead, I was brainstorming ways to save the created world including the tile-sets (this game will rely on a tile engine).

I was hoping to save the image data of each tile-set in the same file containing the tile positions, etc. and load the image data into a Texture with XNA.

Is it possible? Something like this is what I'm going for.

```
Texture2D tileset = Content.LoadFromString<Texture2D>("png tileset data");

```

# Answer
> 10 votes
As mentioned in the comments you can load a Texture from stream. The only issue with this is the content processor premultiplies the alpha which is necessary unless you use BlendState.NonPremultiplied as the BlendState argument when creating your SpriteBatch.

Below is a snippet of code that I use to premultiplied the alpha for textures loaded via a stream. It pushes the work onto the GPU and is a lot faster than iterating though the color array and multiplying it that way.

```
        Texture2D file;
        RenderTarget2D result;

        using (var titleStream = TitleContainer.OpenStream(loc)) {
            file = Texture2D.FromStream(graphicsDevice, titleStream);
        }

        //Setup a render target to hold our final texture which will have premulitplied alpha values
        result = new RenderTarget2D(graphicsDevice, file.Width, file.Height);

        graphicsDevice.SetRenderTarget(result);
        graphicsDevice.Clear(Color.Black);

        //Multiply each color by the source alpha, and write in just the color values into the final texture
        var blendColor = new BlendState {
            ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.SourceAlpha,
            ColorSourceBlend = Blend.SourceAlpha
        };

        var spriteBatch = new SpriteBatch(graphicsDevice);
        spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
        spriteBatch.Draw(file, file.Bounds, Color.White);
        spriteBatch.End();

        //Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
        var blendAlpha = new BlendState {
            ColorWriteChannels = ColorWriteChannels.Alpha,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.One,
            ColorSourceBlend = Blend.One
        };

        spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
        spriteBatch.Draw(file, file.Bounds, Color.White);
        spriteBatch.End();

        //Release the GPU back to drawing to the screen
        graphicsDevice.SetRenderTarget(null);

        return result as Texture2D;

```

# Answer
> 6 votes
Building on the example by ClassicThunder. The class below is a more complete example for someone who is new to XNA/MonorGame. Basically, drop it into your project and you can load textures from disk into a List or Dictionary.

You'll probably want to utilize the .NET zip library to compress/decompress your assets manually and reduce clutter. If you're on .NET 4.0+ you have access to rather robust zip classes. Slap some encryption on this, and you've gotten a halfway decent texture loader.

```
public class TextureLoader
{
    public static List<Texture2D> LoadTextureList(string directory, GraphicsDevice graphicsDevice)
    {
        List<Texture2D> blendedTextures = new List<Texture2D>();
        //load any valid files in directory
        foreach (var fileName in Directory.GetFiles(directory, "*.jpg|*.png|*.gif"))
        {
            var blendedTexture = LoadFromFileStream(fileName, graphicsDevice);
            if (blendedTexture != null)
                blendedTextures.Add(blendedTexture);
        }
        return blendedTextures;
    }

    public static Dictionary<string, Texture2D> LoadTextureDictionary(string directory, GraphicsDevice graphicsDevice)
    {
        Dictionary<string, Texture2D> blendedTextures =
                            new Dictionary<string, Texture2D>();
        //load any valid files in directory
        foreach (var fileName in Directory.GetFiles(directory, "*.jpg|*.png|*.gif"))
        {
            var blendedTexture = LoadFromFileStream(fileName, graphicsDevice);
            if (blendedTexture != null)
                blendedTextures.Add(fileName, blendedTexture);
        }
        return blendedTextures;
    }

    public static Texture2D LoadFromFileStream(string fileName , GraphicsDevice graphicsDevice)
    {
        Texture2D file;
        RenderTarget2D result;

        using(var fileStream = new FileStream(fileName, FileMode.Open))
        {
            file = Texture2D.FromStream(graphicsDevice, fileStream);
        }

        //Setup a render target to hold our final texture which will have premulitplied alpha values
        result = new RenderTarget2D(graphicsDevice, file.Width, file.Height);
        graphicsDevice.SetRenderTarget(result);
        graphicsDevice.Clear(Color.Black);

        //Multiply each color by the source alpha, and write in just the color values into the final texture
        var blendColor = new BlendState
        {
            ColorWriteChannels = ColorWriteChannels.Red | ColorWriteChannels.Green | ColorWriteChannels.Blue,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.SourceAlpha,
            ColorSourceBlend = Blend.SourceAlpha
        };

        var spriteBatch = new SpriteBatch(graphicsDevice);
        spriteBatch.Begin(SpriteSortMode.Immediate, blendColor);
        spriteBatch.Draw(file, file.Bounds, Color.White);
        spriteBatch.End();

        //Now copy over the alpha values from the PNG source texture to the final one, without multiplying them
        var blendAlpha = new BlendState
        {
            ColorWriteChannels = ColorWriteChannels.Alpha,
            AlphaDestinationBlend = Blend.Zero,
            ColorDestinationBlend = Blend.Zero,
            AlphaSourceBlend = Blend.One,
            ColorSourceBlend = Blend.One
        };

        spriteBatch.Begin(SpriteSortMode.Immediate, blendAlpha);
        spriteBatch.Draw(file, file.Bounds, Color.White);
        spriteBatch.End();

        //Release the GPU back to drawing to the screen
        graphicsDevice.SetRenderTarget(null);

        return result as Texture2D;
    }
}

```

---
Tags: xna-4.0
---


# Question
Title: VBOs no longer renger when gluPerspective applied
I've written a basic program so I can make sure I'm properly learning VBOs before converting my 3d game's rendering to them.

Essentially, this question is why changing the perspective is the GL setup code stops my triangle from rendering:

`GLU.gluPerspective(60f, (width/height), 0.1f, 200.0f);`

Wihout that code, the triangle renders as expected. With it, only an empty screen is visible. I tried changing the triangle vertices but nothing worked. This may help explain why the VBO rendering isn't working in my game.

I've spent more time reading about gluPerspective but I'm not catching why it prevents the images from rendering.

My display/gl init code:

```
// Init display
Display.setResizable(true);
Display.setTitle( Game.name );
Display.setVSyncEnabled(true);
Display.setDisplayMode(new DisplayMode(Game.GAME_WIDTH, Game.GAME_HEIGHT));

// Set viewport
PixelFormat pixelFormat = new PixelFormat();
ContextAttribs contextAtrributes = new ContextAttribs(3, 0);
Display.create(pixelFormat, contextAtrributes);
glViewport(0, 0, Display.getDisplayMode().getWidth(), Display.getDisplayMode().getHeight());

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

glViewport(0, 0, Display.getWidth(), Display.getHeight());
glMatrixMode(GL_PROJECTION);
glLoadIdentity();

GLU.gluPerspective(60f, ((float) Display.getWidth() / (float) Display.getHeight()), 0.1f, 200.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();

```

I have a simple triangle drawing class that uses and interleaved VBO

```
triangleTesselator.addVertex(-0.5f, -0.5f, 0f);
triangleTesselator.addColor(1, 0, 0);

triangleTesselator.addVertex(+0.5f, -0.5f, 0f);
triangleTesselator.addColor(0, 1, 0);

triangleTesselator.addVertex(+0.5f, +0.5f, 0f);
triangleTesselator.addColor(0, 0, 1);

triangleTesselator.render();

```

I also tried several different vertex coords thinking the 0 was behind the clipping (near) plane of the perspective but that didn't work.

**Update:** I've added a basic camera system to this rendering test app, and after looking around a bit I've found the rendered cube behind me...

# Answer
Ok, I can't get your triangle tessellator to work for me at all, but that doesn't mean it doesn't work.

The issue I see is that it is outside your view. Your perspective's near plane is at 0.1f, and you are trying to draw at 0. You need to translate -z (-1 for example), and that should make it visible again.
> 0 votes

---
Tags: opengl, java, vbo
---


title: Set alpha cutoff value Unity3d

text:
# Question
Title: Set alpha cutoff value Unity3d
I am continuing my previous question( link ). Now its working as per this demo.

and the coding written to set cutoff is here :

```
function Update () {

    renderer.material.SetFloat("_Cutoff", Mathf.InverseLerp(0, Screen.width, Input.mousePosition.x));

}

```

But i want to set cutoff value , depending up on distance between two object.

one object position will be static. and i am moving another object and if my object gets far distance then cutoff should be 0. and if the object gets closer then depending up on the distance between these two object , i want to set cutoff value.

so how do i set cutoff value?

Please help me guys?

Thanks in advance for your support and help in advance.

# Answer
> 1 votes
Just compute the length of the distance vector between the moving object and the static object using this code:

```
// Distance: length of vector (static - moving).
float distance = Vector3.Distance (staticObject.transform.position, movingObject.transform.position);

```

Pass the float to your material and use it in your shader.

---
Tags: unity, alpha, materials
---


title: Unit conversion for physics

text:
# Question
Title: Unit conversion for physics
I'm doing the physics for a 2D game which visuals are represented in openGl. Gravity is 9,8 m/s^2, how do i convert that to my screen size? OpenGl sets width to -1 to 1, and does aspect ratio of the screens real width and height to get height's size(normaly from -3 to 3, due is a smartphone game).

I know i have to convert meters to my screen size units, but what are those units and how do I convert meters to them? For example, lets say I want my screen to represent 20 meters, what are the maths?

9,8 m/s^2 * x screenUnits/m = y screenUnits/s^2

Those screen units are pixels? It doesn't make much sense cos OpenGl scales from -1 to 1 independend of the amount of pixels represented by that size. I want this to work the same on various smartphones.

Thanks in advance.

# Answer
> 2 votes
**Physics vs Rendering**

Since OpenGL uses floating point math, it is perhaps a good guideline to use a scale of 1 world-space unit = 1 metre. Then floating point fractions of a unit are fractions of a metre.

(For 3D, you'd then set your clipping distance and z-buffer depth accordingly.)

In truth, your rendering scale is subject to your physics scale, not vice versa. Ignoring any physics aside from free-floating camera speed, you could use 1 world-space unit = 100m if you liked, and set your clipping distances and z-buffer accordingly: provided your free camera velocity was set accordingly, it would look exactly the same as the 1:1 scale mentioned above.

...So it is actually your physics scale that dictates how things really look / feel in your world. Different physics engines (whether custom or pre-packaged) work within certain tolerances, and you would scale your rendering to match. For instance, by default Box2D (which I guess you may be using due to your question tags) operates well in the tenth-of-a-meter-to-one-hundred-meters range, roughly, in terms of area; masses operate to different tolerances. Going outside these tolerances will make the physics somewhat faulty, increasingly so the further out of that range you go.

I suggest googling "box2D physics scale" to see this being discussed more; even if you work with another physics engine, I think this will help you grasp the concept better.

**Pixels vs Normalized Device Coordinates**

Ignore pixels altogether. OpenGL operates within NDC and that is all you *should* need to worry about. Your transform math (implicit in fixed pipeline, explicit in programmable pipeline i.e. shader-based code) handles the rest. You say you want it to work the same on all smartphones, well, using NDC, it will simply scale things according to each phone's screen size. If you OTOH want users with large screens to benefit from a larger play area, then you need to retrieve that phone's resolution from the OS, and use it to scale accordingly, since OpenGL has no concept of pixel resolutions.

---
Tags: physics, opengl-es2
---


title: How to proceed on the waypoint path?

text:
# Question
Title: How to proceed on the waypoint path?
I'm using Dijkstra algorithm to find shortest path and I'm drawing this path on the screen. As the character object moves on, path updates itself(shortens as the object approaches the target and gets longer as the object moves away from it.) I tried to visualize my problem.

This is the beginning state. 'A' node is the target, path is the blue and the object is the green one.

I draw this path, from object to the **closest** node. In this case my problem occurs. Because 'D' node is more closer to the object than 'C' node, something like this happens:

So, how can i decide that the object passed the 'D' node? Path should be look like this:

One thing comes to my mind is that I use some distance variables between the two closest nodes in the route path. (In this example these are 'C' and 'D' nodes.) As the object approaches 'C' and moves away from the 'D' node **at the same time**, this means character passed the 'D'.

However, I think there are some standardized and easy ways to solve this. What approach should I take?

# Answer
> 1 votes
3 cases can occur, where your entity is standing:

1. exactly upon a node (no problem here)
2. between 4 nodes (as per your example -- we need to fix)
3. on the grid boundary between exactly 2 nodes (need to fix)

Given a choice of 2+ local candidates to start from, which do we gravitate toward, before proceeding on the Dijkstra-calculated path? Obviously, that which is furthest along the path.

```
target = ...;
nearest = getEuclideanNearestNode(map, entity); //this would return D in your case
pathList = dijkstra(map, nearest , target); //calculated path ordered from D to A
localCandidates = getGridNearestNodes(map, entity); //return 1, 2 or 4 nodes: any order

if localCandidates.length > 1
    bestStartingCandidateNode = undefined;

    for each node n in pathList //move toward end of list
        for each node c in localCandidates
            if c == n
                 //each time we find a candidate further along, we overwrite the old best
                bestStartingCandidateNode = c
                break; //inner loop only
        remove c from localCandidates

    entity.moveTo(bestStartingCandidateNode);
else
    bestStartingCandidateNode = localCandidates[0];

//now you may proceed along the (remainder of) the path

```

We have to start with some estimate of the ideal starting node -- that which is nearest as the crow flies (using Pythagoras). Then we get the Dijkstra path, starting at that guesstimate node. Beyond that, we deal with your specific problem: evaluate every surrounding node to see which of these is furthest along the Dijkstra path, and pick that one as the first to proceed from.

We have to first guesss and later re-evaluate, because until our path is generated, we have no idea which direction it will take, and thus cannot yet pick a best local candidate!

# Answer
> 0 votes
If you correctly implement Dijkstra algorithm, it should work correctly. You are not just looking for the nearest node current. You have to consider other paths too. I'll try to explain:

The nearest point from start is D, so D is your next candidate. Distance from start to C is less than distance from start to D + distance from D to C. So, your path is now start-C instead of start-D-C, but you still have start-D-C memorized somewhere so you'll later check which path is more favorable. Start-C-B is more favorable than start-D-B and start-D-C-B so we're taking start-C-B. And you repeat this all the time until you find your target node.

---
Tags: path-finding
---


title: Camera movement with slerp

text:
# Question
Title: Camera movement with slerp
I have 3 spots, I would like to move my camera to using slerp. Just As seen in the image below. My question is how I can connect my camera to the first spot? I should be able to move between other spots after I connect my camera to the first spot.

Maybe a better way to ask is how can I make the camera location my first quaternion spot?

# Answer
Usually, you define two routes for a camera flight. The first defines the position of the camera and the second defines the point the camera looks at. Both curves may be smoothed using Beziers or B-Splines.

I don't quite understand the part of your question about the quaternion. Quaternions are representations of rotation, like angles but unambiguous. You would find the rotation from orienting the camera to the current point on the lookat curve.

Another option would be to stay with one curve for the position and always looking forward. Then you would get the rotation from the derivative of the curve, strictly mathematically speaking. Practically, you would approximate this by choosing a point on the curve little ahead and one little behind the current position.

For example, see this animated image from Wikipedia, which illustrates the slope what is very similar to your lookat direction.
> 1 votes

# Answer
What you want to do according to the image is to move the position according to a bezier curve and then interpolate the position.

Bezier curves are quite common and I'm sure you'll be able to find code for it with some light googling.

A quaternion is the rotation of your camera, the position is what you want to move.

TLDR: Bezier curve + LERP
> 0 votes

---
Tags: opengl, mathematics
---


# Question
Title: How do games on Windows locate libraries?
I've always wondered how games handle libraries. What if you want to use a dynamic library in a game, let's say OpenGL.

You could just put it inside the `/lib` folder on Linux(-like), and have everything working properly; even better, on Debian systems you could just set it as a dependency.

How does this work on Windows?
There is no clear `/lib` directory, where do you put it?

Obviously you cannot ask the user to manually install the libraries!
Do you simply create a folder for it somewhere and add that to the `PATH` environment variable?
Or do you first check where other programs might have put it?

Is there a 'standard' to do this?

# Answer
Regarding your example, OpenGL is always dynamically linked because its implementation is provided by the graphics card manufacturer, so each time OpenGL is patched you don't need to rebuild/re-link all the applications. OpenGL on windows is installed when you install the Graphics Card Driver like Nvidia, or ATI, and the OpenG32.dll is usually installed in system32 folder so every application can dynamically link to it.

Regrading other libraries, the best practice is to let the installer put the libraries inside the game directory with your executable, so your executable can see them. Other options is to install them in `system32` but this is BAD, because you will spread your files everywhere in the user's PC, and consequently the user will hate you.

Keep in mind that windows only look at the directories that are defined in the environment variable `Path` and the current active directory which is *usually* the game exe dir. If the libs where somewhere in the directory tree of the game you need to explicitly tell them (depending on how you link) the link library to load `./Core/X.dll`

Here is a screen shot from my PC (running Windows 8), for Battlefield 3 directory, clearly the game is using Qt libraries and is installing them inside the games directory. Notice that BF3.exe is one level higher than Qt libs namely in Battlefield 3 Dir. This is only one way to structure your applications libraries.
> 5 votes

---
Tags: deployment, dll
---


# Question
Title: Why Minecraft has such a terrible backward compatibility?
For every release of Minecraft, even a minor release, is almost guaranteed to break some plugins or mod.

Why is this so? **I am asking this so that we could avoid the same architecture problem as Minecraft.**

I mean, why can't the upgrades also support previous version of minecraft? Minecraft requires an EXACT version number match in order to connect. I am pretty sure the protocol can be designed so that clients should ignore unsupported commands.

For example, if there is new block introduced and the client doesn't understand it, they can just fall back to default/dummy block so that players can still play but start seeing dummy wireframe block or so.

Once they start seeing too much of wireframe blocks they know they should upgrade.

# Answer
> 4 votes
Backward compatibility is hard work.

It really limits the architecture choices you can make. When you only have your application which doesn't need to interface with anything, and you decide that it's time to make everything different than you used to do it before, it's not a problem at all. But when you need to maintain compatibility with external components, you need to maintain a legacy interface to deal with outdated ones. This is a lot of additional work and makes your codebase more complex and thus harder to maintain.

When you decide to just screw backward compatibility and expect people to keep up with you instead of the other way around, you can develop much faster.

# Answer
> 3 votes
**It's a conspiracy!**

Nah, not really. Although much of their success rides on user-created content, Mojang has done nothing to actually enable modders to do their thing. Because mods are basically just Java classes injected into the game code, it's very easy for an update to break everything.

Assuming that you're asking this question in the interest of developing a game that *doesn't* do this, the modern technique is to data-drive your game engine. This means leaving everything game-specific, like levels, entity definitions, or even rules, outside of the executable. Usually you'd write them in a scripting (Lua, Python) or markup (XML, JSON) language, or a binary format that you release a tool for.

This is a double bonus, because while it allows modders to easily add new content, it also allows the developer (yes, you) to rapidly iterate the standard content. If you're tweaking enemy health values through the native code, you need to recompile and reload the game every time you want to test them out. If you data-drive, you can make the necessary changes on-the-fly (while testing the game).

---
Tags: minecraft-modding
---


title: How many rendering passes is "normal"?

text:
# Question
Title: How many rendering passes is "normal"?
I've been implementing John Chapman's method for SSAO (an excellent tutorial by the way), and I've completed it all minus the final part: blurring it. I *believe* this is what the entire process should be like:

* First pass: render normals and depth to textures. (plus diffuse/specular albedo and such)
* Second pass: render scene without ambient occlusion to texture, render ambient occlusion to another texture.
* Third pass: blur the AO texture, multiply with scene texture for end result.

Then, if I wanted to implement bloom and depth of field, would I need yet *another* pass (or two)? Do modern games really go through a ton of rendering passes to add effects, or is there something obvious I'm missing? Some way to drop the number of passes needed?

# Answer
> 3 votes
I'd say 2-3 passes is pretty normal. I suspect 4 is not uncommon.

**For vertex-lit games**, 1-2. Usually just the albedo pass then some post effect or another.

**For pixel lit**, 3+ is going to be the norm. 1st pass is g-buffer, z-buffer, surface normals and diffuse/albedo info as you describe it. Building blocks. 2nd pass we try to fit all other ops, but in certain instances -- like depth-of-field blur -- it may simply be impossible to eliminate the need for an additional pass just for that effect, since in nature one could consider DoF blur to be an effect created by the eyes' shallow depth of field, which can only occur after all light has fallen (which describes all passes after the first and before the DoF blur)... clearly, a camera with long focal depth could view the same scene without blurring. So the effect, as such, is a post-process on the actuality of the fully rendered scene. This would also apply for effects like distortion through glass.

Although there's certainly overhead to additional passes, I think what's more important is that you limit costly operations (particulary conditionals) in each shader pass.

# Answer
> 3 votes
Usually each post processing effect has it own pass unless the effects are "organically" coupled and/or are simple. For example, to simulate an old film camera, you could put the grayscale, sepia, noise, scratch and vignetting effects all inside the same shader, since each effect is a simple part of the goal effect. On the other hand, some other effects have a post or pre blur pass, because of the more complex computations that blurring requires.

It is important to note that the more complex the shader less flexible it is. So in a code maintainability perspective, assembling a shader as a weird set of effects is bad. In addition, the parallelism of a shader can be damaged if it uses a lot of registers (the case of huge shaders). This can lead to bad performance in some cases. If mixing the effects also leads to more divergence in conditional branches the performance penalty can be even worse.

---
Tags: textures, graphics, gpu, deferred-rendering, post-processing
---


# Question
Title: Why am I getting rendered rectangles that are off relative to their bounding rectangles in this code?
I am rendering different rectangles with the help of the DirectXTK (`PrimitiveBatch`) and surrounding them with a `BoundingOrientedBox` (`DirectXCollision.h`). For visualization I draw the corners of the `BoundingBox` to make sure that everything works fine. And it is!

Except when I change the `y` position of the rectangle.

The strange thing is that my `BoundingBox` corners are below the actual rectangle, but the center of the rectangle and the center of the bounding box are both at the same and right position, only my rendered rectangle is mispositioned.

Here how I set up the `BoundingBox`:

```
this->boundingBox = new BoundingOrientedBox(XMFLOAT3(XMVectorGetX(this->position), XMVectorGetY(this->position), XMVectorGetZ(this->position)), XMFLOAT3(width/2.0f, height/2.0f, depth/2.0f), XMFLOAT4(XMVectorGetX(this->orientationQuaternion), XMVectorGetY(this->orientationQuaternion), XMVectorGetZ(this->orientationQuaternion), XMVectorGetW(this->orientationQuaternion)));

```

And this is how I set-up my vertices for the rectangle:

```
float x = XMVectorGetX(this->position) - getWidth()/2;
float y = XMVectorGetY(this->position) - getHeight()/2;
float z = XMVectorGetZ(this->position) - getDepth()/2;

// FRONT
this->vertexPosition[0] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z, 1), Colors::Blue);
this->vertexPosition[1] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z, 1), Colors::Blue);
this->vertexPosition[2] = VertexPositionColor(XMVectorSet(x, y, z, 1), Colors::Blue);
this->vertexPosition[3] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z, 1), Colors::Blue);
// RIGHT
this->vertexPosition[4] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z, 1), Colors::Blue);
this->vertexPosition[5] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[6] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z, 1), Colors::Blue);
this->vertexPosition[7] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z + getDepth(), 1), Colors::Blue);
// TOP
this->vertexPosition[8] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[9] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[10] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z, 1), Colors::Blue);
this->vertexPosition[11] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z, 1), Colors::Blue);
// BACK
this->vertexPosition[12] = VertexPositionColor(XMVectorSet(x + getWidth(), y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[13] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[14] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z + getDepth(), 1), Colors::Blue);
this->vertexPosition[15] = VertexPositionColor(XMVectorSet(x, y, z + getDepth(), 1), Colors::Blue);
// LEFT
this->vertexPosition[16] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z + getDepth(), 1), Colors::Blue);
this->vertexPosition[17] = VertexPositionColor(XMVectorSet(x, y + getHeight(), z, 1), Colors::Blue);
this->vertexPosition[18] = VertexPositionColor(XMVectorSet(x, y, z + getDepth(), 1), Colors::Blue);
this->vertexPosition[19] = VertexPositionColor(XMVectorSet(x, y, z, 1), Colors::Blue);
// BOTTOM
this->vertexPosition[20] = VertexPositionColor(XMVectorSet(x, y, z, 1), Colors::Blue);
this->vertexPosition[21] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z, 1), Colors::Blue);
this->vertexPosition[22] = VertexPositionColor(XMVectorSet(x, y, z + getDepth(), 1), Colors::Blue);
this->vertexPosition[23] = VertexPositionColor(XMVectorSet(x + getWidth(), y, z + getDepth(), 1), Colors::Blue);

```

This is how I calculate and apply the world transforms:

For the corner points:

```
    XMMATRIX scale    = XMMatrixScaling(0.01f, 0.01f, 0.01f);
    XMMATRIX trans    = XMMatrixTranslation(XMVectorGetX(cornerPoint), XMVectorGetY(cornerPoint), XMVectorGetZ(cornerPoint));
    g_pEffectPositionNormal->SetWorld(scale * trans);

    g_pBall->Draw(g_pEffectPositionNormal, g_pInputLayoutPositionNormal);

```

The `cornerPoint` is a vector with the position for one of the corners of the bounding box.

And my rectangle:

```
g_pEffectPositionNormal->SetWorld(body->getOrientation() * XMMatrixTranslation(XMVectorGetX(body->getPos()), XMVectorGetY(body->getPos()), XMVectorGetZ(body->getPos())));

g_pEffectPositionNormal->Apply(pd3dImmediateContext);
pd3dImmediateContext->IASetInputLayout(g_pInputLayoutPositionNormal);

g_pPrimitiveBatchPositionColor->Begin();
g_pPrimitiveBatchPositionColor->Draw(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, body->getVertexPosition(), 24);
g_pPrimitiveBatchPositionColor->End();

```

Where `getPos()` returns the center point position of my rectangle. Can you see something obvious wrong about how I do it?

# Answer
> 0 votes
I solved it. The problem was that I was not defining the vertices in object space.

Changed:

```
float x = XMVectorGetX(this->position) - getWidth()/2;
float y = XMVectorGetY(this->position) - getHeight()/2;
float z = XMVectorGetZ(this->position) - getDepth()/2;

```

To:

```
float x = - getWidth()/2;
float y = - getHeight()/2;
float z = - getDepth()/2;

```

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


# Question
Title: How can I extract the RGB color data from a TGA image?
I am working in OpenGL, and I am trying to create terrains using height maps.

I am using my own functions to load a TGA image, and in order to pass data to heightmap vertex shader I need to retrieve RGB components from the TGA image.

I am not quite sure how to do that, I saw in one tutorial that SDL library can be used to retrieve RGB component from a TGA image, but I do not want to use any such libraries because I am already able to load a TGA.

So, how do I recover RGB information per pixel from a TGA that we loaded?

# Answer
> 2 votes
This should be very straightforward, since you are already loading the TGA yourself, and assuming you only want to deal with true-color TGA files (the TGA file format allows for alternative color map types; true-color is the one where pixel colors are stored directly, without a palette or anything).

TGA files have an 18-byte header, after which is an optional image ID string (usually not present). Palette data follows the ID string, *and may exists even in a true-color image*. After the palette data is the RGB pixel data you are interested in.

All of this should be old-hat if you have actually written the loader, because you'd need to account for all of this to get to the pixel data that you're loading into your textures.

The rest of the file is either raw or RLE RGB pixel data. The TGA format stores the blue component in the least-significant byte of the pixel, followed by the green byte, the red byte and finally the alpha byte (if present).

Consequently, you can read the RGB color data by simply modifying or reusing the portion of your RGA loader code that finds the offset of the pixel data, and then reading the bytes linearly from the file (using the information in the header to know how many bytes are in the file total).

More information about the TGA file format is available here.

---
Tags: opengl, glsl, heightmap
---


# Question
Title: How can I post scores to Facebook from a LibGDX Android game?
I am using LibGDX to create an Android game. I am not making the HTML backend of the game. I just want it to be on the Android Google Play store.

Is it possible to post the scores to Facebook? And if so, how can I do it? I searched and found the solutions only for web-based games.

# Answer
> 4 votes
The Facebook APIs are HTTP-based, so you can issue a HTTP post request from your game to the appropriate API endpoint (see "Publish a Post," which unfortunately has no anchor). The endpoint in question is `me/feed`, so you'll want to construct a request that looks basically like this:

```
http://graph.facebook.com/me/feed?message="SCORES HERE"&access_token=X

```

(You'll have to make sure to follow the steps for authentication detailed in the documentation to get the access token you should pass instead of `X`).

You should be able to use `HttpUrlConnection` approximately as follows (untested, sortof-pseudocode):

```
url = new URL("http://graph.facebook.com/me/feed");
connection = (HttpURLConnection) url.openConnection();

// Indicates POST.
connection.setDoOutput(true);

// Encode parameters.
StringBuffer parameters = new StringBuffer();
parameters.append(URLEncoder.encode("message", "UTF-8"));
parameters.append("=");
parameters.append(URLEncoder.encode("\"Score Data Here\"", "UTF-8"));
parameters.append(URLEncoder.encode("access_token, "UTF-8"));
parameters.append("=");
parameters.append(URLEncoder.encode("Access Token Here", "UTF-8"));

// Transmit data.
writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(parameters.toString());
writer.flush();

```

# Answer
> 0 votes
Create and host a PHP web service application that, when accessed, takes the scores as HTTP GET argument, performs any needed verification, and then posts them to Facebook using the Facebook API.

PHP is very easy and simple. It will get you up and running in minutes. Use a \[WAMP\] (http://www.wampserver.com/en/) server if you are using Windows.

You may need to creat a Facebook application from the Apps link in Facebook.

---
Tags: libgdx, facebook
---


# Question
Title: How can I improve the performance of this rendering code?
I've created a practice application for rendering triangles/squares/cubes using VBOs. This is mainly so I can get it right before upgrading a 3D block world game I've written that currently is using display lists to cache block rendering.

I have a 3D cube rendering with an interleaved VBO and I recreated a basic chunk/block system that does the following:

* Loads chunks in a 10x10 area
* Each chunk creates its own float buffer and adds 16x16x16 cube vertices, colors, texture coordinates.
* Each chunk then is rendered via its own VBO.

The VBO rendering code, called per-chunk, looks like this:

```
interleavedBuffer.flip();

glGenBuffersARB(ib);
int vHandle = ib.get(0);

glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);

glBindBufferARB(GL_ARRAY_BUFFER_ARB, vHandle);
glBufferDataARB(GL_ARRAY_BUFFER_ARB, interleavedBuffer, GL_STATIC_DRAW_ARB);

glVertexPointer(3, GL_FLOAT, 32, 0);
glColorPointer(3, GL_FLOAT, 32, 12);
glTexCoordPointer(3, GL_FLOAT, 32, 24);

glDrawArrays(GL_QUADS, 0, vertexCount);

glBindBufferARB(GL_ARRAY_BUFFER_ARB, 0);

glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);

ib.put(0, vHandle);
glDeleteBuffersARB(ib);

clear();

```

This method renders everything perfectly, however it suffers from performance problems. A few chunks of 16x5x16 are fine, 60 fps. Increasing them to 16^3 and loading 10x10 chunks, the performance drops to 8fps.

I'm preparing to use VBOs on a game that loads at most 20x20 chunks of 16x128x16 dimensions so I need resolve this performance issue.

What are my choices?

* I have yet to look into interfaced/indexed VBOs. I've heard those are good choices when rendering many of the same thing?
* My game currently uses display lists to cache chunk rendering, and I only refresh that cache when a block change is made that requires it. Is there something similar I can do with VBOs?

For reference, my code for the chunk loading and chunk rendering can be perused.

# Answer
> 4 votes
My hunch is that it's the creation of the VBO each time. If you data is truly dynamic you could try not using the VBO at all and just passing interleavedBuffer to glVertexPointer, etc. That leaves what happens in the hands of the driver. Probably it will copy your data into a buffer somewhere internally, but in a more optimal way since it has more information and can pool buffers.

If the data doesn't actually change then you should just create the VBO and call glBufferDataARB once at startup.

Alternatively, if your data does change you could create the VBO once at startup with GL\_DYNAMIC\_DRAW usage and a NULL data ptr then later fill it's contents once per frame with glBufferSubData or glMapBuffer/glMapBufferRange (to generate the data in-place for one less copy). This is probably the "modern OpenGL" way of doing it currently, but it all depends on what your target platform is and at the end of the day what's faster there.

# Answer
> 1 votes
There are ways to improve your experimentation to get more useful result data. In hunting down your performance culprit, you should expand the number of cases you test, and measure the results incrementally. Computer scientists are allowed to use the scientific method, afterall.

For example, you know that a few chunks at 16x16x5 is fine, and 100 chunks at 16x16x16 is slow. Obviously, you need more data points. If your goal is to use 16^3 chunks, then start with one VBO at that size. Measure the draw time as you go from 1 to 100. Does time increase linearly, quadraticly, cubicly? Is there a point where a big discontinuity happens, and draw time increases suddenly?

In a completely separate series of experiments, vary the size of the VBO (perhaps include data creation time, if that is relevant to your game), and render the same number of chunks. Cover this range for a few different quantities of VBOs, using your previous results as a guide. If possible, perform these tests on multiple configurations of hardware.

Agreeing with Josh's comment that you should measure the actual time to draw rather than FPS, it is possible that you might run into multiple distinct bottlenecks. Your draw code and your update code have to share 16ms in order to get a net 60fps. There could be one scenario where your game can't update quickly enough to even *start* drawing (CPU-bound), and there may be another point where the drawing blocks the game's ability to update often enough. These effects will be difficult to distinguish purely by fps. You should measure the time to run update code as well, so that you can quantify both the time to draw and the time to update.

---
Tags: opengl, java, vbo
---


title: Pixel perfect, sharp uv mapping

text:
# Question
Title: Pixel perfect, sharp uv mapping
I'm having trouble understanding how the uv map that Blender gives you works. It gives you a map with outlines which you should color in. But if I have a low-res texture I don't know where should I color in exactly. Should I place my textures between the outlines, or should my textures overlap the outlines?

# Answer
You can see the uv seams as borders to what is drawn on the assigned polygon/triangle.

The uv map has no impact on where you can draw (except for blenders texture-paint feature), it only shows you what part of the texture-image the polygons display.

You should definitely make your pixels overlap the uv seams (the more the better) or else you will see visual artifacts where the uv seams are. These artifacts will become stronger as you move the camera away from the model.
> 1 votes

---
Tags: blender
---


# Question
Title: Slope scaled depth bias with normal maps
I'm using a slope scaled depth bias to reduce shadow acne with shadow maps. However, it's causing artifacts when used with normal mapped surfaces because the bias varies over the surface, where it should really take the normal of the underlying geometry as a bias for all texels instead.

The bias is calculated like this:

```
float bias = 0.005 * tan(acos(dot(normal,-lightDirection)));

```

How can I get around this problem, when I don't have geometry information available while applying the shadow map (e.g. during lighting pass of deferred shader)?

# Answer
You could apply the bias when rendering the shadow map, instead of when sampling it. I think that's the usual/"standard" approach to shadow map biasing, actually.

BTW, if you want `tan(acos(something))`, it's probably faster to calculate `sqrt(1 - something^2) / something`, which is equivalent (using some trig identities). Generally if you're combining forward and inverse trig functions in an equation, there's another way to write it with no trig functions at all.
> 8 votes

---
Tags: shadows, shadow-mapping
---


# Question
Title: How can I draw a quad in wireframe with modern OpenGL, without rendering the interior bisecting edge?
I want to draw a quad (*not* two triangles). I actually know that triangles are faster, as I answered this question.

But let's say I am building a 3D modeling tool. It makes sense to draw a quad for the user (like Maya and 3D Max do) and not two triangles especially if he is actually working with quads. Is there any other option than using geometry shaders to accomplish this?

I understand that I can draw two triangles and make them co-planer. Unfortunately this will still make the two diagonal points connected, I don't want this. I want a pure quad. I don't want the line connecting the two points, Exactly like what you see in a modeling tool. I am actually rewriting a modeling tool that I wrote few years ago, and can't get the same behavior I got with the older OpenGL.

Here is an image of the tool I am re-writing using modern OpenGL. I used QUADS, so the question is about an alternative that gives this same behaviour especially I am using two pass rendering to render the model and it's outline. That's why I don't want the line separating the two triangles to appear.

# Answer
> 4 votes
You cannot do this with the out-of-the-box functionality provided by your GPU. The GPU *only understands triangles*. No amount of tweaking API configuration, clever use of degenerate triangles, or geometry shaders will change that fact.

If you want to render an collection of outlined quads, as is often done in 3D modeling programs that support quad-based modeling paradigms, you will have to build on top of the basic functionality of your graphics API to do it. This will require, to some extent, modifying or augmenting the data structure you use to store your mesh.

If you are only interested in the basic outline rendering of all quads, and your meshes are all composed of quads that are uniformly constructed from triangles (as is typical), you could simply utilize a rendering pass that rendered line strips using the four vertices of the quad.

```
B----C  fig 1                      B----C  fig 2
|   /|  {ABCD} form a quad for     |    |  {ABCD} form a quad for outline
|  / |  rendering as a pair        |    |  rendering as a line strip of
| /  |  of triangles {ABC} and     |    |  {A, B, C, D, A}.
|/   |  {ACD}.                     |    |
A----D                             A----D

```

If you wanted to do more interesting things, however, such as thicker rendering of lines or saner interaction with the depth buffer, you would probably want to construct a more complex data structure that understands what the *edges* of a quad are, and whether those edges are *interior* edges (like `AC`, above) or exterior edges (the ones you want to render).

You can then render these edges using any existing "thick line" rendering technique suitable for your graphics API (which itself often involves rendering the "lines" as oriented quads-formed-by-triangles, but in this case you'd be working one level of abstraction above that).

Hardware feature edge detection is a topic you'd probably want to look into if the latter options sounds appealing.

# Answer
> 2 votes
It's all just perspective. The hardware only operates on triangles. It renders what you give it to render: If you want to create quads, you simply need to make sure that all four vertices shared by each such pair of triangles, are co-planar. Then any normals-based lighting algorithm running on the hardware is going to render them as a single, uniformly-shaded, seamless quad.

So create the vertices co-planar on the CPU, and the GPU will handle the rest.

P.S. You can use an older version of OpenGL + `GL_QUADS` if you really want to, but you're just going to force the GPU to break them down into triangles, anyway. That's why they deprecated this option.

**EDIT** I'm not sure which version of OpenGL you were previously using, but if any up to 3.0, the problem may be that you had GL\_QUADS support before, and perhaps don't now (as you may be using 3.1 or higher)... if I understand this answer correctly, you can achieve the effect using GL\_LINES with GL\_QUADS. Could that be why you had it working previously? Older OpenGL version? A compatibility context may help you, if you're presently using 3.1+.

# Answer
> 2 votes
Modern OpenGL defines only points, lines or triangles; there are no 4-vertex primitive types, so you can't draw a quad without triangles.

Using a Geometry Shader won't even allow this as the only valid outputs are points, line-strip or triangle-strip; there's no quad output.

You can emulate a quad with a triangle strip (using the 4th vertex to complete the quad), and if you want to draw multiple quads in a single batch, use primitive restart to handle that.

---
Tags: opengl, geometry, geometry-shader
---


# Question
Title: What do I need to implement a side-scrolling screen, like in classic platformer games?
I'm working on a game in Allegro for C++. I'm stumped about how to scroll the screen.

I'm trying to make the screen scroll with the player, as it does in classic side-scroller games such as Super Mario Brothers. What is the approach I should take to implement such behavior?

# Answer
> 3 votes
You need to know two basic things:

* The size of your screen, in whatever units you are most comfortable with (that is, tiles or pixels, or whatever -- as long as all your measurements use the same unit you're basically fine). This is essentially the size of the "viewport" into your level or world.
* The position of the focus point of your view (that is, where in the world your "viewport" is looking at or centered on).

When you go to prepare a frame for rendering, you take the focus point of your viewport, and use that plus the known size of the viewport to figure out where the edges of the viewport *within the world* are. Something like

```
var viewportLeft = focusPoint.X - (viewportSize.Width / 2);
var viewportRight = focusPoint.X + (viewportSize.Width / 2);
var viewportTop = focusPoint.Y + (viewportHeight / 2);
var viewportBottom = focusPoint.Y - (viewportHeight / 2);

```

For example, if you defined your world with tiles, and the whole world was 1000 tiles long, and your focus point was at (500, 40) and your viewport was 200 tiles wide, then `viewportLeft` (the first tiles you see on the screen) would be 400 and `viewportRight` (the last tile you see on the screen) would be 600. Similarly for the vertical dimension.

Then, you simply only render the tiles that are within that viewport, and you have a system that allows you to center your viewport anywhere with the world. To have your viewport follow your player, simply set the focus point to the player's location every frame.

I specifically suggest tracking the focus point distinctly from the player position so that you can have more flexibility. For example, by doing what I said above and setting the focus point to the player position every frame, you may find the camera feels too rigidly attached to the player. You may want to simulate some sort of "elasticity" in how the view follows the player, or implement special behavior when the player is near the edge of the level (as is very typical in side-scrolling games). Divorcing the two also allows you to easily implement those automatic-scrolling levels from Mario games -- simply increment the `X` position of the focus point by a fixed amount every frame, for example.

# Answer
> 0 votes
The basic idea is keeping the player in the center of the screen while moving your level in the opposite direction the player moves. You should know the position of the player, and offset everything in your level by (-1)\*player.pos.xy every frame. For a background, you might want it to seem like it is a bit farer, so you should offset it by (-1)*player.pos.xy*(1/distance). I think it is the most basic approach.

You might want to implement a tile-based level which can be done several ways, I think a perfect tilemap for beginners is just a text file, with a special character for every tile type, for example a text file containing 100\*100 dots would correspond to a 100\*100 tiled level with "air" everywhere. Replace a dot with a _ which your engine would read as a platform that you can stand on, # for an other object, etc.

The basic movement would be like keeping a velocity vector and a position vector in your Player class for example, and every frame update your player like player.pos+=player.velocity. I'd also keep a movespeed, jumpspeed and an acceleration. In my first simple game I did jumping by giving an upward y velocity to the player, and substract a constant gravity value from that velocity, and in simple games I think it suffices.

---
Tags: c++, side-scroller, allegro
---


title: How to work with delta time?

text:
# Question
Title: How to work with delta time?
I've just started using MonoGame (which pretty much seems to be an open implementation of XNA) and I'm trying to figure out on how to work with framerate independant calculations. Usually what I found in all the other game engines / libraries I've used before its some kind of field called "delta time" which I only had to multiply to all the values to make them framerate independant.

I understood the logic between that and I'd like to continue working with delta time values. But as I couldn't find something like that in MonoGame I made some kind of workaround myself. Here's what I did:

```
protected override void Update (GameTime gameTime) {
    deltaTime = gameTime.ElapsedGameTime;
    float delta = deltaTime.Milliseconds;
    delta = delta / 1000;

    //(...)

    //And now I can use delta to apply movement like this:
    position.X += SpeedX*delta;
}

```

Is that a good workaround? Does it have any overhead I might be overlooking at? Is there a pre-built value for what I'm looking for?

Thank you very much

# Answer
There's no need to do anything complicated. The GameTime.ElapsedGameTime property is a TimeSpan representing the amount of elapsed game time since the last update.

Therefore, if you want to measure your game updates in seconds the easiest thing to do is this:

```
    protected override void Update(GameTime gameTime)
    {
        var delta = (float)gameTime.ElapsedGameTime.TotalSeconds;

        //And now I can use delta to apply movement like this:
        position.X += SpeedX * delta;

        base.Update(gameTime);
    }

```

What you're really doing here is declaring that you want to measure your game updates in seconds. So the value of SpeedX is going to represent pixels per second.

I'm not entirely sure why Microsoft decided to use TimeSpans instead of floats. I suppose in theory you could choose to represent your updates in milliseconds, but in practice I don't think that's very common. In any case, once you've decided the unit of measure it's probably best to stick with it and the easiest way to do that is to pass around a single value as a float.
> 8 votes

# Answer
Try something like this:

```
private double lastTime;

protected override void Update (GameTime gameTime) {
    double delta = (gameTime.TotalSeconds - lastTime);
    lastTime = gameTime.TotalSeconds;

    float deltaF = (float)delta;

    position.X += SpeedX*deltaF;
}

```
> -1 votes

---
Tags: xna, monogame
---


# Question
Title: How can I implement jumping in a 2D game using bounding box collision?
**Problem:**
I'm trying to implement basic jumping to my 2D game engine, but have failed several times.
Basically what I've done so far is disabling gravity and using a separate function moving the player upwards. The problem with this is that it looks really bad.

I've checked a lot of threads about this, and found one way that should work.
This is by simply adding another force going upwards against gravity. This force should be greater than gravity, but should decrease until the force of gravity is greater again.

The problem is that I am unable to implement it.

My code is written in Javascript and uses html5 canvas for rendering.
Note! This code is only a part of the whole engine.
As for variables:
c\_objects - array with all objects the player can collide with
player - object literal with position, width, movement speed, velocity, and the velocity multiplier.

*Pseudo-code is good for me, but i'd love an answer in JS.*

**Code:**

```
// physics module collision
function collision(obj_1, obj_2) {
    var collision = Boolean(
        obj_1.x <= (obj_2.x + obj_2.width)
        && obj_2.x <= (obj_1.x + obj_1.width)
        && obj_1.y <= (obj_2.y + obj_2.height)
        && obj_2.y <= (obj_1.y + obj_1.height)
    );

    // return position booleans
    return {
        collision: collision,
    };
};

function movement(x, y) {
    new_pos.x = player.x + x;
    new_pos.y = player.y + y;
    // check collision for all objects in collision array
    var index;
    var collisions = new Array();
    for (index = 0; index < c_objects.length; ++index) {
        var new_collision = engine.collision(new_pos, c_objects[index]);
        collisions[index] = new_collision.collision;
    }
    var it_collides = collisions.indexOf(true) >= 0;
    if (it_collides == false) {
            player.x += x;
            player.y += y;
    }
}

// velocity & gravity module for adding gravity to an object
function gravity(modifier) {
    if (player.gravity == true) {
        var x = 0;
        var y = 0;
        x = 0;
        y = +(player.velocity * modifier);
        engine.movement(x, y);

        if (player.velocity <= 450) {
            player.velocity = (player.velocity * player.velocity_m);
        }
        else {
            velocity = 450;
        }
    }
};

```

# Answer
> 1 votes
The solution was to add another function with higher velocity than the gravity, this velocity decreases over time which results in the player landing again.

Example of this function:

```
var player = {
    speed: 180, // movement speed in pixels per second
    velocity: 400, // sets the falling speed / gravitational pull
    velocity_m: 1.02, // sets the velocity multiplier
    anti_veloctiy: -850,
    anti_veloctiy_m: 0.98,
};
    // jump
    function jump(modifier) {
        if (player.jump == true) {
            // multiply the anti_velocity
            player.anti_veloctiy = player.anti_veloctiy * player.anti_veloctiy_m;
            var x = 0;
            var y = 0;
            x = 0;
            y = (player.anti_veloctiy * modifier);
            engine.movement(x, y);
        }
    },

```

Call this function from your main loop. Then when your user presses space change
the value of player.jump to true.

Only thing left now is to detect if the player has landed and set player jump to false again. This can be done simply by adding some code to the collision, and movement function. We simply add another argument called height\_margin which offsets the collision detection by a few pixels to check if the player is on ground.
The changes are marked with *change*.

```
// physics module collision. height_margin is a extra option usually used for checking if the player is on the ground or not.
collision: function collision(obj_1, obj_2, *height_margin*) {
    var collision = Boolean(
        obj_1.x <= (obj_2.x + obj_2.width)
        && obj_2.x <= (obj_1.x + obj_1.width)
        && obj_1.y <= (obj_2.y + obj_2.height)
        && obj_2.y <= (obj_1.y + obj_1.height + *height_margin*)
    );

    // return position booleans
    return {
        collision: collision,
    };
},

// the movement function takes the change in movement as arguments, and moves the player unless its colliding with something
movement: function movement(x, y, *height_margin*) {
    *// if height_margin is undefined set it to 0.
    height_margin = height_margin || 0;*
    new_pos.x = player.x + x;
    new_pos.y = player.y + y;
    // check collision for all objects in collision array
    var index;
    var collisions = new Array();
    for (index = 0; index < c_objects.length; ++index) {
        var new_collision = engine.collision(new_pos, c_objects[index], *height_margin*);
        collisions[index] = new_collision.collision;
    }
    var it_collides = collisions.indexOf(true) >= 0;
    if (it_collides == false) {
            player.x += x;
            player.y += y;
            // camera follow player
            offsetX -= x;
            offsetY -= y;
    }
    *// return it collides for use in external functions
    return it_collides;*
},

```

Now in the jump function we call the movement function like this: var on\_ground = engine.movement(0, 0, 10);. We then check if the on\_ground is true or false, and if its on\_ground we set player.jump to false.

For actually adding support for jumping we now need to add a keypress handler which sets player.jump to true if var on\_ground = engine.movement(0, 0, 10); is true.

---
Tags: 2d, physics, platformer
---