# Question
Title: Box2D Joints in entity components system
I search a way to have Box2D joints in an entity component system, here is what i found :

**1)** Having the joints in Box2D/Body component as parameters, we have a joint array with an ID by joint and having in the other body component the same joint ID, like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters), Joints => { Joint1 => (joint parameters), others joints... } } // Joint ID = Joint1

Entity2
- Box2D/Body component { Body => (body parameters), Joints => { Joint1 => (joint parameters), others joints... } } // Same joint ID than in Entity1

```

There are 3 problems with this solution :

The first problem is the implementation of this solution, we must manage the joints ID to create joints and to know between which bodies they are connected.

The second problem is the parameters of joint, where are they got ? on the Entity1 or Entity2 ? If they are the same parameters for the joint, there is no problem but if they are differents ?

The third problem is that we can't limit number of bodies to 2 by joint (which is mandatory), a joint can only link 2 bodies, in this solution, nothing prevents to create more than 2 entities with for each a body component with the same joint ID, in this case, how we know the 2 bodies to joint and what to do with others bodies ?

**2)** Same solution than the first solution but by having entities ID instead of Joint ID, like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters), Joints => { Entity2 => (joint parameters), others joints... } }

Entity2
- Box2D/Body component { Body => (body parameters), Joints => { Entity1 => (joint parameters), others joints... } }

```

With this solution, we fix the first problem of the first solution but we have always the two others problems.

**3)** Having a Box2D/Joint component which is inserted in the entities which contains the bodies to joint (we share the same joint component between entities with bodies to joint), like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters) }
- Box2D/Joint component { Joint => (Joint parameters) } // Shared, same as in Entity2

Entity2
- Box2D/Body component { Body => (body parameters) }
- Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity1

```

There are 2 problems with this solution :

The first problem is the same problem than in solution 1 and 2 : We can't limit number of bodies to 2 by joint (which is mandatory), a joint can only link 2 bodies, in this solution, nothing prevents to create more than 2 entities with for each a body component and the shared joint component, in this case, how we know the 2 bodies to joint and what to do with others bodies ?

The second problem is that we can have only one joint by body because entity components system allows to have only one component of same type in an entity.

So we can't put two Joint components in the same entity.

**4)** Having a Box2D/Joint component which is inserted in the entity which contains the first body component to joint and which has an entity ID parameter (this entity contains the second body to joint), like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters) }
- Box2D/Joint component { Entity2 => (Joint parameters) } // Entity2 is the entity ID which contains the other body to joint, the first body being in this entity

Entity2
- Box2D/Body component { Body => (body parameters) }

```

There are exactly the same problems that in the third solution, the only difference is that we can have two differents joints by entity instead of one (by putting one joint component in an entity and another joint component in another entity, each joint referencing to the other entity).

**5)** Having a Box2D/Joint component which take in parameter the two entities ID which contains the bodies to joint, this component can be inserted in any entity, like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters) }

Entity2
- Box2D/Body component { Body => (body parameters) }

Entity3
- Box2D/Joint component { Joint => (Body1 => Entity1, Body2 => Entity2, others parameters of joint) } // Entity1 is the ID of the entity which have the first body to joint and Entity2 is the ID of the entity which have the second body to joint (This component can be in any entity, that doesn't matter)

```

With this solution, we fix the problem of the body limitation by joint, we can only have two bodies per joint, which is correct.

And we are not limited by number of joints per body, because we can create an another Box2D/Joint component, referencing to Entity1 and Entity2 and put this component in a new entity.

The problem of this solution is : What happens if we change the Body1 or Body2 parameter of Joint component at runtime ? We need to add code to sync the Body1/Body2 parameters changes with the real joint object.

**6)** Same as solution 3 but in a better way : Having a Box2D/Joint component Box2D/Joint which is inserted in the entities which contains the bodies to joint, we share the same joint component between these entities BUT the difference is that we create a new entity to link the body component with the joint component, like in this example :

```
Entity1
- Box2D/Body component { Body => (body parameters) }    // Shared, same as in Entity3

Entity2
- Box2D/Body component { Body => (body parameters) }    // Shared, same as in Entity4

Entity3
- Box2D/Body component { Body => (body parameters) }    // Shared, same as in Entity1
- Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity4

Entity4
- Box2D/Body component { Body => (body parameters) }    // Shared, same as in Entity2
- Box2D/Joint component { Joint => (joint parameters) } // Shared, same as in Entity3

```

With this solution, we fix the second problem of the solution 3, because we can create an Entity5 which will have the shared body component of Entity1 and an another joint component so we are no longer limited in the joint number per body.

But the first problem of solution 3 remains, because we can't limit the number of entities which have the shared joint component.

To resolve this problem, we can add a way to limit the number of share of a component, so for the Joint component, we limit the number of share to 2, because we can only joint 2 bodies per joint.

This solution would be perfect because there is no need to add code to sync changes like in the solution 5 because we are notified by the entity components system when components / entities are added to/removed from the system.

But there is a conception problem : How to know easily and quickly between which bodies the joint operates ? Because, there is no way to find easily an entity with a component instance.

My question is : Which solution is the best ? Is there any other better solutions ?

Sorry for the long text and my bad english.

# Answer
*Note: This has turned out to be a long answer. If you just want to see the main idea, scroll to the **Main Answer** heading*

I have recently come across *almost* the same issue. My home-baked framework is more traditional in the sense that components have a few methods, but I think I should still be able to help.

The real issue you seem to be dancing around can be summed up in the question: "Who owns the joint?" My answer to this question was inspired by how CAD programs manage assemblies. (I'm going to use an analogue here so bear with me.)

## Analogue with CAD software

In SolidWorks (for example) parts contain a feature tree:

Image courtesy of cadjunkie

There are a variable numbers of features in the tree, some of the same type (the one above has many fillets), and some are dependent on eachother. Generally, though (there are a few ways to get around this) each part (.sldprt file) has only one solid body. This is how the software is intended to be used. The important part here is that the part owns the body and all its features.

But the problem is, in most cases we design parts to interface and work with other parts. And you might be thinking 'Do machine designers just make all these parts and hope they fit together when they are fabricated?' The answer is a resounding 'No way Jose'. Most designers will create an assembly file such as the one below:

Image courtesy of MathWorks

In assembly mode, solidworks displays a feature tree on the left, but it is not the same as the feature tree in part mode. Notice the entries are parts instead of features. Also notice that there is one extra entry at the end of the list: MateGroup1. A mate group just expands to reveal a list of mates, where each mates specifies a constraint of one part relative to another. Lets take a look at another assembly to see what a mate group might look like:

Image courtesy of CAPUniversity

The feature here shows many different types of mates (concentric mates ensure cylindrical faces are concentric, and coincident, parallel, and distance mates constrain planar faces). The mates between the parts are specified in a completely separate file (the assembly or .sldasm file) for several reasons: (these are just the ones I can come up with)

1. Part feature trees do not become enormous
2. Parts can be moved relative to eachother as they would in real life (by leaving some parts partially unconstrained or specifying multiple configurations for the assembly)
3. Parts can be reused in other assemblies (if parts contained mates and references to other parts then we would have the problem, who owns the mate? What happens if one part is deleted?)
4. Distinct parts in the model map to physically distinct parts (This may seem obvious, but without assemblies this separation between parts would be hard to make! (if you tried to model an assembly as one part))

You might have guessed it already, but here is what I'm getting at: the idea in SolidWorks is that individual parts do not dictate (directly) how they link to other components, you can only specify the properties of a feature, and that feature may or may not be used to mate to another part in an assembly. IMO this should hold for box2d as well. If you have two bodies you should only indicate where the anchor points are on those two bodies, and its the responsibility of something else to get those two anchor points, along with the bodies, and create the joint.

## Main Answer

This is most like solution 5 of your post. Following your format, my solution goes like this:

```
Entity1
- Box2D/Body component { Body => (body parameters) }
- AnchorPoint component {LocVec}

Entity2
- Box2D/Body component { Body => (body parameters) }
- AnchorPoint component {LocVec}

Entity3
- Box2D/Joint component { Joint => (Body1,AnchorPoint1 => Entity1,
                                    Body2,AnchorPoint2 => Entity2,
                                    other parameters of joint) }

```

Where LocVec is the local position of the anchor point relative to the body origin.

You stated one major issue with this approach:

> The problem of this solution is : What happens if we change the Body1 or Body2 parameter of Joint component at runtime ? We need to add code to sync the Body1/Body2 parameters changes with the real joint object.

I think you are referring to moving the anchor point or changing the joint type after the joint has been created. Unfortunately, that's a box2d limitation; you can't change either of those things after the joint has been created. In that case you should destroy the joint, edit the relevant components (e.g. change the anchorpoint component) and recreate it in one fell swoop.

## Other Notes and Example

Really if your are joining two bodies then they likely have some relationship between eachother. And often it would make sense for them to share some common properties. For example, you might have an enemy pair of scissors in the game, where each blade is an entity, and the ScissorEnemy holds the joint component. The enemy scissors might have a health meter, represented by a Health component. Now that you have a third entity that owns the joint, why not have this entity hold the Health component, too? This makes sense, because the health is not really a property of either scissor blade, or even both of them; it belongs to the scissors as a unit. The system would look like this:

```
Blade1
- Box2D/Body component { Body => (body parameters) }
- AnchorPoint component {LocVec}
- Parent component (ScissorEnemy) // A parent component just holds the parent Entity's ID
- ... other components

Blade2
- Box2D/Body component { Body => (body parameters) }
- AnchorPoint component {LocVec}
- Parent component (ScissorEnemy)
- ... other components

