# Question
Title: Map and fill texture using PBO (OpenGL 3.3)
I'm learning OpenGL 3.3 trying to do the following (as it is done in D3D)...

* Create Texture of Width, Height, Pixel Format
* Map texture memory
* Loop write pixels
* Unmap texture memory
* Set Texture
* Render

Right now though it renders as if the entire texture is black.

I can't find a reliable source for information on how to do this though. Almost every tutorial I've found just uses glTexSubImage2D and passes a pointer to memory.

Here is basically what my code does... (In this case it is generating an 1-byte Alpha Only texture but it is rendering it as the red channel for debugging)

```
GLuint pixelBufferID;
glGenBuffers(1, &pixelBufferID);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixelBufferID);
glBufferData(GL_PIXEL_UNPACK_BUFFER, 512 * 512 * 1, nullptr, GL_STREAM_DRAW);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

GLuint textureID;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 512, 512, 0, GL_RED, GL_UNSIGNED_BYTE, nullptr);
glBindTexture(GL_TEXTURE_2D, 0);

glBindTexture(GL_TEXTURE_2D, textureID);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pixelBufferID);
void *Memory = glMapBuffer(GL_PIXEL_UNPACK_BUFFER, GL_WRITE_ONLY);
// Memory copied here, I know  this is valid because it is the same loop as in my working D3D version
glUnmapBuffer(GL_PIXEL_UNPACK_BUFFER);
glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);

```

And then here is the render loop.

```
// This chunk left in for completeness
glUseProgram(glProgramId);
glBindVertexArray(glVertexArrayId);
glBindBuffer(GL_ARRAY_BUFFER, glVertexBufferId);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 20, 12);
GLuint transformLocationID = glGetUniformLocation(3, 'transform');
glUniformMatrix4fv(transformLocationID , 1, true, somematrix)

// Not sure if this is all I need to do
glBindTexture(GL_TEXTURE_2D, pTex->glTextureId);
GLuint textureLocationID = glGetUniformLocation(glProgramId, "texture");
glUniform1i(textureLocationID, 0);

glDrawArrays(GL_TRIANGLES, Offset*3, Triangles*3);

```

Vertex Shader

```
#version 330 core

in vec3 Position;
in vec2 TexCoords;
out vec2 TexOut;
uniform mat4 transform;

void main()
{
    TexOut = TexCoords;
    gl_Position = vec4(Position, 1.0) * transform;
}

```

Pixel Shader

```
#version 330 core

uniform sampler2D texture;
in vec2 TexCoords;
out vec4 fragColor;

void main()
{
   // Output color
   fragColor.r = texture2D(texture, TexCoords).r;
   fragColor.g = 0.0f;
   fragColor.b = 0.0f;
   fragColor.a = 1.0;
}

```

# Answer
> 6 votes
If you think about this conceptually, you'll see that all that mapping and filling a PBO does is map and fill a PBO - it does absolutely nothing to a texture object and you must handle that yourself in your own code.

The way to do this is via a glTexImage or glTexSubImage call, with the last (data) parameter handled in the same way as for other buffer object types; i.e. rather than being a pointer to system memory it is overloaded to function as an offset into the currently bound PBO.

So, to update a texture, you need to do the following:

```
glBindBuffer (GL_PIXEL_UNPACK_BUFFER, pboid);
byte *ptr = glMapBuffer (GL_PIXEL_UNPACK_BUFFER, ...);
// fill ptr here
glUnmapBuffer (GL_PIXEL_UNPACK_BUFFER);
// use while PBO is still bound, assumes GL_TEXTURE_2D and offset 0
glBindTexture (GL_TEXTURE_2D, textureid);
glTexSubImage2D (GL_TEXTURE_2D, ..., (void *) 0);
glBindBuffer (GL_PIXEL_UNPACK_BUFFER, 0);

```

Regarding your specific use case, I suspect that this is not going to give you great performance. PBOs are really most useful where you can take advantage of the asynchronous nature of the transfer, i.e. by using the texture for drawing a frame or two *after* the texture is filled from the PBO. Since you're using the texture in the same frame you don't get that and OpenGL may need to stall until the transfer completes, as well as incurring the extra overhead of binding and mapping a PBO.