ScissorEnemy
- Child component (Blade 1) // An child component just holds the child Entity's ID
- Child component (Blade 2)
- Health component
- ... other components
- Box2D/Joint component { Joint => (other parameters of joint) } //There's no need for the joint component to hold onto references to bodies or anchor points; you can get all that info from the joint or accessing the bodies' of the child components.

```

So here I've introduced a Parent component and an Entity component. The idea is that if one of the blades is involved in a collision or is otherwise damaged, the collision system (or something equivalent) will look for a Health component on the blade. Upon not finding one, The blade (or the system) should look for a parent component, and then check the parent for a health component and subtract health from that. If a scissorEnemy dies it is easy to destroy the scissor enemy, and leave the two blades in play. The health and any other components (maybe a Pathing component) that were only important when the scissorEnemy was alive are destroyed. As a side note, destroying the scissorEnemy does not necessarily destroy the joint, because box2d (and the two bodies) hold onto references to the joint, So you could choose whether or not to destroy the pin.

So far I haven't had any real issues in using 'entity components' like parent component and child component, and I can't see any real issues for an Artemis-like framework. (Though experience has taught me that the devil is in the details, and I have not been through those details yet. So let me know of any roadblocks.)

Assuming you've made good use of recursion, a system like this would have no trouble working with entities who parent entities who parent other entities (as long as there are no circular chains). You could create an entity with a very deep hierarchy to get a lot of sophistication.

I hope this helps!
> 3 votes

---
Tags: box2d, entity-system, entity-component
---


title: Different aspects of games development

text:
# Question
Title: Different aspects of games development
I am and have been quite interested in programming games for quite a while now, however an interesting question I've thought about lately is what do I want to specialize in?

After doing some research I found that game developers/programmers could specialize their skills in quite a few fields such as:

* AI
* Interface design
* Game engine development

There are even some who focus on optimizing network code in the case of online multiplayer games. So I guess my question would be, what other aspects of games programming exist that I could focus on? What would be the ones that are more valued and would increase my chances of being employed in a well paying company?

# Answer
The best way to increase your chances of being employed as a game developer is to get your hands dirty and actually work on the development of some small games.

You say that you are "interested in programming games", which makes me believe that you haven't developed any games, yet. I advice you to stop thinking and start doing. However, the first order of business will not be to specialize in any of those fields. Let me elaborate.

When I interview you for a job, if you tell me you are interested in programming games and your specialty is game AI, I will immediately ask you which games you worked on. If the answer is "none", I don't care about how many books you read or how you believe you are an expert in game AI. You won't be hired, period.

To obtain game development experience in a specific field such as AI, you need to seek out others that are developing games and try to get into their teams. You want specialization, remember? A generalist can develop the whole game, but a specialist needs to work in a team. However, you will again be asked for previous work for someone to trust you with the AI of their game, let's say. Even if you will work free of charge. So, it's a chicken and egg problem right there. Basically, you can't just specialize in anything with no prior game development experience.

Here's what you need to do: you need to forget about specializing and start contributing to the development of a game in any way you can. You can develop a simple game using a game engine such as Unity, or ask someone else developing a game and they will tell you what they need done. Then you'll figure it out and that will give you experience.

Once you have something to show, not only you will have a better chance of joining a team, but also you'll have a better idea on fields that you can specialize in or that you don't like to work on. Trying to make a decision right now without that experience is like marrying someone without getting to know them. You cannot know if you will hate coding game AI unless you have some relevant experience.
> 6 votes

---
Tags: software-engineering, career, jobs
---


title: Reusable top-down collision class

text:
# Question
Title: Reusable top-down collision class
I've recently picked up monogame and am working on a simple top down game to get me started and learn the basics.
I've got the movement and the rotation to follow the mouse sorted out but I'm stuck with the collisions.
What I want to know, basically, are two things:

1. What would be the best way to handle collisions? I know that `Rectangle.Intersects(Rectangle1, Rectangle2)` returns the overlapping rectangle, but, as the movement in top down is on x/y axis I'd like to know where the collision is happening so I can create kind of "wall sliding" where the player doesn't get stuck at the wall.
Is checking the players x/y coordinates against solid objects coordinates, then throw the player to his previous position if he enters the bounds of a solid object really the best approach? What would you suggest?
2. What would be the best way to apply collisions to all of the solids, npc's etc.? I'm currently thinking of creating a `gameObject` class that all of the objects will inherit from and just handle the collisions there.

Thanks for reading and hope that someone can give me some tips.

# Answer
Generally the way most physics engines handle this problem is by **separating the intersecting objects**.

---

So if your objects are represented by rectangles (also known as "Axis Aligned Bounding Boxes"), and they collide on a given frame like so:

---

You would then measure the amount of interpenetration on each axis. Then select the axis with the smallest amount of interpenetration, and separate the objects along that axis.

---

You would then register this as a "collision" and apply appropriate dynamics.

For example, if you want to slide along the wall, you would just zero-out the velocity on the axis you separated on (the X axis, in the above illustration), leaving the velocity on the other axis alone.

But you could also apply friction, or make the objects bounce apart.

---

Here is an excellent, interactive tutorial that shows how to do this in a lot more detail.

Although, if you're going to go far down this path (anything more than simple AABB-collisions), you might want to consider using an existing engine like Velcro Physics (formerly Farseer Physics).

---

Finally, a note on implementation (if you don't go the Farseer route): `Rectangle` uses `int` values, which aren't really appropriate for doing physics in most cases. Consider making your own `AABB` class that uses `float` instead.

Your second question is pretty well answered by my old answer on game architecture over here, so I won't repeat it here.
> 10 votes

# Answer
1: I have been working on a relatively simple top-down action game as well, and after a week(-s?) of struggle, I ended up using a sort of step-by-step approach to collision detection and response. Main reason being that using the shortest amount of interpenetration would in some cases result in "teleportation" to a new position that the moving object was not in previously.

so, when an object wants to move,

1. I create a boundingbox of the object at object's position + moveAmount vector, creating a sort of target bounding box
2. then I check this target bounding box for any intersects with the game objects, tiles, etc. if there are any, I add them to a new list, that holds all potential collisions for current frame
3. if there are no intersections, object moves. but if there's an intersection,
4. I split up the wanted movement into "steps". then I run a loop for the number of steps I have. each step moves the object just for 1 pixel in x and y direction.
5. for each step I check every new projected position for collisions, if nothing, I add step's move vector to the final move vector.
6. if there's a collision (intersects returns true), I compare the previous position (position at previous step) of moving object with the thing it's colliding with.
7. depending on this previous position I halt the movement along the conflicting axis (e.g., if the moving object comes at the colliding object from above, I set y value of move vector to 0 etc.).
8. I repeat this for every consecutive step, adding the adjusted step vectors together to make one final adjusted moveAmount vector that I can safely use for moving the object without any collisions happening.

this approach both ensures that object "bounces" back to correct previous position and it allows for sliding against the walls, objects, whatever.

2: I myself use a static collision class that can be used by whatever. it holds collision detection and vector adjustment methods, that can be called by pretty much anything. whether these methods are called from a "master" game class or by some object subclass doesn't really matter in my case, because the collision class makes a new list every frame for all rectangles the moving object is intersecting with. these rectangles might be from tiles, decorations, NPCs, whatever that has boundaries and is collidable, basically. this means that the bare necessity for all game objects that are collidable is to have boundaries rectangle. if they have that, collision class will handle the rest.

hope this was understandable.
> 1 votes

# Answer
1: I successfully used a technique to solve this: using the speed and position you can discover the collision, and iterate back until the position is very close to the exact collision point.

It's not part of the answer for your first question, but if you have a lot of objects that can collide with each other you should use quadtrees to improve performance. There is a very good tutorial with a lot of examples here.

2: I always recommend Entity-Systems.
> 0 votes

---
Tags: xna, c#, collision-detection, collision-resolution, monogame
---


title: Implementing a 2d Selection Box

text:
# Question
Title: Implementing a 2d Selection Box
I'm in the process of implementing a selection box for my simulation and am having difficulty with something which appears simple. At the moment, I can draw the selection box and accurately select the items under it, *provided* the box was dragged from the top-left-hand corner downwards:

If I start dragging the box from any other point the rectangle doesn't correspond to that of the viewport, as demonstrated by the negative width and height.

Here is my code:

```
// selectionBox is Rectangle

if (mouse.LeftButton == ButtonState.Pressed && prevMouse.LeftButton == ButtonState.Pressed)
{
    if (selecting)
    {
        selectionBox.Width = mouse.X - selectionBox.X;
        selectionBox.Height = mouse.Y - selectionBox.Y;
    }
    else
    {
        selecting = true;
        selectionBox.X = mouse.X;
        selectionBox.Y = mouse.Y;
    }
}

// Code to handle selection finished omitted

// Drawing code
if (selecting)
{
    DrawingHelper.DrawRectangle(selectionBox, Color.Yellow, false);
    DrawingHelper.DrawRectangle(new Rectangle(startPoint.X - 4, startPoint.Y - 4, 8, 8), Color.Red, true);
}

```

How can I adjust the X, Y, Width and Height of my selection box so that X and Y are always the top-left of the selection box no matter where the selection began?

# Answer
For the width and height, you can just get the absolute value of the difference between the mouse and the start of the box.

```
selectionBox.Width = Math.Abs(mouse.X - selectionBox.X);
selectionBox.Height = Math.Abs(mouse.Y - selectionBox.Y);