Using glMapBuffer itself is also likely to be a suboptimal path; see this link for a further discussion (it's somewhat out of date but I believe still relevant - especially since the advent of glMapBufferRange (see next point) I believe that glMapBuffer is not likely to be anything of a candidate for optimization or sensible implementation for driver writers). You will likely obtain a better result with glMapBufferRange if your driver supports it.

What I would do instead of all this however is just use stock glTexSubImage2D with a system memory pointer as source, and see how that performs. You may well find (particularly with a texture that's only 512X512X1) that it's more than fast enough for you. The worst case should be no worse than what I've just described above, your driver may very well have it's own optimal path for replacing the entire texture rect (it could double-buffer internally, for example), or you could double-buffer the texture yourself if needed. You shouldn't need to consider any alternate options unless this process proves to be a definite and measurable bottleneck.

# Answer
> 7 votes
Pixel buffer objects are for performing pixel *transfers* to images. Pixel transfers are first and foremost *copy* operations.

You cannot map texture memory at all in OpenGL. You can use a buffer object as the destination for a *copy* operation (as in `glGetTexImage`). You can use a buffer object as the source for a *copy* operation (as in `glTexSubImage2D`). But you cannot map texture memory itself.

---
Tags: opengl, textures
---


title: Legality of AngelCode's BMFont

text:
# Question
Title: Legality of AngelCode's BMFont
Is it legal to use a bitmapped version of a proprietary font (such as Arial) in a commercial app?

I'm using AngelCode's BMFont to generate a bitmapped version of a few various system installed fonts for use in an iOS game. Is that legal to do without paying for a license for the font first?

# Answer
I would suspect the answer is that it is legal in your case, although it will vary from font to font, and what follows is advice to help you find out more and decide for yourself.

Font/typeface files are copyrighted, but the actual typeface itself may not be, at least in some jurisdictions, including the USA it seems. But if you want to sell internationally, it's probably wise to assume the font is under copyright.

If we assume this is true, then by default nobody but the owner has the right to distribute copies of the file or any other work derived from that file or the creative work within (ie. the shape of the font), including bitmap images. However, typeface designers know that this would cripple the usefulness of the font, and thus they usually distribute the font to app and OS developers under a license that allows them and their users to use that font in the creation of their own documents. Some licences even explicitly allow the font to be embedded in a document (eg. as commonly done in a PDF). However, the licence usually prohibits you from distributing the font itself, because they wish to reserve that right (so that they can sell it, obviously). And some designers are not so lenient with their licensing - one company quotes $900 for an iOS app use, for example.

So the question becomes more nuanced - is your bitmapped version of the font considered a document created with the font, which is usually explicitly permitted for distribution? Or is it considered a transformed copy of the font, where redistribution is explicitly denied? Obviously it is both, but the following factors may help decide how it will primarily be viewed:

* Are you redistributing the font to someone who wouldn't legally be able to use it anyway? In the case of a system font you are not, so this is fairly uncontroversial - both parties have the right to use the font in their own documents so it would be hard to argue that you need to buy an extra license for this purpose.
* Are you embedding the font in the app? If you put the bitmap into the binary, or otherwise obscured, rather than leaving it as a standalone file that is easily extracted and reused, then this will typically fulfil the embedding requirement and make it an authorised usage (if indeed the licence for the font permits this).
* Are you distributing it in a form that replaces the need for someone else to license it legally? If your app allows easy extraction of the font, or lets people arrange the letters to produce text in that typeface for their own documents (eg. you're selling a mini Photoshop clone), then that is very likely to contradict the spirit of the licence even if the wording is not clear.

Ultimately though, as with most legal questions, it comes down to a question of probabilities - you can't guarantee you won't get sued even if you follow the law to the letter, only that you'll win if you can cover the legal fees long enough to see the case through. Similarly you can break a licence and you may get away with it - and in this case, the licence may not even be meaningful due to the USA court ruling that fonts themselves cannot be copyrighted. But it's a gamble.

The safest thing to do is to select a font that you are explicitly allowed to use in this way. In addition to the links that Mr Beast provided, I like to recommend FontSquirrel as the quality of fonts there is very good and the licences are generally very liberal.
> 2 votes

# Answer
If you convert or modify something it still falls under the same copyright law as the original work.

So the answer is no.

But don't sweat about it, there are a bunch of fonts which are actually free, for example at OpenFontLibrary and dafont.com. I am sure you will find a free font which will suit your needs.
> 2 votes

---
Tags: ios, legal, licensing, fonts
---


title: Farseer Physics: Ways to create a Body?

text:
# Question
Title: Farseer Physics: Ways to create a Body?
I want to create something similar to this using farsser and Kinect:

https://vimeo.com/33500649

This is my implementation until now:

http://www.youtube.com/watch?v=GlIvJRhco4U

I have the outline vertices and the triangulation of the user. And following the Texture to Polygonmsample i used this line to create the shape, where farseerObject is a list of vertices of the triangles:

\_compound = BodyFactory.CreateCompoundPolygon(World, farseerObject, 1f, BodyType.Dynamic);

But I have to update the body each frame (like 30 fps) and this is very slow. I get just 2 or 3 fps.

**There's another (faster) way to create the Body from a list of triangles or the contour vertices?**

How do you think they do this on Box2D?

# Update:

After some testings i used EdgeShapes for the user contour (without triangulation) and i update the vertices for that edges in the fixtures every frame, now all is faster.

```
((EdgeShape)(farseerBody.FixtureList[i].Shape)).Vertex1 = new Vector2(farseerVertices[i].X, farseerVertices[i].Y);

```

**But the collisions does not work!**

My approach is incorrect?

# Answer
> 3 votes
**Finally works!**

I had the vertices of the contour as a sequence, so the solution was use the LoopShape to create the fixture of the body. I did not even know that Class =P

```
 LoopShape loopShape = new LoopShape(farseerVertices);
 //Delete the previous fixture
 farseerBody.DestroyFixture(previousFixture);
 //Create new fixture with the new contour
 farseerBody.CreateFixture(loopShape);

```

And that's all!

---
Tags: xna, c#, algorithm, box2d, farseer-physics-engine
---


# Question
Title: Component-based design: handling objects interaction
I'm not sure how exactly objects do things to other objects in a component based design.

Say I have an `Obj` class. I do:

```
Obj obj;
obj.add(new Position());
obj.add(new Physics());

```

How could I then have another object not only move the ball but have those physics applied. I'm not looking for implementation details but rather abstractly how objects communicate. In an entity based design, you might just have:

```
obj1.emitForceOn(obj2,5.0,0.0,0.0);

```

Any article or explanation to get a better grasp on a component driven design and how to do basic things would be really helpful.

# Answer
> 10 votes
That is usually done using messages. You can find lots of details in other questions on this site, like here or there.

To answer your specific example, a way to go is to define a small `Message` class that your objects can process, e.g:

```
struct Message
{
    Message(const Objt& sender, const std::string& msg)
        : m_sender(&sender)
        , m_msg(msg) {}
    const Obj* m_sender;
    std::string m_msg;
};

void Obj::Process(const Message& msg)
{
    for (int i=0; i<m_components.size(); ++i)
    {
        // let components do some stuff with msg
        m_components[i].Process(msg);
    }
}

```

This way you're not "polluting" you `Obj` class interface with component-related methods. Some components can choose to process the message, some might just ignore it.

You can start by calling this method directly from another object:

```
Message msg(obj1, "EmitForce(5.0,0.0,0.0)");
obj2.ProcessMessage(msg);

```

In this case, `obj2`'s `Physics` will pick the message, and do whatever processing it needs to do. When done, it will either:

* Send a "SetPosition" message to self, that the `Position` component will pick;
* Or directly access the `Position` component for modifications (quite wrong for a pure component-based design, as you can't assume every object has a `Position` component, but the `Position` component could be a requirement of `Physics`).

It's generally a good idea to *delay* the actual processing of the message to the *next* component's update. Processing it immediately could mean sending messages to other components of other objects, so sending just one message could quickly mean an inextricable spaghetti stack.

You'll probably have to go for a more advanced system later on on: asynchronous message queues, sending messages to group of objects, per-component registering/unregistering from messages etc.

The `Message` class can be a generic container for a simple string as shown above, but processing strings at runtime isn't really efficient. You can go for a container of generic values: strings, integers, floats... With a name or better yet, an ID, to distinguish different types of messages. Or you can also derive a base class to fit specific needs. In your case, you could imagine an `EmitForceMessage` that derives from `Message` and adds the desired force vector -but beware of the runtime cost of RTTI if you do so.

# Answer
> 3 votes
What I did to solve a problem similar to what you show, is to add some specific component handlers and add some kind of event resolution system.

So, in the case of your "Physics" object, when that is initialized it would add itself to a central manager of Physics objetcs. In the game loop, these kind of managers have their own update step, so when this PhysicsManager is updated it calculates all the physics interactions and adds them into an event queue.

After you produce all your events, you can resolve your event queue simply checking what happened and taking actions acordingly, in your case, there should be an event saying object A and B interacted somehow, so you call your emitForceOn method.

Pros of this method:

* Conceptually, is really simple to follow.
* Gives you room for specific optimizations like using quadtress or whatever you would need.
* It ends up being really "plug and play". Objects with physics don't interact with non-physics objects because they don't exist for the manager.

Cons:

* You end up with a lot of references moving around, so it can become a bit messy to correctly clean everything if you are not careful (from your component to the component owner, from the manager to the component, from the event to participants, etc).
* You have to put special thought to the order in which you resolve everything. I guess it's not your case, but I faced more than one infinite loop where an event created another event and I was just adding it to the event queue directly.

I hope this helps.

PS: If someone has a cleaner/better way to solve this, i'd really like to hear it.

# Answer
> 1 votes
```
obj->Message( "Physics.EmitForce 0.0 1.1 2.2" );
// and some variations such as...
obj->Message( "Physics.EmitForce", "0.0 1.1 2.2" );
obj->Message( "Physics", "EmitForce", "0.0 1.1 2.2" );

```

A few things to note on this design:

* Name of the component is the first parameter - this is to avoid having too much code work on the message - we can't know what components any message might trigger - and we don't want all of them chewing a message with 90% failure rate that converts to a lot of unnecessary branches and *strcmp*'s.
* Name of the message is the second parameter.
* The first dot (in #1 and #2) is not necessary, it's just to make reading easier (for people, not computers).
* It's sscanf, iostream, you-name-it compatible. No syntactic sugar that does nothing to simplify the processing of the message.
* One string parameter: passing the native types is not cheaper in terms of memory requirements because you have to support an unknown number of parameters of relatively unknown type.

---
Tags: c++, architecture, component-based
---


# Question
Title: Platformer gravity where gravity is greater than tile size
I am making a simple grid-tile-based platformer with basic physics.

I have 16px tiles, and after playing with gravity it seems that to get a nice quick Mario-like jump feel, the player ends up moving faster than 16px per second at the ground.

The problem is that they clip through the first layer of tiles before collisions being detected. Then when I move the player to the top of the colliding tile, they move to the bottom-most tile.

I have tried limiting their maximum velocity to be less than 16px but it does not look right.

Are there any standard approaches to solving this? Thanks.

# Answer
> 5 votes
The easiest approach is to check for collisions more often. This approach separates into two methods:

* \[most optimal, harder to implement\] Check for collisions at least once per frame and after each N pixels (usually half of a tile) of movement.
* \[least optimal, easier to implement\] Split the movement vector into N parts (depends on level design, could even be 16 and more), check for collisions after each addition of a part.

# Answer
> 5 votes
You could use movement subdivision. If you have an object with a bounding box with a height of 50 and it moves 300 pixels in height that frame then you can move it 6 times 50 pixels and check each time if there is a collision.

A small optimization to this technique is to draw a second bounding box from the start position to the end position of the bounding box and check if anything intersects with this. If not you can skip the movement subdivision test and just move it once.

---
Tags: physics, platformer
---


# Question
Title: 2D animations frames vs 3D animation for small indie project: timing considerations
pretty lame question but was wondering..

I am developing a 2D game using Cocos2D for iOS. The art work till now is all 2D (is a shooter game) but some of the characters would benefit of complex animations (eg. 20 frames). I feel a bit stupid because I came across only now that there is the chance to do 3D to 2D frames exporting and then to use them in Cocos2D.

The thing that put me off on 3D gaming at first was that it takes more than one person in a team to do so properly (Illustrator, 3D modeller, 3D animator and programmer). Now I feel a bit stupid because having a 3D model I could do and modify the poses whenever I wanted (I should ask to the 3D animator which I guess would be **time expensive**).

Instead now is me and two illustrators (as I require many frames per character).

Is my impression that it would have been much longer right or not? Are there any other project management considerations that can be done on this?

Sorry if for some this might be trivial but is my first "indie game developer experience".

# Answer
There is no correct answer to your question. It depends on several things, like:

1. How close is your release date? (You have one, right?)
2. How much faster would you be able to finish your game with this newly discovered method?
3. How much extra value would the new graphics add to your game? Would it look better?
4. How much existing content will you have to remake if you decide to go with the 3D models?
5. Do you have the right tools (licensed or free) to create 3D models with animations?
6. Do you have the skills to make the new graphics look at least as good as the current one?

During a project, you'll run into many many many *"I feel a bit stupid because I came across only now..."* moments. As a team leader / game designer, you have to consider many things before deciding to switch to another technology, or to stick with the existing one. **Just keep in mind, that you software has to be finished at some point.** Techniques and technologies come and go, and **you'll feel on many occasions, that you are doing something stupid by not following a great new technique**. If you're really not sure, then the best advice would be just finish your current project with the techniques you're already familiar with.
> 1 votes

# Answer
This depends on a lot of factors and cannot easily be answered, like:

* How fast or slow are the 2D artists, how detailed drawings do you require of them
* How detailed a 3D model and how complex rigging would it require to fulfill your needs
* Just animating a complex 3D model like a human walking requires skill and time, though animating something mechanical like a spaceship turret rotating really don't

As you've noticed, doing a 3D model with all the work behind it including texturing, rigging, a few key poses and so on will likely take a lot more initial time, but with the possibility to pay off in the end if you can reuse it often to render new sprites/frames. But only if it's good enough to work for all the poses you realize you require along the way.

I would consider this more of a question of art design, as both methods has the potential to be equally time consuming - what kind of looks should the game have? Regardless of shading, 3D rendered sprites almost always look and animate differently from hand-drawn sprites.
> 1 votes

---
Tags: 2d, 3d, animation, cocos2d-iphone
---


# Question
Title: How many players can UDK support without Networking
I've been looking for the answer to this for some time now, but cannot find anything online that is helpful.

What I want to know is the amount of players that the UDK can support on one single machine. An example of this would be golden eye on the N64. On that, you could get 4 players all playing the same game at the same time using split screen. Like in this image:

Does anyone know is the UDK is capable of doing similar?

# Answer
This is called **split screen**.

It's a relatively big topic to handle in a small reply but is strictly related to how you are managing your viewport, you can find more online in the wiki.
> 5 votes

---
Tags: multiplayer, udk
---


# Question
Title: background animation algorithm for single screen
I’m writing simple strategy game (in xna), and would like to have an animated background. In my game all the actions happens inside one screen and thus standard parallax effect does not look appropriate. However, I found a video of a game with suitable background animation for my game http://www.youtube.com/watch?v=Vcxdbjulf90&feature=share&list=PLEEF9ABAB913946E6 (from 3 to 6s, while main character stays at the same place). What is the algorithm to do this stuff? It would be nice if someone can provide a reference for a similar example (language is not important).

# Answer
> 1 votes
It's not the same effect as the video you linked, but one simple possibility is to scroll a texture over the entire screen using the wrap texture addressing mode. Here's one example using a cloud texture:

One effect that I think looks pretty cool for a top-down game taking place in the ground, is to create a texture which contains only the *shadows* formed by the clouds and wrap that over the scene. I've used that in this demo although the effect is subtle.

As for the video you linked, I believe the effect is probably based on some sort of animated perlin noise so look into that. There are many resources on the subject online.

---
Tags: algorithm, animation
---


# Question
Title: Can I remove the systems from a component entity system?
After reading a lot about entity-component based engines, I feel like there is no real definition for this kind of engine. Reading this question, and the linked articles, made me think a lot. I do not feel that comfortable using the system concept, so I'll write something else that is inspired by this pattern. I'd like to know if it is a good way to organize game code, and what improvements can be made.

Regarding a more strict implementation of the entity-component based engine, is my solution viable? Do I risk getting stuck, at any point, due to the lack of flexibility of this implementation, or anything else?

---

My engine, as for entity-component patterns, has entities and components, but no systems, since the game logic is handled by components. I also think the main difference is the fact that my engine will use inheritance and object-orientated programming concepts, in general. I don't try to minimize them.

* Entity: an entity is an abstract class. It holds a position, width, height, scale and a list of linked components. Every frame, the entity will be updated (i.e. all the components linked to this entity will be updated), and rendered, if a render component is specified.
* Component: like for entity, a component is an abstract class that must be extended to create new components. The behavior of an entity is created through the components collection. Components are updated when the owning entity is updated, or for only one specific component (render component), rendered.

# Answer
> Regarding a more strict implementation of entity/component based engine, is my solution viable?

Will it work? Sure, you can make it work. But I wouldn't recommend it.

> Do I risk to get stuck at any point due to the lack of flexibility of this implementation (or anything else)?

You're straying pretty far away from the entity/component concept. Without the systems, the components *have* to know about each other for things to get done. That means they can no longer happily do their work in isolation and they get very complex the deeper into the project you get. The more complex the components are the more issues you'll have creating new types of entities. Some entities will have loads of code and data in their components that they don't use. Eventually you'll run into all the same problems as an inheritance structure.
> 10 votes

# Answer
I love Component based frameworks. For a long while I looked for a way to uncouple the logic from the data from the graphic. I tried to apply MVVM patterns to game entities but really it did not work. Eventually I wrote my entity based framework and everything became simple and smooth! The main rule is too keep it simple. The second rule is to reduce the flexibility as much as you can. Giving more options to the user is confusing. You should design the as perfect as possible way to solve problems and assume that that way is enough.

Component based frameworks promote composition over inheritance by definition. Initially I thought to let the user inherit from Entity and define his own Entity, eventually I realized that that was a redundant option. Now the user can only define components.

My last advice is to let the user inject dependencies through component constructor. In this way it will be also simple let entities communicate each other.

The definition of the behaviors of the component through interface is more or less what I have done as well and I find it a very good idea.

Edit: About the system, yeah I called them Engines in my framework. They are a good idea as well, solve part of the communication problems, so no, they should not be removed.
> 1 votes

---
Tags: architecture, component-based
---


title: Using MVC with a retained mode renderer

text:
# Question
Title: Using MVC with a retained mode renderer
I am using a retained mode renderer similar to the display lists in Flash. In other words, I have a scene graph data structure called the `Stage` to which I add the graphical primitives I would like to see rendered, such as images, animations, text. For simplicity I'll refer to them as `Sprites`.

Now I'm implementing an architecture which is becoming very similar to MVC, but I feel that that instead of having to create `View` classes, that the sprites already behave pretty much like `Views` (except for not being explicitly connected to the `Model`). And since the `Model` is only changed through the `Controller`, I could simply update the view together with the `Model` in the controller, as in the example below:

**Example 1**

```
class Controller
{
    Model model;
    Sprite view;
    void TeleportTo(Vector2 position) { model.Position = view.Position = position; }
}

```

The alternative, I think, would be to create `View` classes that wrap the sprites, make the model observable, and make the view react to changes on the model. This seems like a lot of extra work and boilerplate code, and I'm not seeing the benefits if I'm just going to have one view per controller.

**Example 2**

```
class Controller
{
    Model model;
    View view;
    void TeleportTo(Vector2 position) { model.Position = position; }
}

class View
{
    Model model;
    Sprite sprite;
    View() { model.PropertyChanged += UpdateView; }
    void UpdateView() { sprite.Position = model.Position; }
}

```

So, how is MVC or more specifically, the View, usually implemented when using a retained-mode renderer? And is there any reason why I shouldn't stick with example 1?

# Answer
> 3 votes
as I've recently written as answer to another question, I tried to adapt the MVC pattern to game entities. My advice is: forget it.

Have a look to a Entity based system to achieve data/graphic/logic uncoupling: Implementing features in an Entity System

however, if you really want to stick with the MVC pattern what I used to do is to inject the model both into the controller and the view. The view was then using the model to update itself (more or less like your second case)

---
Tags: architecture, mvc
---


# Question
Title: World of Warcraft like C++/C# server (highload)
I know it is very big topic and maybe my question is very beaten, but I'm interesting of basics how to write highload server for UDP/TCP client-server communications in MMO-like game on C++/C#? I mean what logic of retrieving hundreds and thousands packages at the same time and sending updates to clients? Please advice me with architecture solutions, your experience, ready-to-use libraries. Maybe you know some interesting details how WoW servers work. Thank you!

Edit: my question is about developing, not hardware/software tools;

# Answer
> 3 votes
Since I can't give a short comment - here a long answer.

First of all: What lorancou said!

To go more into detail: What do you need axactly? Chat - check some common protocols (like IRC) ... BTW a good hint for the gaming relevant things

But I guess it is about gaming relevant issues, so there some general hints I can think of boosting the performance

1. Minimize traffic
    * It is enough to send a movement vector from time to time (try the exact duration)
    * In most cases UDP is sufficient - no ack necessary
2. Minimize number of server requests
    * let the client do a lot of the calculations (if you share the random seed and the stats, it is enough to transmit the actions, every client can calc the exact values and from occasionally there can be a check)
    * you don't need to send the action instantly, it can be enough to send them bundled from time to time)
3. Partition the area, similar to Occlusion Culling in graphics

That are some things I can think of right now w/o much thinking, if you think hard enough you get a lot more information.

Maybe I'm missing the point of your question - in this case you need to clarify.

---
Tags: c++, c#, mmo, client-server, world-of-warcraft-modding
---


# Question
Title: How do I implement features in an entity system?
After asking two questions about entity systems (, ), and reading some articles on them, I think that I understand them much better than before. I still have some uncertainties, mainly about building a particle emitter, an input system, and a camera. I obviously still have some problems understanding entity systems, and they might apply to a whole other range of objects, but I chose these three because they are very different concepts, should cover a pretty broad ground, and help me understand entity systems and how to handle problems like these, myself, as they come along.

I am building an engine in JavaScript, and I've implemented most of the core features, which include: input handling, flexible animation system, particle emitter, math classes and functions, scene handling, a camera and a render, and a whole bunch of other things that engines usually support. I read Byte56's answer, that got me interested into making the engine into an entity system. It would still remain a HTML5 game engine, with the basic scene philosophy, but it should support dynamic creation of entities from components.

---

The problem I have, now, is fitting my old engine concept into this new programming paradigm. These are some of the definitions from the previous questions, updated:

* An **Entity** is an identifier. It doesn't have any data, it's not an object, it's a simple id that represents an index in the scenes list of all entities (which I actually plan to implement as a component matrix).
* A **Component** is a data holder, but with methods that can operate on that data. The best example is a `Vector2D`, or a "Position" component. It has data: `x` and `y`, but also some methods that make operating on the data a bit easier: `add()`, `normalize()`, and so on.
* A **System** is something that can operate on a set of entities that meet the certain requirements; usually the entities need to have a specified set of components, to be operated upon. The system is the "logic" part, the "algorithm" part, all the functionality supplied by components is purely for easier data management.

---

### Camera

The camera has a `Vector2D` position property, a rotation property and some methods for centering it around a point. Each frame, it is fed to a renderer, along with a scene, and all the objects are translated according to its position. The scene is then rendered.

How could I represent this kind of an object in an entity system? Would the camera be an entity, a component, or combination (as per my answer)?

### Particle Emitter

The problem I have with my particle emitter is, again, what should be what. I'm pretty sure that particles themselves shouldn't be entities, as I want to support over 10,000 of them, and I believe that creating that much entities would be a heavy blow on my performance.

How could I represent this kind of an object in an entity system?

### Input Manager

The last one I want to talk about is how input should be handled. In my current version of the engine, there is a class called `Input`. It is a handler that subscribes to the browsers events, such as key presses and mouse position changes, and also maintains an internal state. Then, the player class has a `react()` method, which accepts an input object as an argument. The advantage of this is that the input object could be serialized into .JSON, and then shared over the network, allowing for smooth multiplayer simulations.

How does this translate into an entity system?

# Answer
> 28 votes
* **Camera:** Making this a component would be pretty neat. It would just have a `isRendering` flag and depth range like Sean said. In addition to "field of view" (I guess you might call it scale in 2D?) and an output zone. The output zone could define the portion of the game window that this camera gets rendered to. It wouldn't have a separate position/rotation like you mention. The entity you create that has a camera component would use the position and rotation components of that entity. Then you'd have a camera system that looks for entities that have a camera, position and rotation components. The system takes that entity and draws all the entities it can "see" from it's position, rotation, depth of view and field of view, to the specified portion of the screen. That gives you lots of options for simulating multiple view ports, "character view" windows, local multiplayer, different layers of GUI and so on.
* **Particle Emitter:** This too should just be a component. The particle system would look for entities that have a position, rotation and particle emitter. The emitter has all the properties needed to reproduce your current emitter, I'm not sure what all those are, stuff like: rate, initial velocity, decay time and so on. You wouldn't have to make multiple passes. The particle system knows which entities have that component. I imagine you could re-use a good deal of your existing code.
* **Inputs:** I'd have to say making this into a component makes the most sense given the suggestions I make above. Your `input system` would get updated every frame with the current input events. Then when it's going through all it's entities that have the input component, it will apply those events. The input component would have a list of keyboard and mouse events all associated method callbacks. I'm not really sure where the method callbacks would live. Perhaps some input controller class? Whatever makes the most sense for later modification by users of your engine. But this would give you the power to easily apply input control to camera entities, player entities or whatever you needed. Want to synchronize the movement of a bunch of entities with the keyboard? Just give them all input components that respond to the same inputs and the input system applies those move events to all the components asking for them.

So most of this is just off the top of my head, so it probably won't make sense without further explanation. So just let me know what you're not clear on. Basically, I've given you a lot to work on :)

# Answer
> 14 votes
Here's how I approached this:

**Camera**

My camera is an entity like any other, which has attached components:

1. `Transform` has `Translation`, `Rotation` and `Scale` properties, in addition to others for velocity, etc.
2. `Pov` (Point of view) has `FieldOfView`, `AspectRatio`, `Near`, `Far`, and anything else required to produce a projection matrix, in addition to a `IsOrtho` flag used to switch between perspective and orthographic projections. `Pov` also provides a lazy-load `ProjectionMatrix` property used by the rendering system that's internally calculated on read, and cached until any of the other properties are modified.

There is no dedicated camera system. The Render System maintains a list of `Pov`'s and contains logic for determining which one to use when rendering.

**Input**

An `InputReceiver` component can be attached to any entity. This has an attached event handler (or lambda if your language supports it) that is used to hold entity-specific input processing, which takes parameters for current and previous key state, current and previous mouse location and button state, etc. (Actually, there are separate handlers for mouse and keyboard).

For example, in an Asteroids-like test game I created when getting used to Entity/Component, I have two input lambda methods. One handles ship navigation by processing the arrow keys and the space bar (for firing). The other handles general keyboard input - keys for exit, pause, etc, restart level, etc. I create two components, attach each lambda to its own component, then assign the navigation receiver component to the ship entity, an the other one to a non-visible command processor entity.

Here's the event handler to handle keys that are held between frames that gets attached to the ship's `InputReceiver` component (C#):

```
  void ship_input_Hold(object sender, InputEventArgs args)
    {
        var k = args.Keys;
        var e = args.Entity;

        var dt = (float)args.GameTime.ElapsedGameTime.TotalSeconds;

        var verlet = e.As<VerletMotion>();
        var transform = e.As<Transform>();

        if (verlet != null)
        {

        /// calculate applied force
            var force = Vector3.Zero;
            var forward = transform.RotationMatrix.Up * Settings.ShipSpeedMax;

            if (k.Contains(Keys.W))
                force += forward;

            if (k.Contains(Keys.S))
                force -= forward;

            verlet.Force += force * dt;
        }

        if (transform != null)
        {
            var theta = Vector3.Zero;

            if (k.Contains(Keys.A))
                theta.Z += Settings.TurnRate;

            if (k.Contains(Keys.D))
                theta.Z -= Settings.TurnRate;

            transform.Rotation += theta * dt;
        }

        if (k.Contains(Keys.Space))
        {
            var time = (float)args.GameTime.TotalGameTime.TotalSeconds - _rapidFireLast;

            if (time >= _rapidFireDelay)
            {
                Fire();
                _rapidFireLast = (float)args.GameTime.TotalGameTime.TotalSeconds;
            }
        }
    }

```

If your camera is mobile, give it its own `InputReceiver` and `Transform` component, attach a lambda or handler that implements whatever kind of control you want, and you're done.

This is kind of neat in that you can move the `InputReceiver` component with the navigation handler attached from the ship to an asteroid, or anything else for that matter, and fly that around instead. Or, by assigning a `Pov` component to anything else in your scene - an asteroid, street lamp, etc. - you can view your scene from that entity's perspective.

An `InputSystem` class that maintains an internal state for the keyboard, mouse, etc. `InputSystem` filters its internal entity collection to entities that have an `InputReceiver` component. In its `Update()` method, it iterates through that collection and calls the input handlers attached to each of those components in the same way that the rendering system draws each entity with a `Renderable` component.

**Particles**

This really depends on how you plan on interacting with the particles. If you just need a particle system that behaves like one object - say, a fireworks show that the player can't touch or hit - then I'd create a single entity, and a `ParticleRenderGroup` component that contains whatever information you need for the particles - decay, etc. - that isn't covered by your `Renderable` component. When rendering, the render system would see if an entity has the `RenderParticleGroup` attached and handle it accordingly.

If you need individual particles to participate in collision detection, respond to input, etc., but you just want to render them as a batch, I'd create a `Particle` component that contains that information on a per-particle basis, and create them as separate entities. The render system can still batch them, but they'll be treated as separate objects by the other systems. (This works very well with instancing.)

Then, either in your `MotionSystem` (or whatever your using that handles updating entity position, etc.) or in dedicated `ParticleSystem`, perform whatever processing is required for each particle per-frame. The `RenderSystem` would be responsible for building/batching and caching particle collections as they're created and destroyed, and render them as required.

One nice thing about this approach is that you don't have to have any special cases for collision, culling, etc. for particles; they code you write for every other kind of entity can still be used.

**Conclusion**

If you're considering going cross-platform - not super-applicable to JavaScript - all of your platform-specific code (namely, rendering and input) is isolated into two systems. Your game logic remains in platform-agnositic classes (motion, collision, etc.) so you shouldn't have to touch them when porting.

I understand and agree with Sean's position that shoe-horning things into a pattern in order to strictly adhere to the pattern, rather than tweaking the pattern to fill the needs of your application, is bad. I just don't see anything in Input, Camera or Particles that requires that sort of treatment.

# Answer
> 7 votes
Input and game logic will likely be handled in a dedicated chunk of code outside the entity component system. It's technically possible to shove it into the design, but there's little benefit - game logic and UI is hacky and full of leaky abstractions no matter what you do, and trying to force the square peg into a round hole just for architectural purity is a waste of time.

Likewise, particle emitters are special beasts, especially if you care at all about performance. An emitter component makes sense, but graphics is going to be doing some special magic with those components, intermixed with the magic for the rest of rendering.

Regarding your camera, just give cameras an active flag and maybe a "depth" index, and let the graphics system render all of them that are enabled. This is actually handy for a lot of tricks, including GUIs ( want your GUI rendered in an orthographic mode on top of the game world? No problem, they're just two cameras with different object masks and GUI set to a higher layer). It's also useful for special effects layers and such.

# Answer
> 5 votes
> Would the camera be an entity or simply a component?

I'm not sure what this question is really asking. Given that the only things you have in the game are entities, then cameras have to be entities. The camera functionality is implemented via some sort of camera component. Don't have separate "Position" and "Rotation" components - that is far too low level. They should be combined into some sort of WorldPosition component which would apply to any entity located in the world. As for which one to use... you have to get logic into the system somehow. Either you hard-code it into your camera handling system, or you attach scripts, or something. You can have an enabled/disabled flag on a camera component if it helps.

> I'm pretty sure that particles themselves shouldn't be entities

Me too. A particle emitter would be an entity, and the particle system would track the particles associated with a given entity. Things like this are where you realise that "everything is an entity" is absurdly impractical. In practice, the only things that are entities are relatively complex objects that benefit from combinations of components.

As for Input: input doesn't exist in the game world as such so that's handled by a system. Not necessarily a 'component system' because not everything in your game is going to revolve around components. But there will be an input system. You might want to mark the entity that responds to input with some sort of Player component, but the input is going to be complex and completely game-specific so there's little point trying to make components for this.

# Answer
> 1 votes
Here are some of my ideas of solving these problems. They will probably have something wrong with them, and there will probably be a better approach, so please, direct me to those in your answer!

**Camera**:

There is a "Camera" component, which can be added to any entity. I can't really figure what data should I put in this component, though: I could have separate "Position" and "Rotation" components! The `follow` method doesn't need to be implemented, because it's already following the entity it is attached to! And I'm free to move it around. The problem with this system would be many different camera objects: how can the `RendererSystem` know which ones to use? And also, I used to just pass the camera object around, but now it seems that the `RendererSystem` will need to iterate two times over all the entities: first to find the ones acting like cameras, and second, to actually render everything.

**ParticleEmitter**:

There would be a `ParticleSystem` which would update all entities that had a "Emitter" component. Particles are dumb objects in a relative coordinate space, inside that component. There is a problem of rendering here: I would either need to make a `ParticleRenderer` system, or extend the functionality of the existing one.

**Input system**:

The main concern for me here was the logic, or the `react()` method. The only solution I came up with is a separate system for that, and a component for each system, that would indicate which one to use. This really seems too hacky, and I don't know how to handle it well. One thing is that, as long as I'm concerned, the `Input` can stay implemented as a class, but I don't see how could I integrate it to the rest of the game.

---
Tags: javascript, entity-system, component-based
---


title: Low-level game engine renderer design

text:
# Question
Title: Low-level game engine renderer design
I'm piecing together the beginnings of an extremely basic engine which will let me draw arbitrary objects (`SceneObject`). I've got to the point where I'm creating a few sensible sounding classes, but as this is my first outing into game engines, I've got the feeling I'm overlooking things. I'm familiar with compartmentalising larger portions of the code so that individual sub-systems don't overly interact with each other, but I'm thinking more of the low-level stuff, starting from vertices working up.

So if I have a `Vertex` class, I can combine a list of those with a list of indices to make a `Mesh` class. How does the engine determine identical meshes for objects? Or is that left to the level designer? Once we have a `Mesh`, that can be contained in the `SceneObject` class. And a list of `SceneObject` can be placed into the `Scene` to be drawn.

Right now I'm only using OpenGL, but I'm aware that I don't want to be tying OpenGL calls right in to base classes (such as updating the vertices in the `Mesh`, I don't want to be calling `glBufferData` etc).

Are there any good resources that discuss these issues? Are there any "common" heirachies which should be used?

# Answer
> 4 votes
A mesh class should include more things like AABB and material info. You might even find yourself in a need to store multiple meshes in one class. Or perhaps you could need different vertex formats. It appears that you've started building your engine before your game. And that never helps. You should instead try to think of what you're realistically going to need and design with that in mind.

Tying OpenGL calls in base classes isn't bad. It just means that you won't use another API. And no one needs two APIs at the same time. If you'll find yourself in a need for multiple renderers (even though you shouldn't because you use OpenGL), it is much easier to implement the renderer as a service which the game passes data to and simply lets it sort out rendering any way it wants. But I've also succeeded in making a low-level API wrapper so that path (even though it's slightly more complicated) is a valid path to take, too, as long as feature set allows it (shader support is required for this to work).

As for common hierarchies, try something like this:

```
class SceneInfo {
    MeshList meshes;
    ParticleSystemList pslist;
    ...
}
class Renderer { function Render( SceneInfo* info ); }
class Game { SceneInfo info; Renderer renderer; }

```

# Answer
> 2 votes
I am guessing your `Vertex` class actually represents a vertex buffer (and not a collection of thousands of Vertex objects that make up your Mesh). When I started out making a low-level rendering engine, I had a `Mesh` class only require exactly one `IndexBuffer` and `VertexBuffer` class, because I didn't see a need where I would have to swap index buffers with a different Mesh after the Mesh is fully built. (This terminology reflects DirectX which I was using)

The buffers were initialized with separate `IndexLoader` and `VertexLoader` classes, which inherited a base `Loader` class. A `FileReader` class read the mesh file and spit out structures used by the Loaders. In hindsight this might have been overengineering it a bit, but I wanted to keep the loading stuff separate from the rendering.

A `Scene` pools the Meshes for updating and rendering. `SceneRenderer` has a reference to a scene, it can be swapped with a different Scene if you want several rendering layers going on.

I wanted to introduce some basic culling for the scene, so I kept both an ordered list and an unordered list of Meshes for pooling. Every Mesh created goes to the ordered list first, and the unordered list keeps pointers to the ones that needed to be drawed in that frame.

Insertion time to the ordered list was linear * log n I believe, because I used string handles for the Meshes ordered to make binary search possible. This made it possible to quickly access the Meshes that need to be drawn (in log n time) and copied to the unordered list. The SceneRenderer iterates through this list in linear time when the scene is drawn.

---
Tags: architecture, rendering
---


# Question
Title: strange behavior in Box2D+LibGDX when applying impulse
I have been playing around with Box2D and LibGDX and have been using a sample code from DecisionTreeGames as the testing ground. Now I have a screen with four walls and a rectangle shape, lets call it a brick. When I use **applyLinearImpulse** to the brick, it starts bouncing right and left without any pattern and won't stop!

I tried adding friction and increasing the density, but the behavior still remains the same. Here are some of the code that might be useful:

method for applying the impulse:

```
center = brick.getWorldCenter();
brick.applyLinearImpulse(20, 0, center.x, center.y);

```

Defining the brick:

```
brick_bodyDef.type = BodyType.DynamicBody;
brick_bodyDef.position.set(pos); // brick is initially on the ground
brick_bodyDef.angle = 0;
brick_body = world.createBody(brick_bodyDef);
brick_body.setBullet(true);
brick_bodyShape.setAsBox(w,h);
brick_fixtureDef.density = 0.9f;
brick_fixtureDef.restitution = 1;
brick_fixtureDef.shape = brick_bodyShape;
brick_fixtureDef.friction=1;
brick_body.createFixture(fixtureDef);

```

Walls are defined the same only their bullet value is set to false

I would really appreciate it if you could help me have a change this code to have a realistic behavior (i.e. when I apply impulse to the brick it should trip a few times and then stop completely).

---

Further info:

1. At first, the brick is standing still.
2. With an impulse to its right side, it slowly leans rightward.
3. the moment it touches the ground wall, it jumps back with a high speed. **It is like the ground is a trampoline**!!
4. from here on, it bounces very quickly.
5. In these jumps it rarely touches other walls.

# Answer
> 1 votes
It seems that **restitution** was at fault. When I set it to 0.5 everything worked fine.

# Answer
> 1 votes
First, it doesn't seem like your "brick" needs to be treated like a bullet, so setBullet(false). Now, where in your code are you applying the impulse? Take a close look at your game loop and make sure you're not applying different forces somewhere else. Also, turn on debugging so you can better see what's going on. Maybe your "brick" is bouncing off of other invisible objects making it appear to be moving randomly. Make sure to set all debug flags to true to look at everything.

---
Tags: box2d, libgdx
---


title: Adding delay between damage

text:
# Question
Title: Adding delay between damage
I have a bunch of enemies chasing my main-character, and if they intersect I want them to damage him and that's all good. The problem is that right now they damage him as long as they stand around him, every frame! and since it gets called every frame my character's HP reaches 0 almost instantly.

I've tried adding delay and I've tried a `timertask`, but can't get it to work.

This is the code I use to check for intersection:

```
private void checkCollision(Canvas canvas) {
    synchronized (getHolder()) {
        Rect h1 = happy.getBounds();
        for (int i = 0; i < enemies.size(); i++) {
            for (int j = 0; j < bullets.size(); j++) {
                Rect b1 = bullets.get(j).getBounds();
                Rect e1 = enemies.get(i).getBounds();
                if (b1.intersect(e1)) {
                    enemies.get(i).damageHP(5);
                    bullets.remove(j);
                }
                if(e1.intersect(h1)){
                    happy.damageHP(5);
                // this is the statement that needs some sort of delay, I want them to damage him every 2 seconds they intersect him.
                }

                if(enemies.get(i).getHP() <= 0){
                    enemies.get(i).death(canvas, enemies);
                    score.incScore(5);
                    break;
                }
                if(happy.getHP() <= 0){
                    score.incScore(-50);
                    //end-screen
                }
            }
        }
    }
}

```

If anyone knows the logic to do this please do tell.

# Answer
Just add a cooldown for any action that needs to be delayed. When the action is performed set the cooldown to a proper value and deduct the time in your update loop. Something like:

```
Class Entity
{
  const float COOLDOWN_TIME = 10; //in seconds

  private float cooldown = 0;

//...//

public void Update(float time)
{
  cooldown -= time;
}

public bool attack()
{
  if(cooldown <= 0)
  {
    bringThePain();
    cooldown = COOLDOWN_TIME;
    return true;
  }else{
    return false;
  }

}

}

```
> 5 votes

# Answer
This should be pretty easy to achieve. Just save a `System.currentTimeMillis()` for every enemy when he damages you, and check the difference to the current `System.currentTimeMillis()` if it is larger than an threshold you get damage and the enemy timer is newly set.

```
private void checkCollision(Canvas canvas) {
    synchronized (getHolder()) {
        long time = System.currentTimeMillis();
        Rect h1 = happy.getBounds();
        for (int i = 0; i < enemies.size(); i++) {
            for (int j = 0; j < bullets.size(); j++) {
                Rect b1 = bullets.get(j).getBounds();
                Rect e1 = enemies.get(i).getBounds();
                if (b1.intersect(e1)) {
                    enemies.get(i).damageHP(5);
                    bullets.remove(j);
                }
                if(e1.intersect(h1)){
                    if(time - enemies.get(i).getTime() > 2000) {
                        happy.damageHP(5);
                        enemies.get(i).setTime(time);
                    }
                }

                if(enemies.get(i).getHP() <= 0){
                    enemies.get(i).death(canvas, enemies);
                    score.incScore(5);
                    break;
                }
                if(happy.getHP() <= 0){
                    score.incScore(-50);
                    //end-screen
                }
            }
        }
    }
}

```
> 3 votes

---
Tags: 2d, android, collision-detection
---


# Question
Title: How to make my character slide (not bounce) off a slope
My character needs to slide and not bounce off a slope.

The solutions I found here use a Reflection vector, but they make my character bouncy when they run downwards a slope.

```
var reflectVector = normal.clone().multiplyScalar(-this.velocity.clone().dot(normal));
this.velocity.addSelf(reflectVector);

```

How can I make my character simply stick to the terrain when they walk?

# Answer
> 5 votes
Eliminate the normal component from the old velocity using vector projection to get the desired velocity. Assuming normal is a unit vector, the formula is:

```
desiredVelocity = oldVelocity - dot(normal, oldVelocity) * normal;

```

Applying gravity should accelerate the desired velocity, or if you just want constant speed, normalize it and scale as you wish.

You can also think this as a case of reflection. Reflection is `oldVelocity - 2 * dot(normal, oldVelocity) * normal;`. Here 2 can be replaced with (1 + e), where e is elasticy in the range \[0, 1\]. With 1 you get the perfect reflection and with 0 you get the formula above with your desired result. With a value between 0 and 1 you get small bounce.

# Answer
> 2 votes
here is pseudo code of one way it can be accomplished.

```
float speed = oldVelocity.Length();
tempVector = cross(oldVelocity, normal);
desiredVelocity = cross(normal, tempVector);
desiredVelocity.normalize();
desiredVelocity *= speed;

```

---
Tags: collision-detection, mathematics
---


# Question
Title: How exactly does XNA's SpriteBatch work?
To be more precise, if I needed to recreate this functionality from scratch in another API (e.g. in OpenGL) what would it need to be capable of doing?

I do have a general idea of some of the steps, such as how it prepares an orthographic projection matrix and creates a quad for each draw call.

I'm not too familiar, however, with the batching process itself. Are all quads stored in the same vertex buffer? Does it need an index buffer? How are different textures handled?

If possible I'd be grateful if you could guide me through the process from when SpriteBatch.Begin() is called until SpriteBatch.End(), at least when using the default Deferred mode.

# Answer
I have sort of replicated the behaviour of SpriteBatch in deferred mode for a cross-platform engine I'm working on, so here are the steps I have reverse engineered so far:

1. **SpriteBatch constructor:** creates a `DynamicIndexBuffer`, `DynamicVertexBuffer` and array of `VertexPositionColorTexture` of fixed size (in this case, the maximum batch size - 2048 for sprites and 8192 for vertices).

* The index buffer is filled with the vertex indices of the quads that will be drawn (0-1-2, 0-2-3, 4-5-6, 4-6-7 and so on).
    * An internal array of `SpriteInfo` structs is created, too. This will store temporal sprite settings to be used when batching.
2. **SpriteBatch.Begin:** internally stores the values of `BlendState`, `SamplerState`, etc. specified and checks if it has been called twice without a `SpriteBatch.End` in between.
3. **SpriteBatch.Draw:** takes all the sprite info (texture, position, color) and copies it to a `SpriteInfo`. If the max batch size is reached, the entire batch is drawn to make room for new sprites.

* `SpriteBatch.DrawString` just issues a `Draw` for each character of the string, taking into account kerning and spacing.
4. **SpriteBatch.End:** does the following operations:

* Sets the render states specified in `Begin`.
    * Creates the orthographic projection matrix.
    * Applies the `SpriteBatch` shader.
    * Binds the `DynamicVertexBuffer` and `DynamicIndexBuffer`.
    * Performs the following batching operation:
```
    startingOffset = 0;
    currentTexture, oldTexture = null;

    // Iterate through all sprites
    foreach SpriteInfo in SpriteBuffer
    {
        // Store sprite index and texture
        spriteIndex = SpriteBuffer.IndexOf(SpriteInfo);
        currentTexture = SpriteInfo.Texture;

        // Issue draw call if batch count > 0 and there is a texture change
        if (currentTexture != oldTexture)
        {
            if (spriteIndex > startingOffset)
            {
                RenderBatch(oldTexture, SpriteBuffer, startingOffset,
                            spriteIndex - startingOffset);
            }
            startingOffset = spriteIndex;
            oldTexture = currentTexture;
        }
    }

    // Draw remaining batch and clear the sprite data
    RenderBatch(currentTexture, SpriteBuffer, startingOffset,
                SpriteBuffer.Count - startingOffset);
    SpriteBuffer.Clear();

```
5. **SpriteBatch.RenderBatch:** executes the following operations for each of the `SpriteInfo` in the batch:

* Takes the position of the sprite and calculates the final position of the four vertices according to the origin and size. Applies existing rotation.
    * Calculates the UV coordinates and applies specified `SpriteEffects` to them.
    * Copies the sprite color.
    * These values are then stored in the array of `VertexPositionColorTexture` elements previously created. When all sprites have been calculated, `SetData` is called on the `DynamicVertexBuffer` and a `DrawIndexedPrimitives` call is issued.
    * The vertex shader only performs a tranform operation, and the pixel shader applies the tinting on the color fetched from the texture.
> 43 votes

# Answer
Just want to point out that the XNA SpriteBatch code has been ported to DirectX and released as OSS by a previous member of the XNA team. So if you want to see exactly how it works in XNA, the latest version of the XNA SpriteBatch as native C++ can be found on this GitHub repo: `.h` & `.cpp`

A DirectX12 version is also available: `.h` & `.cpp`
> 14 votes

---
Tags: xna, spritebatch
---


title: Intersection of player and mesh

text:
# Question
Title: Intersection of player and mesh
I have a 3D scene, and a player that can move about in it.

In a time-step the player can move from point A to point B. The player should follow the terrain height but slow going up cliffs and then fall back, or stop when jumping and hitting a wall and so on.

In my first prototype I determine the Y at the player's centre's X,Z by intersecting a ray with every triangle in the scene. I am not checking their path, but rather just sampling their end-point for each tick. Despite this being Javascript, it works acceptably performance-wise.

However, because I am modeling the player as a single point, the player can position themselves so that they are half-in a cliff face and so on. I need to model them as as a solid e.g. some cluster of spheres or a even their fuller mesh. I am also concerned that if they were moving faster they might miss the test altogether.

How should I solve this?

# Answer
> 5 votes
Have a collision mesh that you don't render and is smaller than the room by the maximum diameter of the player. In this case the collision mesh could be much less detailed than then visible model helping performance.

---
Tags: collision-detection, geometry
---


# Question
Title: Having the same texture data in different ID3D11Texture2D
Sorry if this has been answered elsewhere - I'm rather new to DX. My question concerns conservation of resources - specifically textures in VRAM. I assume that upon returning from a call to CreateTexture2D, a copy of any textures data supplied has been copied elsewhere, likely VRAM. Does DX11 have any facility for having multiple ID3D11Texture2D objects which point to the same data?

This might at first seem silly, but imagine a ID3D11Texture2D which is an array of textures. In one material, an artist has chosen to blend three identically sized maps, saved on disk as A.dds, B.dds, and C.dds. Then imagine they have another material which also uses three maps, but this time A.dds, B.dds, and D.dds.

The shader code knows the diffuse texture is a texture array, and also has the number of layers baked (three in each case). I would essentially like to set up just two ID3D11Texture2D objects, one for each material, but I don't want to waste VRAM for two identical copies of A.dds and B.dds.

I could use explicit texture arrays, of course, but this reduces the number of resources available to the shader and can complicate code somewhat more than would otherwise be needed.

# Answer
I don't *think* that this is possible. What I would do in this case is have either 4 different textures sourced from A, B, C and D, or else a single array with 4 slices (A, B, C and D again) and include the array slices to use in the material definition.
> 3 votes

# Answer
I'm pretty sure D3D11 does not allow multiple ID3D11Texture2D objects to point to the same pixel data in memory. However, you can certainly have multiple ID3D11ShaderResourceView objects point to the same ID3D11Texture2D object, which addresses the same core concern. Using your example above, you could have six unique ShaderResourceView objects and four unique Textures set up as follows:

* Material1.pSRV1 points to Texture A
* Material1.pSRV2 points to Texture B
* Material1.pSRV3 points to Texture C
* Material2.pSRV1 points to Texture A
* Material2.pSRV2 points to Texture B
* Material2.pSRV3 points to Texture D

Memory-wise, SRVs are relatively lightweight objects compared to the Textures they refer to.
> 2 votes

---
Tags: directx, textures, directx11
---


# Question
Title: Collision detection doesn't work for automated elements in XNA 4.0
I have a really weird problem. I made a 3D simulator of an "assembly line" as a part of a college project. Among other things it needs to be able to detect when a box object passes in front of sensor. I tried to solve this by making a model of a laser and checking if the box collides with it. I had some problems with BoundingSpheres of models meshes so I simply create a BoundingSphere and place it in the same place as the model. I organized them into a list of BoundingSpheres called "spheres" and for each model I create one BoundingSphere. All models except the box are static, so the box object has its own BoundingSphere (not a member of the "spheres" list). I also implemented a picking algorithm that I use to start the movement. This is the code that checks for collision:

```
if (spheres.Count != 0)
        {

            for (int i = 1; i < spheres.Count; i++)
            {
                if (spheres[i].Intersects(PickingRay) != null && Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton)
                {
                    start = true;
                    break;
                }
                if (BoxSphere.Intersects(spheres[i]) && start)
                {
                    MoveBox(0, false);//The MoveBox function receives the direction (0) and a bool value that dictates whether the box should move or not (false means stop)
                    start = false;
                    break;
                }
                if (start /*&& Microsoft.Xna.Framework.Input.ButtonState.Pressed == Mouse.GetState().LeftButton*/ && !BoxSphere.Intersects(spheres[i]))
                {
                    MoveBox(0, true);
                    break;
                }

            }

```

The problem is this: When I use the mouse to move the box (the commented part in the third if condition) the collision works fine (I have another part of code that I removed to simplify my question - it calculates the "address" of the box, and by that number I know that the collision is correct). But when I comment it (like in this example) the box just passes trough the lasers and does not detect the collision (the idea is that the box stops at each laser and the user passes it forth by clicking on the appropriate "switch"). Can you see the problem? Please help, and if you need more informations I will try to give them. Thanks

# Answer
> 0 votes
This is the code that works properly:

```
        if (ButtonState.Pressed == Mouse.GetState().LeftButton)
        {
            start = true;
        }
        if (start)
        {
         MoveBox(0,true);
        }
        for (int i = 1; i < spheres.Count; i++)
        {
            if (BoxSphere.Contains(spheres[i])== ContainmentType.Contains)
            {
                start = false;
            }
        }

```

# Answer
> 1 votes
It seems like you may not be hitting your `MoveBox` method if you hold down your Left Mouse Button since the statement keeps breaking. An alternative would be to check to see if the mouse is pressed after we check to see if there is a collision.

```
if(spheres.Any())
{
    var mousePressed = ButtonState.Pressed == Mouse.GetState().LeftButton;
    for (int i = 1; i < spheres.Count; i++)
    {
        if(!start)
            var sphereIntersects = spheres[i].Intersects(PickingRay) != null;
            if (sphereIntersects && mousePressed)
            {
                start = true;
                break;
            }
        }
        else
        {
            if(!mousePressed)
            {
                start = false;
                break;
            }
            var intersects = BoxSphere.Intersects(spheres[i]);
            if (intersects)
            {
                MoveBox(0, false);
                start = false;
                break;
            }
            else
            {
                MoveBox(0, true);
                break;
            }
        }
    }
}

```

# Answer
> 0 votes
If the `spheres[i].Intersects(PickingRay) != null` check succeeds, and your pressing the mouse button, you set `start = true` and then promptly exit the for loop.

The next time the for loop is called `start` will presumably still be true, but the only way it can get to `BoxSphere.Intersects(spheres[i])` is if the ray intersection *fails* (or you let go of the mousebutton first).

This means that the only box that it can try to pick, is one that does not intersect with the ray (since if it does it will break the for loop).

---

It also just occured to me that your going through the list starting at `i=1` lists in C# start at index 0, if your list (as mentioned in comment) only hold one item it would simply skip over that single box.

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


# Question
Title: making a box2d body move along a Bezier curve/ arc path
I have been trying to make a box2d body move along a Bezier curve/ arc path. Most of the posts I've seen recommend an approach of manipulating SetLinearVelocity and SetTransform to arrive at an arc-like movement. I don't think testing linear velocity values on a try and error basis would help. I would appreciate any help solving this problem. Thanks.

# Answer
If you don't need to worry about stuff running into it simply use `Body.SetPosition()`.

If you do then make sure its a kinematic body so its not bumped off course. You should know the time delta the physics engine is going to be updated by. So we can use that to find a direction and velocity that will cause us to be where we want to be after the step has occurred.

I haven't slept in about 24 hours so hopefully I have this right.

```
Vector3 travelThisStep = (Target - Body.GetPosition()); //How much we need to travel to arrive at our destination
float velocity = travelThisStep.Lenght() / TimeStep; //Distance to travel / Time to travel said distance
travelThisStep.normalize();
Vector3 velocity = travelThisStep * velocity;
Body.SetLinearVelocity(velocity);

World.Step(TimeStep);

```
> 2 votes

---
Tags: physics, box2d, curves
---


# Question
Title: Multiple game frames in construct 2 for new levels?
Hi there I'm new to Construct and have tried out a few platformer tutorials. I'm getting to grips with setting variables and collisions, I'm now at the stage where I want to start adding new levels. What the best way to effectively go to a new level, I know in flash this would be a new frame on the timeline, what would you do in construct 2?

# Answer
> 3 votes
Use the System object's 'Go to layout' action.

---
Tags: html5, construct-2
---


title: how to set usermassdata of dynamic body

text:
# Question
Title: how to set usermassdata of dynamic body
How to set the user mass data of dynamic body in andEngine. My problem is that in my game when i increase the speed of running player, the player on jump cover very long distance with x-axis. This distance changes with the speed. Any solution please..

# Answer
> 2 votes
For setting mass data of dynamic body following code can help you.

```
MassData data =  bombBody.getMassData();
data.mass = 10f;
bombBody.setMassData(data);

```

---
Tags: android, andengine
---


# Question
Title: AndEngine: How to add multiple fixtures into body?
I want to create a custom body which have very random shape like a table. So how to add/combine multiple fixtures into a body?

# Answer
> 1 votes
You have to use physics editor and using that you have to generate xml file which contains the fixture and body information. Using parsing you have to create PolygonShape, create a new fixture and assign it to the body.

```
for (int l = 0; l < size; l++)
    vector2s[l] = vectorList.get(l);

PolygonShape polygonShape = new PolygonShape();
polygonShape.set(vector2s);
FixtureDef fixtureDef = new FixtureDef();
fixtureDef = PhysicsFactory.createFixtureDef(1, 0, 0.8f,
               false, Constants.CATEGORYBIT_BOMB,
                Constants.MASKBIT_BOMB, (short) 0);
fixtureDef.shape = polygonShape;
bombBody.createFixture(fixtureDef);

```

---
Tags: android, andengine
---


# Question
Title: Why are triangle fans not supported in Direct3D 10 or later?
As covered in the documentation, triangle fans not supported in Direct3D 10 or later.

Why? Are there inherent drawbacks to working with triangle fans?

# Answer
> 16 votes
For well over a decade hardware vendors have been pushing triangle strips, indexed triangle lists and indexed triangle strips as the fastest primitive types to use. Why? Strips have better cache locality (reusing the last 2 verts submitted instead of having to continually jump back to the first one) and indexing allows hardware vertex caches to actually work, as well as being more effective for eliminating duplicate verts.

If all hardware vendors say "do it this way and you're going to be faster" then there's a pretty good chance that if you do it this way you actually will be faster.

So D3D10+ just formalizes this; if that's the fast path then that's the path you're going to use and other paths won't exist. This is in keeping with one of the design philosophies of D3D10+, which is to put you onto the fast path and keep you there.

# Answer
> 4 votes
I do not know how much this actually affects the development but as with any such changes, it's been told that they will let driver developers write better drivers. The complexity of GPU drivers is amazing but I'm not sure if this exact change will help much.

In either case, it's possible to replace triangle fans for most of your needs (like convex polygon rendering) with strips, often with better results.

```
// A simplified API interface is presented for the purposes of having readable pseudocode
// Push( pos ) - pushes position data to make a new vertex
// TRIANGLE FANS:
for( i = 0; i < vertices.count; ++i )
    Push( vertices[ i ] );

// TRIANGLE STRIPS:
for( i = 0; i < vertices.count; ++i )
{
    if( i % 2 == 0 )
        vertex = i / 2;
    else
        vertex = vertices.count - 1 - i / 2;
    Push( vertices[ vertex ] );
}

```

EDIT: forgot to mention - if you need to change winding order - just reverse the test in that "if" (== to !=).

# Answer
> 2 votes
(This particular question warrants an opinion answer:)

Subjectively, I'd say its architecture astronauticism. OpenGLES also threw-out lots of stuff to make it 'less complex' whilst actually just pushing complexity onto each and every developer with legacy code instead.

Of course, even when the hardware doesn't support it natively it would have been trivial to provide compatibility with people sequencing triangle fans by converting them to strips or triangles.

WebGL run-times and such have to keep track of validated buffers and such all the time, and drivers could *easily* manage people sending them fans despite them not supporting it.

So the whole throwing out of FFP and such is just a big annoyance IMO.

---
Tags: xna, directx10
---


title: 2D basic map system

text:
# Question
Title: 2D basic map system
i'm currently coding a 2D game in Java, and I would like to have some clues on how-to build this system :

the screen is moving on a grander map, for instance, the screen represent 800\*600 units on a 100K\*100K map.

When you command your unit to go to another position, the screen move on this map AND when you move your mouse on a side or another of the screen, you move the screen on the map.

Not sure that i'm clear, but we can retrieve this system in most RTS games (warcraft/starcraft for example).

I'm currently using Slick 2D.

Any idea ?

Thanks.

# Answer
> 2 votes
As was said in the comments, you need to handle a camera, which in 2d is just an offset for your render method.

For exemple if you had a call like
MyObject.draw(x, y);
You replace it with
MyObject.draw(x + offsetx, y + offsety);

Then all you need to do is to modify the offset when the user uses the mouse or when a unit is moved.

# Answer
> 0 votes
You need some sort of a viewport into the larger area. Then, when the viewable area is changed you will need to draw it based on what should be displayed there (you can obtain this information from a database, for example -- in particular, PostgreSQL has some specialized indexing features available that are optimized for the needed types of queries).

PostgreSQL (free and open source)
http://www.postgresql.org/

You'll also want to make sure the areas that are no longer needed will not remain in memory for too long, otherwise a player who likes to explore with the **"run 20 times faster" boots** will fill up their computer's memory quickly.

One problem you might experience will be that as you load the tiles that are in view, the player will see blanks at first that get filled in shortly after. One strategy you can use to resolve this problem is to also load tiles that are slightly out of view; that way, when the player moves, those next tiles will already be pre-loaded while your code starts loading other slightly-out-of-view tiles in preparation for the next moves (no matter what direction the player goes since you can't accurately predict this anyway, especially if the player suddenly sees a **dangerous giant spider that likes to eat speed-boosting-boots**).

The beauty of using a database to load up on the nearby areas is that you have the option of increasing the size of your world far beyond 100k-by-100k.

For your database, you'll need to have two columns that represent the X and Y positions. If your player can move their character up (e.g., onto a rooftop) or down (e.g., into a dungeon), then you'll need to have a third column that represents the Z position as well.

# Answer
> 0 votes
If you're new to game development, I would recommend that you take a look at Tiled. Tiled is a free tile based level editor, that supports orthogonal and isometric map formats.

Tiled Page

Slick has a class, TiledMap, that can load the tmx format generated by Tiled. You can draw the background of the map simply with tiledmap and then render your units, building etc. on top of it.

You can find the examples in the Slick2d wiki: Tiled WIKI Page

---
Tags: 2d, java, maps, slick
---


# Question
Title: Why does my health bar disappear whenever my character takes damage?
I'm making a health bar for my game that looks like this:

```
public void healthBar(Canvas canvas)
{
    float healthScale = happy.getHP() / happy.getMaxHP();
    Rect rect = new Rect(20, 20,(120 * (int)healthScale), 40);
    Paint paint = new Paint();
    paint.setColor(Color.RED);
    canvas.drawRect(20, 20, 220 * healthScale, 40, paint);
}

```

This is called every time my game renders. When the game starts it's where I want it, but as soon as my character ("happy") takes any damage, it dissapears. And I know that his hp only gets subtracted by 5 every time he gets hit. So this should not happen?

Example:

```
@Startup: happy.getHP() == 100, happy.getMaxHP == 100.
when damaged HP -=5, -> happy.getHP() == 95 -> healthscale == 0,95 -> 220 * 0,95 == new width for Rect(?)

```

# Answer
> 7 votes
I have a good feeling that `getHP()` and `getMaxHP()` are returning integral values (int, short, long, byte, etc). If so, they should be cast to floating point numbers (float or double) before dividing otherwise integer division will take place, causing the health scale to be either 1 or 0 and nothing in between. This also goes for this: `120 * (int)healthScale`. If you truncate a floating point number: 0.95, you'll lose everything after the decimal place, resulting in 0.

As a side note: It's worth using a debugger to narrow down errors like this one. If you don't have a debugger, find one. If you can't find one, use the poor man's debugger: use printouts.

---
Tags: android, graphics, html-canvas
---


# Question
Title: What is the best way to store meshes or 3d models in a class
I am wondering, how I should store my mesh into memory after loading it from whatever file. I have Questions floating in my head:

1. Should a mesh could have sub meshes or does the 3d model just store a list of meshes all on the same level
2. Is there one material assigned to one mesh 1:1?
3. What do I have to consider, if I want to store skeletal animations?

Btw it's a OpenGL|ES2 iOS game using GLKit.

I came up with some basic struct types: (But I think they are way to simple and I need to add padding or change the vector3 to vector4.)

```
typedef union _N3DShortVector2 {
    struct { short x, y; };
    struct { short s, t; };
    short v[2];
} N3DShortVector2;

typedef union _N3DShortVector3 {
    struct { short x, y, z; };
    struct { short r, g, b; };
    struct { short s, t, p; };
    short v[3];
} N3DShortVector3;

typedef GLKVector3 N3DFloatVector3;

typedef struct _N3DMeshRecordSV3 {
    N3DShortVector3 v1, v2, v3;
} N3DMeshRecordSV3;

typedef struct _N3DMeshRecordSV3FN3ST2 {
    N3DShortVector3 v1, v2, v3;
    N3DFloatVector3 n1, n2, n3;
    N3DShortVector2 t1, t2, t3;
} N3DMeshRecordSV3FN3ST2;

```

# Answer
> 2 votes
1. Ultimately, each mesh is a collection of OpenGL primitives (triangles, triangle strips, etc) that form a 3D model. You'll want a level to include a variety of meshes, so you can address them each separately.
2. To my knowledge, each mesh can only have one material, although generally one would use texturing to get around this (I.e. set up a texture to color each part of the model as you like). A texture or material can be reused on multiple models.
3. Sorry, I don't have experience with this.

To answer your original question, this depends slightly on what you are using the models for. If your models will be rigid, meaning you will not change each vertex individually, and you will render many frames with the same model, you will achieve the best performance not by storing the models in your class, but in vertex buffer objects (VBOs). This basically means that the models are stored in GPU memory instead of CPU memory, minimizing GPU to CPU transfers and greatly improving rendering performance. A good tutorial on OpenGL ES vertex buffering is available at http://www.learnopengles.com/android-lesson-seven-an-introduction-to-vertex-buffer-objects-vbos/ (This is for android, but the code will be similar).

Regardless of whether you decide to store your mesh on the CPU or GPU, your performance will be best if you interweave vertex, normal, and UV coordinates, use the smallest data primitives that provide the accuracy needed for your application, and align your data structure to the memory. http://developer.apple.com/library/ios/documentation/3DDrawing/Conceptual/OpenGLES\_ProgrammingGuide/TechniquesforWorkingwithVertexData/TechniquesforWorkingwithVertexData.html

# Answer
> 0 votes
1 and 2: Sounds like your 3D model is what contains transformation of an object and the mesh data. If you want want hierarchical objects, your 3D models should have child models. Meshes themself don't need hierarchy, a flat list is enough. Each part of a model should allow own material, so each mesh should have a material assigned. However even in that case it's a good idea to allow meshes to share the same vertex data, i.e. vertex buffers inside a single 3D model. Index buffers are unique for each mesh.

You can also add one level of indirection, where the list of meshes can be shared between different 3D models. You could rename the meshes to mesh clusters and the list of meshes as the mesh itself. In that case the 3D models could share meshes.

---
Tags: opengl-es, ios, 3d-meshes
---


# Question
Title: How do I efficiently generate chunks to fill entire screen when my player moves?
In my game I generate chunks when the player moves. The chunks are all generated on the fly, but currently I just created a simple flat 8X8 floor. What happens is that when he moves to a new chunk the chunk in the direction of the player gets generated and its neighboring chunks.

This is not efficient because the generator does not fill the entire screen. I did try to use recursion but its not as fast as I would like it to be.

My question is what would be an efficient way of doing so? How does minecraft do so? When I say this I mean just the way it PICKS which chunks to generate and in what order. Not how they generate or how they are saved in regions, just the order/way it generates them.

I just want to know what is a good way to load chunks around the player.

# Answer
> 4 votes
If I understand you correctly...

Could you not just load the chunks in a spiral around the player? Each time you check for the next chunk to load you could start whole spiral process again (or come up with a better way to find 'missing' chunks) as this will loads the correct chunks whilst the player moves.

---
Tags: java, procedural-generation, minecraft-modding
---


# Question
Title: OpenGL ES 2.0: Repository of Quality Shaders
Could I kindly ask, to suggest me a repository of **high quality OpenGL (OpenGL ES 2.0) vertex and fragment shaders**, please?

I am looking for **pixel based ligting shaders** (such as **phong**) and simmilar. It would be nice to see more of them, to be able to choose between quality vs shader performance.

# Answer
> 16 votes
Shaders of any complexity aren't generally the kind of thing you can download and drop in to your project like interchangeable cogs. Typically the more interesting effects require a fair bit of coupling to the CPU-side rendering subsystem in order to achieve their results. The same is generally true of performance -- performance tradeoffs with respect to accuracy and quality over instruction count or pipelining tend to be rooted in application-specific requirements.

As a result there really isn't much in the way of the kind of repositories you are thinking of. The GPU Gems books offer a good collection of cookbook-style descriptions of techniques with both game and shaded code examples that you may want to take a look at, though. So do the Shader X books.

# Answer
> 13 votes
Not much, but at least a couple of basic shaders to get started with can also be found between my open sorce engines files:

the .vsh files contain the vertex shaders and the .fsh files the fragment shaders, but I guess thats selfexplaining...

On current mobile hardware, you should do as much as possible within the vertex shader and the trick for great looking and fast games is to write many very specialized shaders doing always just exactly what is needed to make something look the way it is meant to. At least thats my experience with my iPhone 3GS, which features the same gpu as the iPhone 4 but has less pixels to do deliver data for. This is most probably already much better with tegra 2 and even better with apples A5 chip, but for now, this means that you should not try to port shaders for desktop gpus to mobile phones and expect a great performance :P This also means that fullscreen effects, especially on devices with a high resolution display tend to be slow.

Hope this also helps a bit :).

# Answer
> 9 votes
might snatch some of the arcane knowledge from here http://glslsandbox.com/

# Answer
> 4 votes
When I was looking how to implement fog under OpenGL ES 2.0, I have found link to OpenGL ES 2.0 backward compatible project implementing functionality, which is not in OpenGL ES 2.0, For example fog, per vertex, per fragment(pixel) shading. You can look directly into shaders source.

I have been implementing per fragment lighting too, modifying this example created by ClockworkCoders (not OpenGL ES 2.0).

You can also take a look on these great tutorials by lighthouse3D

# Answer
> 1 votes
The AMD RenderMonkey package contains very advanced shaders for OpenGL ES 2.0 among the sample files.

Take a look especially at the Renderman shader sample in the GLES samples directory, which provides a more-or-less bare-bones OpenGL ES 2.0 shader that might serve as a good starting point. And might also give you a good idea as to why there aren't many cut-and-paste examples of good shaders out there. The basic problem: that shaders are tightly coupled with OpenGL ES server configuration, and the models that get rendered on them. Still. The Renderman shader is an excellent starting point, if you can pry it loose from the REnderMonkey tool.

# Answer
> 1 votes
Take a look at GPUImage (https://github.com/BradLarson/GPUImage), its probably the most complete collection of shaders I have found on the web so far. Since they are all designed to work with GPUImage, they all share the same structure, so if you adapt the same structure in your application/game you should be able to quickly import a number of different effects.

Cheers!

---
Tags: shaders, opengl-es, glsl
---


# Question
Title: Collisions between moving ball and polygons
I know this is a very typical problem and that there area a lot of similar questions, but I have been looking for a while and I have not found anything that fits what I want.

I am developing a 2D game in which I need to perform collisions between a ball and simple polygons. The polygons are defined as an array of vertices.

I have implemented the collisions with the bounding boxes of the polygons (that was easy) and I need to refine that collision in the cases where the ball collides with the bounding box. The ball can move quite fast and the polygons are not too big so I need to perform continuous collisions.

I am looking for a method that allows me to detect if the ball collides with a polygon and, at the same time, calculate the new direction for the ball after bouncing in the polygon.

(I am using XNA, in case that helps)

# Answer
The sounds similar to something I was working with and there is no simple answer that could be confined to one post that covers everything. In my opinion you should look into something called separate axis theorem (SAT).

When I was trying to implement it the best walk through I could across was this: http://dl.dropbox.com/u/22121701/Polygon%20collision.rar

It starts with first principles and eventually works it's way up to a full blown rigid body simulator. I only followed it as far as having it accommodate fast movements. It's written for C++, so it would help if you knew C++ however I didn't know it and still don't know it when I implemented it in XNA.

If you can't make heads or tails of it then you may want to look for something a bit more specialised for your case (this is a VERY general approach and will work for most things). If you're REALLY struggling I would be happy to give you MY implementation of it, but there are few comments and it was done when I was learning C#/XNA so it may not be efficient.
> 2 votes

# Answer
Why not simply use the edges and use line to line collision? One line is the distance traversed by you and one is an edge of the poly. Extend each poly line by the width of your sphere in each direction to account for the size of the sphere. Also after a collision has occurred you have all the angle info you'll need to determine the angle of reflection.

Line/Line Collision
> 1 votes

---
Tags: xna, 2d, collision-detection, physics, collision-resolution
---