```

As for the X and Y, you'll need to maintain two values if you want them to always correspond to the top left. Something like `startPoint`.

```
if (selecting)
{
    selectionBox.Width = Math.Abs(mouse.X - startPoint.X);
    selectionBox.Height = Math.Abs(mouse.Y - startPoint.Y);
    //Set the start point to the top left, which is the minimum X and minimum Y
    //Choose between the start point and the current mouse position
    selectionBox.X = Math.Min(startPoint.X, mouse.X);
    selectionBox.Y = Math.Min(startPoint.Y, mouse.Y);
}
else
{
    selecting = true;
    startPoint.X = mouse.X;
    startPoint.Y = mouse.Y;
    selectionBox.X = mouse.X;
    selectionBox.Y = mouse.Y;
}

```

Now when you're done with the box, it'll be as if the user started at the upper left and ended in the bottom right, no matter where they actually started/ended.
> 1 votes

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


# Question
Title: In OpenGL, how to confirm a primitive is rendered properly
I have to confirm that a primitive (say triangle) is rendered properly in opengl.

I can use the glGetError() after a opengl draw calls(glDrawElement/glDrawArrays)

Is it enough to confirm ? Is there any other ways to confirm?

Please let me know.

* Arun AC

# Answer
The answer depends a lot on what you mean by "properly", but overall, you pretty much can't.

Some architectures postpone actual rendering as much as possible, so if some odd error occurs at a very late stage, there's no way to signal an error. However, these cases are very, very rare, and you'll likely get an error while setting up rendering - be sure to check your shader compilation logs, etc.

A lot of things can go wrong, so it's generally a good idea to pepper your code with glerror checks. Alternatively (or additionally) you may want to hit your program with gDEBugger, or whatever AMD is calling it these days.

Now, if by "properly" you mean from a driver/hardware developer point of view, you can always just flush, read back the framebuffer and do a compare with a "golden image"..
> 1 votes

# Answer
Well if you absolutely need NASA space mission perfection, the only way to really be sure it rendered correctly is to do it yourself in software and compare it to the OpenGL output...

That aside, if you can rely on an estimate of the number of pixels then you could investigate using Occlusion Queries to make a guess as to whether or not it rendered properly.
> -1 votes

---
Tags: opengl, rendering, opengl-es
---


# Question
Title: Store voxel type data in XML or Java classes?
So, I want it to be very easy to create all the entities of my game and for other people to come in and do the same. I was thinking I could just let the users/myself create an XML sheet the stores all the properties of each block (Like a Terraria or Minecraft voxel) and add Lua scripts that are referenced in the XML for additional functionality of any of the blocks.

I'm starting to think It would just be easier to let the user create a JAR file full of classes for each block. And then that JAR file could easily be used to get all the blocks. It'd just be interesting to reference all the blocks by a block id without storing all the classes by ID. Or I could give each class a static id. But that's not important.

Okay, so my short question is **what are the pros and cons of storing all the the different types of blocks as classes versus in an XML sheet with Lua for additional functionality?**

**UPDATE:** I will probably go for the only use Lua approach. I found about it just recently and it appears like it could be the best method as of right now for me!

# Answer
> 2 votes
The first thing to do here is consider yourself. You, just like your end users, will want to add functionality to blocks. So, think how you would most like to add the functionality. Most likely, if you find it simple and efficient, then the modders will too.

**JAR Files**

* Pros

+ More possibilities for functionality.
    + Linking in of 3rd party libraries.
    + Lots of tools (potentially debugging).
    + Compiler (can flag errors before you run the application).
    + Possibility to link in 3rd party libraries.
* Cons

+ More complex (less accessible to the layman).
    + Security concerns.
    + System API needs to be clean and well documented.

**LUA**

* Pros

+ Easier for the layman.
    + More control over potential functionality.
    + Less security concerns.
    + Forces mod code to be in a human readable format (users can read and extend mods they like).
    + Can be easily reloaded at runtime.
    + Option to provide an in game command line environment for writing/testing scripts during gameplay.
* Cons

+ Limited extensibility compared to JAR files (fewer possibilities for functionality).
    + No compiler checking for errors.

**Note**

If you add functionality by writing straight to your code base then you may simply want to consider just going open source. If you do go open source then user's won't be able to pick and choose the mods they want or share them as easily, but you may also find that the community is willing to help further develop your game in more ways than you currently have in mind.

# Answer
> 0 votes
First of all, your focus should probably be elsewhere. Have you ever made a game that attracted just a modest user base before? If not simply making a game that people want to play in the first place is a plenty steep goal.

Supporting good moddability is hard and time consuming. It takes some experience that you probably don't have and require a more frameworkish structure.

For all the good things there is to say about planning ahead and doing things right from the beginning, you easily risk such concerns getting in the way of actually making a game.

Go with the easiest solution. For all the cases where that leads you to go back and redesign there will be many more where you avoided needless extra work. With time you should learn to spot the cases where a more elaborate approach is required.

The Java classes offer by far the easiest option to implement, and while some XML files may be easier to edit you have to offer some pretty elaborate bindings in order to make that LUA script anywhere near as flexible as an option for modifying the native Java code.

---
Tags: java, lua, voxels, xml
---


title: What type of server should I use?

text:
# Question
Title: What type of server should I use?
I am planning on making a game in c#. It will be a turn based, space exploration game. I want the turns of the different players to be able to happen at the same time though. I have been researching for what type of server to use for hours and I cannot find one that works the way I want it to.

I have heard of listening servers, dedicated servers, and peer to peer. -the peer to peer I have heard are almost gone, and obsolete for the most part -dedicated servers are expensive, in terms of resources (lots of data) -and there are listening servers which seem to be the best option.

Also is there a way for the server to run under the same exe as the client? like how minecraft does it? where each game is internally run in a server though 2 windows do not appear?

EDIT:

I know that I need to create my own server, and I am pretty sure I can do it in c# ( i made a small client and server that doesn't do much but it works) but I want to know what structure of server I should create

# Answer
> 2 votes
I would recommend you to allow both, because it allows your players to have both of two worlds. They can run it on servers in datacenters to provide a permanent meeting-point for their social circle. But they could also open an ad-hoc server from their client.

You could easily do this by implementing the server in a DLL which is used by both the client when it opens a listenserver and by your much more lightweight dedicated server executable.

Another decision you didn't consider is letting the community host their own servers vs. hosting a server for them. When you host your own servers you have these advantages and disadvantages:

Pro:

* Most community server hosters will be hobbyists, but as a professional with commercial interests you can provide a much more reliable service (hopefully)
* It solves the piracy problem in a very elegant way, because you have an excuse to give every buyer an own account with password and ban anyone who shares their account with someone else
* Releasing updates become easier, because you just have to update your own servers
* You can globally ban any cheaters or other misbehaving players.
* You can provide authoritative global highscores and statistics. This would be impossible when the players host their own servers, because it would be impossible to prevent them from cheating when they control the hardware.
* Players are unable to hack and mod the server, preventing them from bastardizing your game

Contra:

* You have to pay the bills for the hardware
* You have to pay the admins who keep it running
* You have to pay the mods who ban the cheaters and abusers (or hand-pick some volunteers from the community which will be a source of endless drama)
* Players are unable to hack and mod the server, preventing them from adding free value to your game

# Answer
> 0 votes
To start off, yes, it's definitely possible to create the server and client in 1 executable. For this, take a look at threads. A 'thread' is a place where code is ran asynchronous.

Secondly, you are probably best off with a dedicated server in C#. If you make a game in C#, it's a good idea to make the server in C#. If I were you I would not worry about the resources of the server, as a turn-based game doesn't use a lot of data at all. Unless your game becomes *really* big, you will be fine with a tcp/ip or udp server in C#.

A little tip on C# servers: use the Lidgren library. It saves you alot of time, as the library will create a high-performance udp server for you with a few lines of code.

---
Tags: c#, server, client-server, client
---


# Question
Title: What makes a path finding heuristic Monotonic vs. Non-monotonic?
I am currently working on an algorithm that solves a path through the maze. So far I have implemented a Manhattan and Pythagorean Heuristic. I was wondering what makes a heuristic monotonic and how would one go about making a heuristic non-monotonic.

# Answer
A heuristic \\$h\\$ is monotonic when, in addition to being admissible (meaning the estimate is always equal or lesser to the actual minimum cost) the heuristic satisfies the relation:

$$h(x) \<= d(x,y) + h(y)$$

fo all adjacent nodes \\$x\\$ and \\$y\\$, where \\$d(x,y)\\$ is the distance from node \\$x\\$ to node \\$y\\$.

More can be found here.

**Update**: (thanks to ilmari-karonen):
An even better link here:

*Consistent* (aka \*monotonic) heuristics are usually preferred because as each node is reached, consistency guarantees that the path length to that point is equal to the minimal path-length from the start node. This means that a *closed-set* can be used to avoid expanding nodes more than once.

The most common use of an admissible but not consistent heuristic is when using a **bidirectional** A\*; however in this instance each branch is self-consistent, and so it suffices to expand each node once from each branch.
> 2 votes

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


# Question
Title: Sprite sheet textures picking up edges of adjacent texture
I have a custom sprite routine (openGL 2.0) which uses a simple sprite sheet (my textures are arranged horizontally next to each other).

So, for example, here is a test sprite sheet with 2 simple textures:

Now, what I do when creating my openGL sprite object is specify the total number of frames in its atlas and when drawing, specify which frame I want to draw.

It then works out where to grab the texture from by:

Dividing the required frame number by the total number of frames (to get the left coordinate)

And then diving 1 by the total number of frames and adding the result to the left hand coordinate calculated above.

This does seem to work but sometimes I get problems. Say for example, I want to draw the X below and I get...........

I've heard about putting a 'padding' of 1 px between each texture but could someone explain exactly how this works? I mean if I do this it will surely throw off the calculations for getting the texture.

If I simple include the padding in texture picked up (so the sprite is drawn with a blank border), then surely this will cause problem with collision detection? (ie sprites may appear to collide when using bounding boxes when the transparent parts collide).

Would appreciate if someone could explain.

# Answer
The problem with using texture atlases and adjacent texels leaking has to do with the way linear texture filtering works.

For any point in the texture that is not sampled exactly at the center of a texel, linear sampling will sample 4 adjacent texels and compute the value at the location you asked as the weighted (based on distance from the sample point) average of all 4 samples.

Here's a nice visualization of the problem:

Since you cannot use something like `GL_CLAMP_TO_EDGE` in a texture atlas, you need to create border texels around the edge of each texture. These border texels will prevent neighboring samples from completely different textures in the atlas from altering the image through weighted interpolation explained above.

Note that when you use anisotropic filtering, you may need to increase the width of the border. This is because anisotropic filtering will increase the size of the sample neighborhood at extreme angles.

To illustrate what I mean by using a border around the edge of each texture, consider the various wrap modes available in OpenGL. Pay special attention to `CLAMP TO EDGE`.

Despite there being a mode called "Clamp to Border", that is actually not what we are interested in. That mode lets you define a single color to use as a border around your texture for any texture coordinates that fall outside of the normalized \[0.0-1.0\] range.

What we want is to replicate the behavior of `CLAMP_TO_EDGE`, where any texture coordinate outside the proper range for the (sub-)texture receives the value of the last texel center in the direction it was out of bounds in. Since you have almost complete control over the texture coordinates in an atlas system, the only scenario in which (effective) texture coordinates might refer to a location outside of your texture are during the weighted average step of texture filtering.

We know that `GL_LINEAR` will sample the 4 nearest neighbors as seen in the diagram above, so we only need a 1-texel border. You may need a wider texel border if you use anisotropic filtering, because it increases the sample neighborhood size under certain conditions.

Here's an example of a texture that illustrates the border more clearly, though for your purposes you can make the border 1 texel or 2 texels wide.

(NOTE: The border I am referring to is not the black around all four edges of the image, but the area where the checkerboard pattern stops repeating regularly)

In case you were wondering, here is why I keep bringing up anisotropic filtering. It changes the shape of the sample neighborhood based on angle and can cause more than 4 texels to be used for filtering:

http://www.arcsynthesis.org/gltut/Texturing/ParallelogramDiag.svg

The larger the degree of anisotropy you use, the more likely you will have to deal with sample neighborhoods containing more than 4 texels. A 2 texel border should be adequate for most anisotropic filtering situations.

Last but not least, here is how a packed texture atlas would be built that would replicate `GL_CLAMP_TO_EDGE` behavior in the presence of a `GL_LINEAR` texture filter:

<sub>(*Subtract 1 from X and Y in the black coordinates, I did not proof read the image before posting.*)</sub>

Due to border storage, storing 4 256x256 textures in this atlas requires a texture with dimensions 516x516. The borders are color coded based on how you would fill them with texel data during atlas creation:

* Red = Replace with texel directly below
* Yellow = Replace with texel directly above
* Green = Replace with texel directly to the left
* Blue = Replace with texel directly to the right

Effectively in this packed example, each texture in the atlas uses a 258x258 region of the atlas, but you will generate texture coordinates that map to the visible 256x256 region. The bordering texels are only ever used when texture filtering is done at the edges of textures in the atlas, and the way they are designed mimics `GL_CLAMP_TO_EDGE` behavior.

In case you were wondering, you can implement other types of wrap modes using a similar approach -- `GL_REPEAT` can be implemented by exchanging the left/right and top/bottom border texels in the texture atlas and a little bit of clever texture coordinate math in a shader. That is a little more complicated, so do not worry about that for now. Since you're only dealing with sprite sheets limit yourself to `GL_CLAMP_TO_EDGE` :)
> 16 votes

---
Tags: textures, opengl-es, opengl-es2, spritesheet, texture-atlas
---


# Question
Title: How to implement pathfinding in this situation
So I'm creating a game for android using the libgdx library. I render the map from a tmx file and in it all the water tiles have the property of blocked. My player(a sprite) moves to where I clicked/tapped.

My problem is that I am unsure as to how to implement pathfinding. I can get in the layer with the tiles that which have the blocked property but I'm not sure as to how to stop my player from moving through them. I am using the tweenengine to move the player.

I was thinking that perhaps the code would create waypoints for the tween movement from a path finding code but again I'm not sure as to how to implement it.

I looked at A\* and all the examples I was looking at were using rectangles and my player doesnt move in a uniform way(1 tile per move). So I cant really assign it values (10 for vertical/horizontal, 14 for diagonal).

If I have said anything that is not true then please correct me

# Answer
> 2 votes
I'm going to assume even if you're not moving by squares on the map that you still have them.

With this in mind the solution becomes the same as if your character did move along the squares. Use a pathfinding algorithm to find where the character needs to head. Then find the nodes where the slope of the path changes and these nodes become waypoints. You can then tween between the waypoints.

For instance, say your character is at (0,0) on the map and your pathfinding algorithm starts with a slope of 3/4 (move 3 blocks up and 4 to the right) to point (4,3) then changes to a slope of 0 to point (4,13) then changes again to slope 1/6 to point (10, 14).

You then go through and find the points listed since the slopes change and then tween as so:

```
(0,0) to (4,3)
(4,3) to (4,13)
(4,13) to (10,14)

```

# Answer
> 1 votes
Although it is written in C#, Eric Lippert presented an excellent introduction to the A\* algorithm here. Implementing A\* in any other C-like language should be straightforward from Eric's description and analysis.

Eric's algorithm is for a square grid, and illustrates usage of the **.NET** framework for understandable reasons.

An **ALT bidirectional implementation** of A\* (also in C#) is available in my Open Source (MIT) hex-grid library here for any who require a more efficient implementation. (It calculates shortest paths on a 750 x 460 hexgrid terrain map in under 5ms on my i7 laptop.)

---
Tags: java, 2d, sprites, libgdx, path-finding
---


title: OpenGL - Z- Buffer translucency

text:
# Question
Title: OpenGL - Z- Buffer translucency
So lately I wanted to use the Z buffer in opengl to order my 2D sprites in my program. Now I didn;t relaize that if you use the Z buffer then you cant blend these sprites. And some of these sprites are translucent.

My question is what can I do to fix this, by still using the handly Z buffer?

# Answer
You don't, at least not for writes. Z-buffer writing/ordering and transparency is not really something you can do easily. Most techniques require significantly more work than you're likely prepared for, like using depth peeling.

Sort your objects. Typically you would sort opaque (or alpha cutout) objects front-to-back with Z-buffering enabled, then do a second pass of any translucent objects sorted back-to-front with Z-buffer writes disabled (but Z-testing still enabled!). Doing the opaque front-to-back typically helps performance when you have a lot of overdraw (overlapping objects/sprites) by avoiding drawing the same pixel fragment more than once.

The problem with Z-buffering is that there is no way for the Z-buffer to both know what the closest opaque (occluding) pixel is (in a hardware-friendly way, at least), and even if it could, *transparency order matters* for some blending modes. If you blend A onto B you will get a different color than if you blend B onto A in many common blending modes. You *must* sort the objects to get the correct output, with or without Z-buffering issues. You also need to draw the opaque objects first to blend over them.

Larger 3D engines typically handle this by having multiple *render queues* that sort and batch objects separately. Opaque objects can end up in one queue with Z-buffering on, and maybe with front-to-back sorting on. Translucent order-dependent objects end up in a different queue with Z writes off but reads on (you don't want to blend in translucent objects that are behind the opaque scenery!). Translucent order-independent objects (additive-blending particles most often) can be put in yet another queue with no sorting at all, Z-writes off (Z-reads still on). You can also have multiple render queues for things like UI overlays and such.
> 7 votes

---
Tags: opengl, 2d, transparency
---


# Question
Title: When several classes need to access the same data, where should the data be declared?
I have a basic 2D tower defense game in C++.

Each map is a separate class which inherits from GameState. The map delegates the logic and drawing code to each object in the game and sets data such as the map path. In pseudo-code the logic section might look something like this:

```
update():
  for each creep in creeps:
    creep.update()
  for each tower in towers:
    tower.update()
  for each missile in missiles:
    missile.update()

```

The objects (creeps, towers and missiles) are stored in vector-of-pointers. The towers must have access to the vector-of-creeps and the vector-of-missiles to create new missiles and identify targets.

The question is: where do I declare the vectors? Should they be members of the Map class, and passed as arguments to the tower.update() function? Or declared globally? Or are there other solutions I'm missing entirely?

When several classes need to access the same data, where should the data be declared?

# Answer
When you need a single instance of a class throughout your program, we call that class a **service**. There are several standard methods of implementing services in programs:

* **Global variables**. These are the easiest to implement, but the worst design. If you use too many global variables, you will quickly find yourself writing modules that rely on each other too much (strong-coupling), making the flow of logic very difficult to follow. Global variables are not multithreading-friendly. Global variables make tracking the lifetime of objects more difficult, and clutter the namespace. They are, however, the most performant option, so there are times when they can and should be used, but use them spareingly.
* **Singletons**. About 10-15 years ago, singletons were *the* big design-pattern to know about. However, nowadays they are looked down upon. They are much easier to multi-thread, but you must limit their use to one thread at a time, which is not always what you want. Tracking lifetimes is just as difficult as with global variables.
A typical singleton class will look something like this:

```
class MyClass
{
private:
    static MyClass* _instance;
    MyClass() {} //private constructor

public:
    static MyClass* getInstance();
    void method();
};

...

MyClass* MyClass::_instance = NULL;
MyClass* MyClass::getInstance()
{
    if(_instance == NULL)
        _instance = new MyClass(); //Not thread-safe version
    return _instance;

    //Note that _instance is *never* deleted -
    //it exists for the entire lifetime of the program!
}

```
* **Dependency Injection (DI)**. This just means passing the service in as a constructor parameter. A service must already exist in order to pass it into a class, so there's no way for two services to rely on each other; in 98% of the cases, this is what you want *(and for the other 2%, you can always create a `setWhatever()` method and pass in the service later)*. Because of this, DI doesn't have the same coupling problems as the other options. It can be used with multithreading, because each thread can simply have its own instance of every service (and share only those it absolutely needs to). It also makes code unit-testable, if you care about that.

The problem with dependency injection is that it takes up more memory; now every instance of a class needs references to every service it will use. Also, it gets annoying to use when you have too many services; there are frameworks that mitigate this problem in other languages, but because of C++'s lack of reflection, DI frameworks in C++ tend to be even more work than just doing it manually.

```
//Example of dependency injection
class Tower
{
private:
    MissileCreationService* _missileCreator;
    CreepLocatorService* _creepLocator;
public:
    Tower(MissileCreationService*, CreepLocatorService*);
}

//In order to create a tower, the creating-class must also have instances of
// MissileCreationService and CreepLocatorService; thus, if we want to
// add a new service to the Tower constructor, we must add it to the
// constructor of every class which creates a Tower as well!
//This is not a problem in languages like C# and Java, where you can use
// a framework to create an instance and inject automatically.

```

*See this page (from the documentation for Ninject, a C# DI framework) for another example.*

Dependency injection is the usual solution for this problem, and is the answer you will see most highly upvoted to questions like this on StackOverflow.com. DI is a type of Inversion of Control (IoC).
* **Service Locator**. Basically, just a class that holds an instance of every service. You can do it using reflection, or you can just add a new instance to it every time you want to create a new service. You still have the same problem as before - *How do classes access this locator?* \- which can be solved in any of the above ways, but now you only need to do it for your `ServiceLocator` class, rather than for dozens of services. This method is also unit-testable, if you care about that sort of thing.

Service Locators are another form of Inversion of Control (IoC). Usually, frameworks that do automatic dependency injection will also have a service locator.

XNA *(Microsoft's C# game programming framework)* includes a service locator; to learn more about it, see this answer.

---

By the way, IMHO the towers should not know about the creeps. Unless you are planning on simply looping over the list of creeps for every tower, you'll probably want to implement some nontrivial space partitioning; and that sort of logic doesn't belong in the towers class.
> 53 votes

# Answer
I personally would use polymorphism here. Why have a `missile` vector, a `tower` vector, and a `creep` vector..when they all call the same function; `update`? Why not have a vector of pointers to some base class `Entity` or `GameObject`?

I find a good way to design is to think 'does this make sense in terms of ownership'? Obviously a tower owns a way to update itself, but does a map own all the objects on it? If you go for global, are you saying that nothing owns the towers and creeps? Global is usually a bad solution - it promotes bad design patterns, yet it is much easier to work with. Consider weighing up 'do I want to finish this?' and 'do I want something that I can reuse'?

One way around this is some form of messaging system. The `tower` may send a message to the `map` (which it has access to, perhaps a reference to its owner?) that it hit a `creep`, and the `map` then tells the `creep` it's been hit. This is very clean and segregates data.

Another way is to just search the map itself for what it wants. However, there may be issues with update order here.
> 5 votes

# Answer
This is a case in which strict object oriented programming (OOP) breaks down.

According to the principles of OOP, you should group data with related behavior using classes. But **you have a behavior (targeting) that needs data that are not related to each other (towers and creeps).** In this situation, many programmers will try to associate the behavior with part of the data it needs (e.g. towers handle targeting, but don't know about creeps), but there's another option: **don't group the behavior with the data.**

Instead of making the targeting behavior a method of the tower class, make it a free function which accepts towers and creeps as arguments. This might require making more of the members that are left in the tower and creep classes public, and *that's OK.* Data hiding is useful, but it's a means, not an end in itself, and you shouldn't be a slave to it. Besides, private members aren't the only way to control access to data — if data isn't passed into a function and it isn't global, it's effectively hidden from that function. If using this technique lets you avoid global data, you might actually be *improving* encapsulation.

An extreme example of this approach is the entity system architecture.
> 0 votes

---
Tags: c++, architecture, game-loop
---


title: JMonkeyEngine in Eclipse

text:
# Question
Title: JMonkeyEngine in Eclipse
I wanted to try the JMonkey engine, so I downloaded the JMonkey sdk, but I don't want to work in the JME IDE, I would rather like to work with Eclipse, since I already started a game project there, and I only want to replace the game engine(the code is modular, so i can do that) form pure LWJGL to JME. I found this tutorial: http://hub.jmonkeyengine.org/wiki/doku.php/jme3:setting\_up\_jme3\_in\_eclipse But that won't work, when I add the jar-s then there is no com.jme3.app.SimpleApplication anywhere there, as the tutorial suggests. Also where are the correct native files? I googled, but I can't find any example projects of Eclipse, or any decent explanations how to set up JME in Eclipse properly.

# Answer
> 2 votes
Problem solved, I downloaded an older version of JME by accident. I now downloaded the proper version, and I did exactly as the tutorial said, and it worked. Sorry for bothering.

---
Tags: java, 3d, eclipse
---


# Question
Title: In A star, do I use the sum or the edge cost?
When you add a new node to the closed list, you need to check all the adjacent nodes. If you find any adjacent nodes on the open list, you have to check if G would be lower if you went through the current node to get there.

My questions is, when checking if the G would be lower if you went through the current node, do you add up from the last node or start from 0?

Say you're using G = 14 for diagonal and G = 10 for horizontal. Last one on the closed list's G was 20. Your current node is one block lower from the last one on the closed list, and has an adjacent one that's on the open list with G = 34. Are you supposed to check if the G would be lower if you went through your current node by doing 20 + 10 + 14 = 44, 44 !\< 34. Or, are you supposed to start from 0, so 0 + 10 + 14 = 24, 24 \< 34?

I'm pretty sure it's the latter as with the former, the number is never going to be lower. But if it's the latter, wouldn't the number be lower every single time after a certain point?

# Answer
TL;DR : Yes, the adjacent nodes inherit the G cost from the current node PLUS the directional cost to the adjacent node.

---

When you check adjacent nodes, do you not already calculate the costs? The nodes you add to the open list should have some costs calculated and assigned to them. When the adjacent is already in the open list( aka already had its turn as "adjacent node") you compare those values with the values that are calculated from the current path. If the new one is cheaper you reassign the parent of the node in the open list to the current node.

Basically your "current node" is the node with the lowest costs in your open list/tree. And each time a tile/node has been processed it will be put in the closed list and the next one with the lowest costs will be processed. It keeps going until the goal has been reached or no solution is found. You are checking the adjacent nodes, calculate their costs and set their parent. So when you come across an adjacent node that is also already in the open list/tree the costs from that node is already calculated by a different potential path. That's when you compare values and see which path is superior and switch their parent ( or not if the other path deems to be faster ).

At the end you trace back through each parent node which eventually leads back to your starting point.

Note: A\* can be achieved in different ways. I am assuming you are using some sort of uniform grid and iterate trough your tiles.

If you look at the third panel you can see that we check the adjacent tiles of the tile right from the starting point. The already checked tile above it ( top right adjacent from the start) has already a calculated cost. This cost was assigned to it when it was checked from the start ( note that I left H costs out for simplicity ). It appears that the new calculated cost actually takes 20 G to walk from the start point to this adjacent tile. But since the existing node in the open list has a G value of 10, which is lower, we let this one be. If the outcome were reversed where the new cost is cheaper we would set the parent of this adjacent tile in the open list to the current node and set the G value to the value that deems to be cheaper.

The cost of each adjacent node is :

```
currAdjNode.G = currentNode.G + directionCost; // 14 or 10 in your case
currAdjNode.H = //your manhatten distance function from currAdjNode;
currAdjNode.F = currAdjNode.G + currAdjNode.H;

```

If you keep iterating through each adjacent node this way the costs will logically add up. And thus also give you an easy solution for comparing open nodes with new nodes and determine whether or not to swap parents.
> 1 votes

---
Tags: path-finding
---


title: Server List for a game

text:
# Question
Title: Server List for a game
I'm making a c++ multiplayer game, and I'm trying to implement a server list, where everyone can host his own server. But I don't know how to start, I've google'd for a while and I didn't find anything about this. I tried to search for a master server specially designed to handle with the server list, so if I refresh it, it will ask the master how many servers it has, and tell the client the servers' informations, and I don't have any idea on how I could make it.

Could you just show me an example, or tell me how could I begin?

Any help is really appreciated.

# Answer
Building a master server so people can host their own dedicated servers is not a hard task. Once you have setup a tcp/ip or udp server / client structure, you will need 2 basic things:

**Heartbeat system**: The idea of a heartbeat system is easy. A dedicated server hosted by players sends a heartbeat (just a packet with information) to the master server every x seconds, with basic information about the server (server ip, server port, server version, current amount of players, maximum amount of players, server-side variables such as game speed, game mode etc). The server will save this information in the server structure, for example a List of Server(class) objects.

**Request list of servers**: Once a player opens the client, it will send a packet to the server containing a command to request the server list. The master server then sends back a serialized list of all the servers that have sent a heartbeat in the last x seconds. This way you always have a up-to date list of all the player-hosted servers.

Also you should have a timer which deletes servers from the master server which have not sent a heartbeat for for example a minute.
> 4 votes

# Answer
Unless you're intending your players to all share a LAN or VPN, trying to implement a purely peer to peer game is very difficult; there are just too many firewalls and other obstacles to transparent routing. Plan to keep a public server with a stable IP address as the hub for all communications, and make any idea of a private server a virtual entity mediated by that hub.
> 0 votes

---
Tags: c++, multiplayer
---


# Question
Title: Decomposing a collision grid into a set of boxes
I'm looking for a *decent* algorithm to decompose a collision grid (e.g. `bool[w,h]`)...

...into a non-overlapping set of boxes (e.g. `List<Rectangle>`).

The solution does not have to be the *best* all the time, as long as it is simplified enough (otherwise I would just create one box per tile).

# Answer
> 2 votes
Perhaps you could check if there is a group of 4 tiles. For example the left top tile group is invalid because you have a passible tile. Then you check whether if there is a possible group in the vertical or horizontal alignment and keep resizing the box until no solid tile is found. In case there is a group of 4 you check in either direction whether 2 of those tiles can form another 4. If not then you stop looking in that direction and keep the rectangle as is.

For each grouped tileset you also mark them as checked to make sure your algorithm does not check them again.

So in sequence:

etc. Simply go from top left to bottom right one tile at a time. If its solid check the algorithm. If the tile is already checked we skip those till we reach the last tile. As long the rectangle can grow downwards and to the right equal in size you should cover it.

# Answer
> 1 votes
A simple algorithm I could think of (it won't optimize the distribution/coverage too well, but it will):

1. Have some kind of bitmask/array to mark boxes as "done".
2. From left to right top to bottom, pick the first box not marked as done.
3. From there on walk to the right as long as the boxes are filled and not yet "done".
4. Once you hit the end of the map or some not occupied box, go down as long as these rows are identical (i.e. same boxes filled).
5. Mark all boxes selected that way as "done" and store the rectangle.
6. Repeat starting with the step 2 till all boxes are "done".

This will essentially get you the exact same structure you've outlined in your image, with the slight difference that the bright green rectangle will be shorter by two boxes (as the blue and dark green ones take the first/last box).

---
Tags: algorithm, geometry
---


# Question
Title: One index buffer with multiple vertex buffers?
I noticed that there's `IASetVertexBuffers()` to set multiple vertex buffers at once but there's only `IASetIndexBuffer()` to set one index buffer. So I assume that I can simultaneously only have **one** index buffer set but I can have **multiple** vertex buffers set at the same time.

1. Is that correct?
2. How do I use index buffer with multiple vertex buffers? I.e. what indices do I provide to use more than one vertex buffer and how do I know what buffer conrete indices refer to?

Or is this used **only** in the case when instead of interleaved vertex data: (Pos, Normal, Pos, Normal, Pos, Normal) I provide the data in multiple buffers: (Pos, Pos, Pos) (Normal, Normal, Normal) and conrete indices refer to the same vertices in each buffer?

# Answer
> 8 votes
Multiple vertex buffers would be used when your data is non-interleaved. If your data was interleaved then you'd put it all in one vertex buffer. (You can also have vertex data partially interleaved and partially not. For instance, all the positions could be in one buffer, and all the other attributes - normals, UVs, etc. - interleaved in another buffer.)

Regardless of the vertex layout, there's only one index buffer bound at a time, and the same index is used for all vertex buffers. If the number 47 is found in the index buffer then the GPU will load the 47th element of the first vertex buffer, the 47th element of the second vertex buffer, etc. The data from all bound vertex buffers will be available as inputs to the vertex shader.

# Answer
> 4 votes
This question comes up a lot in relation to the .obj model format, and the answer is that yes: you can only have a single index buffer, but it works with both interleaved and non-interleaved data.

For the non-interleaved case I'm assuming that you're thinking of a case where the data is fully de-duplicated (again, like .obj). What's important to realise here is that this kind of case may be optimized for *storage*, but it's not optimized for *rendering*.

The solution is to re-introduce duplicate vertex attributes so that the single index buffer is capable of handling all streams. Roundabout this time many people say "surely that's less efficient because it uses more memory?" The answer to that one is "no".

Saving memory is not the be-all and end-all of performance. Using an index buffer gives other advantages too, and both of these are more important for performance than saving memory:

* Your hardware's vertex cache will now work, meaning that recently transformed vertices will not need to be re-transformed if they're shared, and:
* An entire model can be drawn in a single draw call rather than having to split it into multiple draw calls.

It *may* be the case that future hardware will allow for multiple index buffers, or an extra level of index indirection, but there's no sign of that on the horizon. The current approaches work more than well enough, and a little extra memory usage is a fair tradeoff for a *lot* of extra performance.

# Answer
> 0 votes
Look at my answer on a similar question on stack overflow here for interleaving and duplicate vertex attribute from an obj file.

Also, the way to use non interleaved vertex attributes ( but with matching indices ) is by tweaking the input layout.

The `InputSlot` attribute of D3D11\_INPUT\_ELEMENT\_DESC provide to CreateInputLayout is what you are seeking for.

---
Tags: c++, directx11, index-buffer, vertex-buffer
---


# Question
Title: How to cancel out simultaneous collisions in libGosu?
I am working on an Asteroids remake. When the player's bullets hit a large meteor, it should break apart into 2 smaller meteors. This works when the player is only firing one bullet, but when the player's weapon is upgraded, shooting multiple bullets, sometimes two bullets hit the same meteor at the same time, causing it to break into 4 smaller meteors, not 2 as intended.

Is there a way to cancel out one of the collisions when there are two simultaneous collisions - or a way to omit the creation of the unwanted extra meteors when two bullets hit the same meteor at the same time?

Here is how I have the collision detection set up currently:

```
Bullet.each_collision(Meteor1) do |bullet, meteor|
  Explosion.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  meteor.destroy
  bullet.destroy
  @score += 100
  Sound["media/audio/explosion.ogg"].play(0.2)
end

```

Following are screenshots demonstrating the situation:

In the first two images (above) the player fires one bullet at a time, the large meteor breaks into two smaller meteors, and the score increases by 100.

In the last two images, the player fires three bullets at a time, the large meteor breaks apart into four smaller meteors, and the score increases by 200, due to a simultaneous collision.

# Answer
> 1 votes
Just add a small delay that keeps the meteors from splitting apart for an instant after it has just been split.

# Answer
> 1 votes
You need to ensure that the block is ignored if the meteor has already been destroyed:

```
require 'set'

destroyed_meteors = Set.new
Bullet.each_collision(Meteor1) do |bullet, meteor|
  # Prevent multiple destructions of a single meteor
  next if destroyed_meteors.include? meteor
  destroyed_meteors << meteor

  Explosion.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  Meteor2.create(:x => meteor.x, :y => meteor.y)
  meteor.destroy
  bullet.destroy
  @score += 100
  Sound["media/audio/explosion.ogg"].play(0.2)
end

```

---
Tags: 2d, collision-detection, ruby, libgosu, chingu
---


# Question
Title: SharpDx how to detect if Mouse Button is pressed?
I'm wondering how it's possible to detect if a mousebutton is pressed or released.

```
var di = new DirectInput();
_mouse = new Mouse(di);
_mouse.Acquire();
_mouseState = _mouse.GetCurrentState()

```

All I can access is now the X Y and Z Axis of the Mouse and the Boolean array Buttons. Any Ideas?

# Answer
Ok so the error wasn't if it's pressed or not. These things were already right. My error was the MousePosition, it seems like sharpDx mouseposition is a bit different. So the Solution was instead of using the SharpDX mouse position X Y state, to use System.Windows.Forms.Cursor.Position.X Y thats all
> 0 votes

# Answer
The SharpDX `MouseState.Buttons` property is what you're after. As you've found, you can get access to the MouseState with `GetCurrentState()`. You can reference the order of the buttons you'll find in the `MouseState.Buttons` array here. (I'm pretty sure that "None" is not stored in the array, so start with "Left").

So, if you wanted to know if the left mouse button was pressed you'd check to see if its position in the array was set to `True`. Like so:

```
if(_mouseState.Buttons[0] == True)
    //Left button pressed
if(_mouseState.Buttons[2] == True)
    //Right button pressed

```

That'll tell you when the buttons are down. But how do you know exactly when the button was pressed? Well, you need to keep track of the state of the mouse separately. Keep your own copy of the Buttons array. Every frame, copy the current `MouseState.Buttons` array into another array called something like `PreviousButtonsState`. Now each frame you can do a check and find out if a button was *just* pressed. This allows you to respond only once to clicks. You can also trigger events for when the button is pressed, or when the button is released. For example:

```
if(_mouseState.Buttons[0] == True && PreviousButtonsState[0] == False)
    //Left button was just pressed!
    OnMouseDown(0);
if(_mouseState.Buttons[2] == True && PreviousButtonsState[2] == False)
    //Right button was just pressed!
    OnMouseDown(2);
if(_mouseState.Buttons[0] == False && PreviousButtonsState[0] == True)
    //Left button was just released!
    OnMouseUp(0);

....

OnMouseDown(int button) {
    switch(button){
    case 0:
        //Do something when left button is pressed
        break;
    case 1:
        //Do something when middle button is pressed
        break;
    case 2:
        //Do something when right button is pressed
    }
}

OnMouseUp(int button) {
    switch(button){
    case 0:
        //Do something when left button is released
        break;
    case 1:
        //Do something when middle button is released
        break;
    case 2:
        //Do something when right button is released
    }
}

```
> 1 votes

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


# Question
Title: In A star, what is the point of recalculating the best path?
In A\* after the finding the next node with the lowest F value, you have to search the adjacent nodes again. When you find a node that was already in the open list, you're supposed to check if the g score for that node would be lower if you went through the current node to get there. My question is, what is the point of this? Won't it always be the same? If you take G = 14 for diagonal and G = 10 for horizontal/vertical wouldn't the G always be more if you went through 2 nodes instead of one?

Say the last node on the closed list's G value was 50. It has an adjacent square to the right with a G value of 60. Your current node has a G value of 64. If you went through the current node to get to the node adjacent to the one with the G value of 50, the G would be 74. You could switch the numbers all you want but the recalculated G would always be higher so what is the point of recalculating it?

# Answer
> If you take G = 14 for diagonal and G = 10 for horizontal/vertical wouldn't the G always be more if you went through 2 nodes instead of one?

Yes, but that is only one specific case. In that case, you would *not* have to check if the g-score would be lower and potentially re-add the node to the open list, because, in your graph, we can guarantee it will have the lowest g-score the first time it is added to the open list.

However, this is not true for all graphs.

---

We can formalize this. If the heuristic we use satisfies these two constraints:

```
for all nodes x,y with an edge between them,  h(x) <= h(y) + c(x,y)
h(goal) = 0

```

then we call the heuristic consistent *(or, less commonly, "monotone")*. In that case, we don't need to recheck the g-scores or readd a node to the open-list.

Since your heuristic satisfies those constraints, it is consistent.
> 3 votes

# Answer
What BlueRaja said. Essentially A\* allows you to also consider a weighted graph. Imagine that same game grid but some tiles are mountains, others are swamp and others are road. These different movement costs mean there is a faster route. For example, following the road around a mountain, rather than going over it. If the road is step cost 1, and the mountain is step cost 100. That is either a really long road, or the road is just more efficient.
> 0 votes

# Answer
> In A\* after the finding the next node with the lowest F value, you have to search the adjacent nodes again. When you find a node that was already in the open list, you're supposed to check if the g score for that node would be lower if you went through the current node to get there. My question is, what is the point of this? Won't it always be the same?

Only if you visit the nodes in order of increasing G value.

> If you take G = 14 for diagonal and G = 10 for horizontal/vertical wouldn't the G always be more if you went through 2 nodes instead of one?

Yes.

However, you're visiting the nodes in order of increasing F value. Depending on the details of the heuristic, this may not be the same as the order of increasing G value.
> 0 votes

---
Tags: path-finding
---


title: Creating and drawing models efficiently

text:
# Question
Title: Creating and drawing models efficiently
As I am learning the basics of game programming (in xna), I want to start creating simple 3d models and draw them (I'm already able to draw, control and animate them).

I want to create the following: a square surrounded by pillars.

What is better (in terms of performance and work):

1. Create a model containing the square and 20 prepositioned (of the same) pillars
2. Create a square and 1 pillar and then position and draw 20 pillars

Options 1 is obviously less work, but I think option 2 is better for performance.

Is this logical thinking and what do you think is the best option?

# Answer
The "best" option is to try it yourself and see what's faster. I will put my money on option 1 being faster.

You will only gain performance benefit this way if the pillar is incredibly expensive to draw, and you use effective culling.
> 1 votes

---
Tags: xna, 3d, models, performance
---


title: Modular spaceship control

text:
# Question
Title: Modular spaceship control
I am developing a physics based game with spaceships.

A spaceship is constructed from circles connected by joints. Some of the circles have engines attached.

Engines can rotate around the center of circle and create thrust. I want to be able to move the ship in a direction or rotate around a point by setting the rotation and thrust for each of the ship's engines.

How can I find the rotation and thrust needed for each engine to achieve this?

# Answer
I am solved that with local search. It's working, but performance is nearly bad. Maybe it is better to use theoretical mechanics but I do not know it.
> -5 votes

# Answer
Lets imagine the simple situation of a ship with just one engine. In order to move the ship, we simply point the thruster away from the direction we want to go, and thrust out. That pushes us in the direction we want to go. It's not possible to rotate a ship composed of only one thruster.

Lets scale our ship to three engines to make it more interesting:

If we wanted to move this ship somewhere up and to the left, we'd just point all our thrusters in the opposite direction and fire:

Same solution as the single thruster that takes care of linear movement.

But what about if we're missing a thruster? We have an unequal load?

Following the same strategy will cause the ship to rotate. In many situations, this will be mostly unavoidable, and in some cases preferable since it will orient the ship for better use of the available thrusters.

One strategy for mitigating this would be equalization. Split the ship down the axis of desired movement:

Then ensure that the right side and the left side equal each other. If they don't scale the thruster output until they do. This can easily result in no thrust being applied. It's up to you to decide if you want to instead thrust out causing rotation or force the player to redesign their ship by re-organizing their thrusters.

**How about rotation?**

This question describes the idea very well.

You'll need to calculate the center of mass. Then calculate the torque provided by each thruster. Lucky for you, your thrusters rotate, so you can rotate them to provide maximum torque. Maximum torque will come from a right angle to the moment arm. Applying the sum of the torques will rotate the body around the center of mass. You can also choose some other arbitrary rotation point like the bridge of the ship.

If you want to ensure that you rotate *in place* you can scale back the thrust of the thrusters that will cause your ship to move linearly. You can do that by adding up all the thrusters that have a positive torque and all those with a negative torque, then compare their absolute values. The group with the larger absolute value should be scaled back to match the absolute value of the other group.

You may also find a very helpful resource in Amit Patel.

He's done a 4 part series on configurable space ships here: part 1, part 2, part 3, part 4
> 6 votes

---
Tags: mathematics, physics
---


title: XNA - Getting pixel shade texcoords?

text:
# Question
Title: XNA - Getting pixel shade texcoords?
I'm still new to shaders and I'm trying to create a glow a shader. I understand how it all works and I don't think I'll have too much trouble with the rest of it, but I'm stuck at one point in particular which is getting the texcoords of the render target into my pixel shader.

Right now I'm setting the rendertarget, saving it to the texture, passing it to the shader. Then I'm going to do tex2D(texture, coords) but I don't know HOW to get the coordinates into my pixel shader. I've created float2 TexCoord : TEXCOORD0; for my vertex shader output but I don't know how to assign the coordinates as it reaches the pixel shader. Everything else (color,pos, normal) is just automatically passed in through the vertex shader and I'm assuming I don't need to change the format of that to include texcoords and it's something within the actual shader itself I need to add?

Thanks.

# Answer
Actually, you can use the `VPOS` built-in input to the pixel shader to get the coordinates of the pixel in the viewport. Like this:

```
void ps_main(float2 pixel : VPOS, /* ...other inputs... */)
{
    float2 uvPixel = (pixel + 0.5) * float2(1.0 / screenWidth, 1.0 / screenHeight);
    // ...sample a texture using uvPixel...
}

```

This includes the infamous half-texel offset that's needed to perfectly map a screen-space texture to the screen in D3D9. You don't need to write any outputs to `VPOS` from the vertex shader; it's handled for you automatically by the hardware. The `float2(1.0 / screenWidth, 1.0 / screenHeight)` can be precalculated and stored in a uniform. Some more info on `VPOS` is available in this gamedev.net thread.
> 3 votes

---
Tags: xna
---


# Question
Title: In A star, how does the heuristic help determine your path?
Say you're using a 4 by 5 grid. The G cost for horizontal and vertical movement is 10, and the G cost for diagonal movement is 14. On this page: http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html it says "At one extreme, if h(n) is 0, then only g(n) plays a role, and A\* turns into Dijkstra’s algorithm, which is guaranteed to find a shortest path."

Why would it find the shortest path? Wouldn't it find the longest path instead? If the heuristic no longer plays a role then it will never consider going diagonal because the cost of diagonal movement is 14. Previously, even if the G cost was higher than another adjacent node, it could still be chosen if the H cost was a bit lower.

Now, even if the shortest path was by going diagonal, it would never go diagonal because the G cost of diagonal movement will always be higher than the G cost for horizontal/vertical movement. So why exactly would it be guaranteed to find the shortest path if the heuristic was 0?

Another thing, what would be the difference if, let's say we're using the Manhatten method, and after calculating the total number of squares moved horizontally and vertically to reach the target square from the current square the heuristic was multiplied by 1 or if it was multiplied by 100? Wouldn't the path be the same either way?

# Answer
In short, the heuristic is added to the "cost so far". That's why when h(x) = 0 we have A\*=Dijkstra. In Dijkstra we only use the "cost so far", and adding 0 to a number doesn't change it.

In short, the formula is:

```
cost to reach P from Q = cost to reach Q + cost from P to Q + heuristic

```

I believe what you are missing is the "cost to reach Q part". Either way, I'll explain how Dijkstra works here so you can see it in action (I'm less familiar with A\*, but it shouldn't matter since they're the same in this case).

Say we have nine nodes:

```
TL TM TR
ML MM MR
BL BM BR

```

(TR=top-right, BL=bottom-left, etc.)

We start in BR and we want to find the path to TL.

Initially, we set the distance to the three nodes from BR:

```
MR = 10 from BR
BM = 10 from BR
MM = 14 from BR

```

Now, we take the node with the lowest cost so far, which is MR or BM. Let's take MR.

From MR we can reach TR, TM, MM, TM and BR. We'll add the costs of these distances to the cost of reaching MR (which is `10`). Also, since we've already visited BR, we won't check it again (in Dijkstra, at least).

```
TR = 10 + 10 = 20 from MR
TM = 10 + 14 = 24 from MR
MM = 14 from BR, 10 + 10 = 20 from MR. Since 14 < 20, we'll keep the path from BR and ignore the path from MR.
BM = 10 from BR, 10 + 14 = 24 from MR. We'll keep 10 from BR.

```

So we have:

```
BM = 10 from BR
MM = 14 from BR
TR = 20 from MR
TM = 24 from MR

```

So next we'll visit BM.

As you can see, the best path to MM the algorithm found so far is the one from BR, not the one from MR.

After we finish the algorithm, we'll have:

```
(TR = 20 from MR) (TM = 24 from MR or MM) (TL = 28 from MM)
(MR = 10 from BR) (MM = 14 from MM) (ML = 24 from MM or BM)
(BR = 0, start) (BM = 10 from BR) (BL = 20 from BM)

```

As you can see, the shortest path to TL *does* use the diagonals

> Another thing, what would be the difference if, let's say we're using the Manhatten method, and after calculating the total number of squares moved horizontally and vertically to reach the target square from the current square the heuristic was multiplied by 1 or if it was multiplied by 100? Wouldn't the path be the same either way?

Multiplying the heuristic by 1 would change nothing, since `1 * h(x) = h(x)`. Multiplying the heuristic by 100 would make the heuristic be bigger relatively to the "distance so far" which, according to the article you quoted, makes A\* look more like a Best-first-search and less like Dijkstra.
> 3 votes

# Answer
This is from a paper I wrote, which is why it is so expository.

The popular variant of Dijkstra's algorithm, the A\* algorithm, uses a ***heuristic*** to "help" Dijkstra's algorithm converge on a solution faster. What A\* does really is ***deter*** Dijkstra's algorithm from exploring nodes that are in the "wrong direction" from the destination by adding an ***additional cost*** (*on top of the edge weight cost*) to the exploration of nodes that would take us ***away*** from the desired destination node. As you can see in the figure below, A\* "doesn't bother" expanding nodes that lead away from the solution, hence converging on a solution faster.

Figure: Dijkstra's algorithm (left) and A\* algorithm (right) running on the same map as solved by the software accompanying Buckland's text. Red denotes expanded nodes, blue denotes final decision path.

The additional cost added to an edge traversal is called the ***heuristic function***. The cost of reaching a node then becomes *f(n) = g(n) + h(n)*, where *g(n)* is the accumulated edge weight cost and *h(n)* is the heuristic function.

The value of h(n) is usually the Euclidean distance ￼`sqrt(x^2+y^2)` to the destination node. If diagonal moves are not allowed, then its value can be the Manhattan distance to the destination node. The extra cost *h(n)* will not spoil the correctness of Dijkstra's algorithm so long as *h(n)* does not ever exceed *g(n)* (the actual edge‐weight cost of reaching that node), for any node. When *h(n)* meets this condition *h(n)* is called admissible. If *h(n)* is not admissible, then it will prevent A\* from finding the shortest path much like a backseat driver prevents an otherwise good driver from taking the best path by assigning incorrectly high costs to otherwise good routes.
> 7 votes

# Answer
The problem is that you're forgetting that the G function by itself is not the cost. The cost of a node is the cost of the parent node plus the G function cost to the new node.

Even if diagonal movements are 14 and cardinal moves are 10, the cost of moving diagonally from a parent close to the start node will be much lower than the cost of moving cardinally from a node far away from the start. That is, moving diagonally from the start node has a total cost of 14 (`0 + G:14 = 14`) while moving two square away in a straight line has a total cost of 20 (parent node cost of 10, so `10 + G:10 = 20`). Hence the diagonal movement will be checked before the linear movement in this scenario as it has a total lower cost.

The H function just helps in that it makes the engine more likely to consider a node closer to the goal. Dijkstra finds the shortest paths leading out from the start node until it happens up on the goal. That is, Dijkstra finds the shortest paths that are 1 unit away, then 2 units away, then 3 units away, etc. A\* will lean toward a path that is closer to the goal rather than just the shortest path to a node leading away from the goal.
> 2 votes

---
Tags: path-finding, heuristics
---


# Question
Title: What is the term for levels divided into a small number of chapters, each containing a grid of short levels?
There is a style of game design which is shared by many mobile puzzle games where a game is divided into an small number (3-10) of main chapters and each one has a grid of a larger number of short levels.

A famous example is Angry Birds, which has chapters it calls "Episodes":

Each one containing a grid of levels:

I would like to know what this style of game design is called.

I don't remember any game with this style from my childhood, this style seems to be relatively new.

SkyRoads (1993) has a relatively similar level selection menu:

# Answer
Well this is a level select menu. It's not new. *California games* had a level select menu.

Once you defeat all the levels in super mario world, you also effectively have a level select menu (it is very graphical though)
> 4 votes

# Answer
What you're referring to is actually a combination of two game design ideas, plus a UI design.

* Splitting game into multiple chapters or episodes, each with many levels in them
* Being able to select levels after you've completed them, and replay to get a higher score
* (UI) presenting the level selection as a grid

These ideas are all quite old. The first is detailed in this wiki article: Episodic video game, with examples going as far back as 1979. The key characteristic is similar to the Gillette razor model (which is an even older idea), where the first installment(s) are provided at very low cost (or even free in the case of episodic shareware games pioneered by Apogee), and subsequent episodes could be created relatively cheaply.

The second, level selection, is also an old and relatively obvious idea. Level select lets players replay earlier parts of the game, and having a "star" or high score system provides the incentive. Other ways of encouraging replays include using "par" times, or adding secret collectables.

The third is a UI idea; grid interfaces suit mobile touch interfaces particularly well. As a comparison, the game Candy Crush uses the first two game design ideas but not the grid interface, which makes it rather difficult to browse through the previous levels.
> 4 votes

# Answer
There is no official name. The grid like pattern is just a layout, no official name. The level design theory is linear level progression, which is pretty much the default type of level progression. I remember The Adventuers of Lolo also had a similar level progression. That was an NES game.

**Source:** Fundamentals of Game Design 2nd Edition - Earnest Adams ISBN: 9780132104753
**Source:** Personal knowledge
> 1 votes

---
Tags: game-design, gui, terminology, levels
---


# Question
Title: OpenGL - drawElements 2D imposible z-sorting (textured)
I am creating a 2D program in OpenGL 3.2 Now to render what I do is have a VBO for each texture and add the elements of the objects that use that texture to this vbo. Now as you know the order you render objects will be the **(fliped)** order you see them on the screen.

Here is the problem, as you know its possible to sort objects by their Z value in the same VBO *(by inserting them to the vbo according to their Z value)*. But when you want to sort them between VBOs thats impossible because they have to be in the correct VBO to have the correct texture, Meaning the VBOs that are drawn last will have positive Z value priority over VBOs that are drawn first.

*This causes the Z value to transfer from the actual objects, to their textures and makes the Z value be grouped for all objects that use the same texture.*

That was kinda confusing so to recap, because of the way VBOs work this is what is going to happen:

**Turtule texture id 1**

**Box texture id 2**

*(Each textures has its own VBO)*

*There is one turtle and **one** box, the turtle **(z = -1)** is behind the box **(z = 0)** . if I render the box VBO then the Turtle VBO What will happen is we will see the turtle over the box even though it has a z value that is less then the box.*

Here is some art I drew to help you visualize the problem:

**^^^** That makes the Z value of the actual turtle meaning less compared to the **"** Z **"** value of the VBO. This can be worked around by having a Z value for each VBO but that limits the program because if the Z of the boxes is bigger than turtles no matter what every turtles is gonna be hidden behind every box. And its a stupid way of doing it.

So finally to the question:

---

> What can I do to fix this, to have a meaning full Z value to each OBJECT.

---

**Notes:**

* I cannot draw the object individually because I use drawElements and because I add them to texture coresponding VBOs to reduce the VBO count and texture binding count.

**Stuff I have tried\* :** I have tried using the actual opengl Z-buffer, but I cannot blend layers because of that so its not a solution.

# Answer
> 3 votes
Put all the objects inside the same VBO, and use a texture atlas to put all your sprites on the same texture.

A texture atlas should look like this:

All you have to do is the get UV of each sprite in the atlas (which you can do using a tool like spritesheetmaker).

Don't be afraid to make a 1024x1024 texture, or a 2048x2048 texture, or even 4096x4096 textures seem to have reasonable support on GPUs these days.

# Answer
> 2 votes
Z values by themselves do relatively little other than change the projection of the individual vertex which for a 2D orthographic sprite game basically means they do nothing at all. If you want to have the API take Z values into account when rendering overlapping items the way you want, you need to be sure to turn on Z buffering. As you stated, though, this does not play well with blending by default; you need something more. Translucent objects *must* be sorted or a non-trivial order-independent translucency technique (like *depth peeling*) must be used.

Typically in a 2D app, however, you just sort the objects back-to-front. This is called the *painter's algorithm*. Sorting manually is quite easy. You don't need to change the VBO setup I think you're using (I'm not 100% clear), just change the order of your draw calls.

Even high-end 3D games still have to do this, as translucency all but requires it and high-performance rendering actually benefits quite a bit from it for opaque objects (by sorting closest first with Z-buffering on, to avoid overdraw and keeping fillrates low).

You can do the same thing for 2D, of course: sort front-to-back for opaque or "cut-out" objects (those with alpha values of only either 1 or 0), and then draw back-to-front for translucent objects. Use Z-buffering in both passes but only enable Z-*writing* for the first opaque object pass. This is relatively easy, gives good performance (especially on fillrate-limited hardware like most mobile devices), and shouldn't require many changes to your code.

You should also highly consider @bobobobo's advice. Atlasing is a *huge* benefit to performance, and is very much possible on GL 1.1 systems. You don't need a single atlas, you can have more than one. The primary benefit is that it lets you reduce state (texture changes) and minimize draw calls, which can have a huge performance impact. You can automatically generate texture atlases from your images at runtime which fits whatever the current driver's maximum texture size is, if you're really worried about compatibility with ancient/deficient drivers.

---
Tags: opengl, 2d, textures, vbo
---