title: Vertex shader are evil for performance?

text:
# Question
Title: Vertex shader are evil for performance?
I found that the vertex shaders are sometimes very useful, especially because they can generate geometries and extract and use a lot of informations from just 1 image.

The problem is that my project still isn't that big and looking to bigger project or just to commercial games, seems like the vertex shaders are rarely used.

Am I wrong or the pixel shaders are much more used than the vertex shaders?

This has something to do with performance issues and compatibility issues? What about some possible bottleneck like the memory controller/CPU ?

# Answer
> 11 votes
This seems like a big misunderstanding on your part, and I think the comparison doesn't make much sense because in general they serve different purposes:

* Vertex shaders are executed once for every vertex in the geometry, and are used to modify or add new information to those vertices. For example, they can be used to slightly modify the position of the vertex, or calculate a light value for that vertex.
* Pixel shaders on the other hand are executed once for every pixel/fragment that covers that geometry, and are used to determine what the final color for that fragment should be.

It might be true that pixel shaders are used a lot more than vertex shaders, but that's because there are a lot of effects that require that extra control over the color of each fragment that are only possible with pixel shaders, e.g. things such as bump mapping, or any full screen post processing effect. Vertex shaders have different uses, and are used mostly for other types of effects such as creating waves in the ocean, and other types of distortions.

As for your performance question, if you can implement the exact same effect, with same visual quality either on vertex shader or pixel shader, then I think the vertex shader version will probably be a lot *faster*, because the number of vertices will usually (always?) be a lot smaller than the number of pixels covered by the primitive.

---
Tags: shaders, performance, vertex, geometry-shader
---


# Question
Title: How to move a b2Body explosively to a new Location
I am building an Game based on Box2d with the following basic structure:

The Box2d World itself does not have any Gravity and is filled with some bodies (sheres and simple polygons) of more or less the same size. The user can select on of them and if he clicks on the free space, the selected body should be moved onto the "point of click".

The movement should be explosive, what the use of b2Body.ApplyImpulse suggests, but also stop quickly when the point is reached.

This leads me to two problems:

Which method should i use: ApplyImpulse or ApplyForce? How could I calculate the right vector of the impulse, if you would use this method?

How could I correct the body's way if it collides with another?

Greetings Philipp

# Answer
> -1 votes
I'm not sure I understand the term "explosively" correctly, but if you want the move to be immediate and not quite over a frame.. have a look at SetTransform. You can find this in this section under "Position and Velocity".

# Answer
> 1 votes
An explosion consists of an impulse applied directly by the detonation (moving at supersonic speed) and a force that is applied over time by the pressure wave (moving at subsonic speed). If have a high order explosion(C4 etc), also called detonation, then you're mainly going to notice the impulse part. If you have a low order explosion (gunpowder, fuel etc), also called deflagration, then you are going to have pretty much only the later. If you are interested (and just who is NOT interested in explosions??) check out the wikipedia articles on detonation and deflagration That's enough real world physics stuff.

For your game I think you'll do well enough only by applying impulse. I've never used box2D but you should probably do nothing special to the bodies affected by the explosion once you have applied the impulse, just let the physics engine handle that.

EDIT: Or maybe I misunderstood your question entirely, just got carried away when I saw explosive movement :)

---
Tags: box2d
---


# Question
Title: How do you stop an Ogre PSSM shader from creating unwanted or blocky shadows due to large 'world size'
I'm using PSSM Shadows in Ogre 1.6.4 and I have a scene which is around 100m square.

I also create a flat ground texture which does not cast shadows and extends off towards the horizon, but when I do this, and the *Sun* light source goes towards the horizon at dawn or dusk, then I get extra shadows at the edges of some of my objects. It's like some kind of self shadowing.

I'm using custom shaders, but the Ogre PlayPen PSSM shader also goes beserk in this environment too.

I've read that the *world size* can affect texture shadow mapping.

Is there a technique to allow this ground area to exist (ie my *world* to be big) without affecting my PSSM shadowing?

(btw - my derived light direction is correctly normalized!)

# Answer
> 2 votes
Well here's what I actually did to resolve my problem:

It so happens that the far terrain that is making my world so large doesn't need to receive shadows, and as I mentioned above, neither is it a shadow caster.

Now in Ogre it seems that although you can tell an object not to cast shadows, you can't tell it not to receive shadows.

But what you *can* do is put the relevant objects in a separate rendergroup in the render queue, and then tell that renderQueue group not to form part of any of the shadow processing or setup:

```
sceneManager->getRenderQueue()->getQueueGroup(myID)->setShadowsEnabled(false);

```

This then fixes my problem where these non casting, non receiving planes seem to be affecting the shadows in the rest of my scene - and maybe ever so slightly improves performance too.

If I'd understood all this a bit more I'd probably have known that's what I should be doing anyway, but there you go!

# Answer
> 1 votes
I don't know about Ogre specifically, but a very common way to deal with shadow resolution in a large world is cascaded shadow maps. This technique uses multiple shadow maps, with high-resolution ones that cover only the area near the camera and lower-resolution ones for areas farther from the camera. There are some subtleties in avoiding "swimming" artifacts as the camera moves around, but if implemented correctly CSM can be very effective. I don't know whether Ogre already has CSM technology built into it or whether you would need to implement it yourself, but it's worth looking into.

---
Tags: ogre, shadows
---


title: MonoGame for iOS - getting started

text:
# Question
Title: MonoGame for iOS - getting started
I can't find any clear directions on how to get started. I only see a Windows installer for MonoGame but what little documentation I've found seems to say you install it on the Mac and do the work there. If someone could simply tell me which parts go where that would be a big help.

# Answer
> 1 votes
Using MonoDevelop, you can get started. What really helped me get started though was taking a look at the StarterKits. If you look here and just download the repository you'll find lots of nice iOS examples. Those should get you on your way!

In terms of setting up your environment, just install MonoDevelop on your Mac and checkout (or just download a ZIP of) this repo. Build in MonoDevelop. You should make a folder called StarterKits and place the previous repo in this directory.

# Answer
> 0 votes
On their site in the downloads section, if you look just above the windows installer download link, there is just a zip file with the project, you just download and extract that. Then you can open up in MonoDevelop

# Answer
> 0 votes
That is because it is based on MonoTouch. You can find general MonoTouch guidance here: http://docs.xamarin.com/ios

---
Tags: ios, monogame
---


# Question
Title: Tile based platformer, using larger tiles?
So for my tile based platformer, It has a grid of tiles Occupying 1x1 block for each one.

However, What if I want larger tiles? Maybe doors, tables, etc. They wouldnt fit in a 1x1 tile, so what I need is a way to let any method trying to access my tile array, know that a tile could be occupying a larger space.

I can already render larger objects correctly, But I simply am looking for a method to let evrything else know a larger tile is there, So I can perform collision on it, and so other tiles cant be placed on it.

# Answer
> 1 votes
So, if you have objects that are larger and you wish to fill a simple collision map (perhaps for sanity checking... you'll want to consider the use of bounding rectangles if that suits your game) let us take a look at how one might implement this using a simple 2D array.

Let us use the example for our collision map:

```
0, 0, 0, 0
0, 0, 0, 0
0, 1, 1, 0
0, 1, 1, 2

0 = null
1 = object with ID 1
2  = object with ID 2

```

If we use this simple model, upon placing the object we can fill all adjacent nodes in the array that are occupied with the object width and height. When checking for collisions, you can simply check for a 0.. anything else can be assumed to need further checking. If some objects can be passed through, either just write a 0 there to begin with... (you might be able to get away with this) or query for the object from your entity lookup table and check for more information.

# Answer
> 2 votes
I plan to solve that by aggregating larger objects out of simple tiles.

For example, if you want your door to be 3\*5 tiles big, you could construct it like this:

```
000
010
010

```

`1` is a tile that, upon collision, leads you to another map (specified in the tile-descriptor) and `0` is simply a pretty picture.

# Answer
> 1 votes
My first idea for a solution would be to have objects that can span several tiles and then have a reference to that object in the tile so you know it's a door or whatever in case you need to open it later. So if an object spans 3x3 tiles when you add a reference to it to all adjacent tiles as well. Then you know that all those tiles contain that specific door with that state (open/closed, hitpoints etc).

If you want to go all crazy maybe you could look at using quadtrees for very large worlds but that might be a later issue. Never done that myself, it just seems really really cool :)

---
Tags: xna, c#, 2d, tiles, platformer
---


# Question
Title: UDK weapon on first person not showing up
I've been following this tutorial http://www.moug-portfolio.info/udk-weapon-basics/

all my code is the same as the page...

except here

```
DefaultPropeties
{
Begin Object Name=GunMesh
    SkeletalMesh=SkeletalMesh'WP_LinkGun.Mesh.SK_WP_Linkgun_3P'
    HiddenGame=FALSE
    HiddenEditor=FALSE
end object

Mesh=GunMesh
Components.Add(GunMesh)
}

```

i had to replace begin object for this

```
Begin Object Class=SkeletalMeshComponent Name=GunMesh

```

i think i might have forgot to add a model/skeletal so i dont have anywhere to attach the weapon to? How can I do that??

Can some UnrealScript expert please look to it for me or give me a valid tutorial link for creating a custom weapon?

thank you very much

# Answer
> 1 votes
I found out that I was missing a model to attach the weapon to like I suspected

just added this code to my default props on my pawn class and everything went ok

```
Begin Object class=SkeletalMeshComponent Name=SkeletalMeshComponent0
    SkeletalMesh=SkeletalMesh'CH_IronGuard_Male.Mesh.SK_CH_IronGuard_MaleA'
    AnimSets(0)=AnimSet'CH_AnimHuman.Anims.K_AnimHuman_BaseMale'
    AnimTreeTemplate=AnimTree'AT_CH_Human'
    PhysicsAsset=PhysicsAsset'SK_CH_Corrupt_Male_Physics'
    //bHasPhysicsAssetInstance=True
    bEnableSoftBodySimulation=True
    bSoftBodyAwakeOnStartup=True
End Object
Mesh=SkeletalMeshComponent0
Components.Add(SkeletalMeshComponent0)

```

---
Tags: udk, unreal
---


title: Scene transitions

text:
# Question
Title: Scene transitions
It's my first time working with actual scenes/states, aka DrawableGameComponents, which work separate from one another. I'm now wondering what's the best way to make transitions between them, and how to affect them from other scenes.

Lets say I wanted to "push" one screen to the right, with another one coming in at the same time. Naturally I'd have to keep drawing both, until the transition is complete. And I'd have to adjust the coordinates I'm drawing at while doing it. Is there a way around specifically handling this special case in every single scene?

Or of I wanted to fade one into the other. Basically the question stays the same, how would you do that without having to handle it in every single scene?

While writing this I'm realizing it will be the same thing for all kinds of transitions. Maybe a central Draw method in the manager could be a solution, where parameters and effects are applied when necessary. But this wouldn't work if objects that are drawn have their own method, and aren't drawn within the scene, or if an effect has to be applied to the whole scene. That means, maybe scenes have to be drawn to their own rendertarget? That way one call to the base class after the normal drawing could be enough, to apply the effects, while drawing it to the main render target. But I once heard there are problems when switching from target to target, back and forth. So is that even a viable option?

As you can see, I have some basic ideas how it might work... but nothing specific. I'd like to learn what's the common way to achieve such things, a general way to apply all kinds of transitions.

# Answer
> 4 votes
The Game State Management sample that deals with screen transitions can be found here. (The MSDN site recently updated their App Hub url's so I'm guessing a lot of links will be broken for a while)

Personally I find some of the code to be too complex for beginners, with the constant use of events to be fired when menu items are clicked, and layering of state machines, etc. However I can explain the idea behind all of this.

Each scene has a transition delta time variable, which doesn't change when it's not transitioning. During transitions you increment it each frame. When the delta time reaches a threshold (like 1 or 0) the screen should update itself from "exiting" to "exited". You should pass this variable to functions responsible for drawing the screens.

Maybe you don't want the actual transition behavior coded in the screen object, but it should have some set of parameters to tell the Draw method how it should transition. That way Draw can still take care of the visuals, from position to alpha and anything else you want to add. I am in the process of making "menu skins" for my menu system, adapted from the XNA sample. As you would expect, the skin determines the menu's appearance but also where it should be placed, and how it should transition in/out. This works as a struct of parameters passed on to the Draw method.

Next time the main Update loop runs, the Screen Manager will check through the screens to see which ones have exited and it will remove those from the list.

This way you can have two or more screens at once, so one function can tell Screen A to leave and the other one to enter. Both of them will be "passing through" and don't need to know about each other to know when to finish their transitions.

# Answer
> 0 votes
I don't know if there's a general way of applying transitions but this is how I do it:

In my Game1 class i have this piece of code which basically shows a new scene and hides the active one:

```
    protected void ShowScene(GameScene scene)
    {
        activeScene.Hide();
        activeScene = scene;
        scene.Show();
    }

```

Then I have some scenes which inherit from SceneManager.

I made a Fade transition between my scenes in SceneManager:

```
    public virtual void Show()
    {
        Visible = true;
        Enabled = true;
        alpha = 0;        // Invisible
        fade = Fade.In;   // An enum Fade with values In, Out, Idle
    }

    public virtual void Hide()
    {
        Enabled = true;   // Has to be enabled to run the update method below.
        alpha = 1;        // Fully visible
        fade = Fade.Out;
    }

    public override void Update(GameTime gameTime)
    {
        if (fade != Fade.Out) // This is to avoid having two scenes active at the same
        {                     // time during the transition; this can lead to
                              // unexpected behavior.

            // -- all other code --

            foreach (GameComponent component in components)
            {
                component.Update(gameTime);
            }
        }

        // the enum 'fade' increases or reduces the float 'alpha'

        switch (fade)
        {
            case Fade.In:
                alpha += 0.01f;
                break;
            case Fade.Out:
                alpha -= 0.01f;
                break;
        }

        if (fade != Fade.Idle)
        {
            if (alpha < 0)        // end of Fade.Out
            {
                alpha = 0;
                fade = Fade.Idle;
                Visible = false;  // stop the draw of the scene
                Enabled = false;  // stop the update
            }
            else if (alpha > 1)   // end of Fade.In
            {
                alpha = 1;
                fade = Fade.Idle;
            }
        }

        base.Update(gameTime);
    }

```

Now that we got the alpha value we can pass it down to all the components in the scene. Those components can then use that alpha value to add transparency on its textures:

```
    public override void Draw(GameTime gameTime)
    {
        SpriteBatch sBatch = (SpriteBatch)Game.Services.GetService(typeof(SpriteBatch));

        sBatch.Draw(texture, position, Color.White * alpha);

        base.Draw(gameTime);
    }

```

If you want a 'slide to a side' transition you can do the same thing but then use the position as variable.

# Answer
> 0 votes
There used to be a great state management sample for XNA that was available, called "Game State Management Sample". I can't seem to find it anymore (the first hit on Google is it, but Microsoft moved the page...) You can find the WP7 version which should be nearly identical right here. It has transitions built into it (a fade-in effect, at least) and you should definitely check it out.

---
Tags: xna, effects, scene
---


title: Need help compiling detour function

text:
# Question
Title: Need help compiling detour function
I try to compile this dll for MW2. It will not compile due to the fact that detour function is undefined.

Here's the code:

```
// dll_load.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include <stdio.h>
#include <string>
using std::string;

typedef void (*SV_GameSendServerCommand_t)(int clientNum, /*svscmd_type*/int type, const char *text);
SV_GameSendServerCommand_t SV_GameSendServerCommand = (SV_GameSendServerCommand_t)0x822548C8;

typedef int (*Key_IsDown)(int ClientNum, int ButtonEnum);
Key_IsDown button_Pressed = (Key_IsDown)0x82141308;

typedef void* (*R_RegisterFont_t)(char* asset, int imagetrack);
R_RegisterFont_t R_RegisterFont = (R_RegisterFont_t)0x8234DC20;

typedef void (*R_AddCmdDrawText_t)(const char *text, int maxChars, void *font, float x, float y, float xScale, float yScale, float rotation, const float *color, int style);
R_AddCmdDrawText_t R_AddCmdDrawText = (R_AddCmdDrawText_t)0x823501E8;

typedef bool (__cdecl * Dvar_GetBool_t)(const char * dvarName);
Dvar_GetBool_t Dvar_GetBool = (Dvar_GetBool_t)0x8229EEE0;

void AddCmdDrawText(char* Text, int Unknown1, void* Font, float X, float Y, float Unknown2, float Unknown3, float Unknown4, const float *Color, int Unknown5)
{
    void* font = R_RegisterFont("fonts/smalldevFont", 1);
    float color[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
    R_AddCmdDrawText("undefined", 0x7FFFFFFF, font, 100, 400, 1.0f, 1.0f, 0.0f,   color, 0);
}

typedef void ( _cdecl* tRenderStuff )();

tRenderStuff oRenderStuff=0;

void hRenderStuff()
{
    void* font = R_RegisterFont("fonts/smalldevFont", 1);
    float colorWhite[4] = {1.0f, 1.0f, 1.0f, 1.0f};
    R_AddCmdDrawText("undefined", 0x7FFFFFFF, font, 100, 400, 1.0f, 1.0f, 0.0f, colorWhite, 0);

oRenderStuff();
}

DWORD WINAPI commands(LPVOID)
{
        for(;;)
        {
            if (Dvar_GetBool("cl_ingame"))
            {
                oRenderStuff = (tRenderStuff)DetourFunction( ( PBYTE )0x585830, ( PBYTE )&hRenderStuff );     //hook endframe
            return 0;
        }
        Sleep(45);
    }
    Sleep(45);
}

BOOL WINAPI DllMain(HANDLE hInstDLL, DWORD reason, LPVOID lpReserved)
{
    if(reason==DLL_PROCESS_ATTACH)
    {
      CreateThread(0,0,commands,0,0,0);
    }
  return TRUE;
}

```

# Answer
Your code is missing this include:

```
#include <detours.h>

```

Which is likely the header file that has the definition for `DetourFunction`. Try to just compile the exact code in the tutorial first, then make your changes from there. Recompile/test after each change you make, then you'll know which change broke the code and you won't have to backtrack so much.
> 1 votes

---
Tags: c++
---


title: Lights system with shaders in OpenGL?

text:
# Question
Title: Lights system with shaders in OpenGL?
In more than just 1 occasion, i read about 2 ways of doing a light's system in OpenGL:

* normal way? i don't know how to call this one
* with the shaders ( GLSL )

The problem is i don't get the difference in terms of rendering performance and system usage, what are the pros and cons for each one ?

Thanks.

# Answer
There are the fixed function and programmable shader pipelines.

This is much bigger than just lighting, chances are your learning a whole bunch of other outdated stuff. The following are some common functions that are now deprecated:

* glBegin(...)
* glEnd()
* glVertex\*
* glNormal\*
* glColor\*
* glTextCoord\*
* glMultiTexCoord\*
* glLoadIdentity\*
* glMatrixMode(GL\_MODELVIEW/GL\_PROJECTION/...)
* glRotate\*
* glTranslate\*

If your learning the fixed function stuff your learning out of date programming techniques. They are easier but all of which would have to be unlearned. I recommend you look at how your learning OpenGL and look for some modern tutorials.

Take a look at my post on the gamedev stackexchange. It covers learning the new stuff.

Specifically for lighting. Fixed function is easier but has the following problems: * It isn't per-pixel lighting so the quality is much worse. * It's not supported at all in OpenGL ES 2.0/3.0 or WebGL * No way to do things like bump/normal mapping. Specular reflection textures (Making part of a texture shiny and reflect more light). * Your probably going to need shaders for other effects (for example shadows), once you use any shaders you loose the fixed functionality and must reimplement it anyway. * No control over the shading algorithms other than some basic properties. * It's been deprecated/removed in the new versions of OpenGL 3+. Basically it's the out of date method and should be avoided.

About the only use fixed function has now days is if you need to target OpenGL versions before 2.0 or OpenGL ES 1.x (for the older iPhones).

Programmable shaders do require more work and understanding.

* Firstly you have to understand the OpenGL shader API. How to compile and link shaders (not to hard).
* Also you have to understand how to communicate with them. How will you represent your lights in structures and upload them to the shaders.
* And you have to learn the GLSL language (it's C like so not to hard).
* Finally you have to understand the actual algorithms used in shaders.

For vertex shaders it's how a Model, View and Projection matrix combine together to turn the 3D coordinates you give vertices into the 2D coordinates you see on your flat screen.

For the fragment/pixel shaders you have to understand the shading algorithms. Blinn, Phong or whatever. How the angle of the camera combines with the normals on the surface to produce shading. Your also going to have to do stuff like texturing.

I think it's best to just start out learning the shader pipeline. You can rely on some deprecated functionality but it's best if you just use the stuff OpenGL does by default rather than actively learning old stuff.
> 4 votes

# Answer
I want to answer my own question because i think that after reading some article about it, considering the kind of hardware available on the market, there is no point that can lead me to adopt a fixed pipeline instead of a programmable pipeline based on the shaders.

So even if you are targeting an hardware that can let you choose between a fixed pipeline or a programmable pipeline you probably want to do everything with a programmable pipeline and just avoid the fixed pipeline that is something from the past and simply can't unlock all the potential of a modern GPU.
> 1 votes

---
Tags: opengl-es, glsl, opengl-es2, lighting
---


# Question
Title: Current status of 3D Sound Effect APIs in games
I'm doing a little research on a subject, and it looks like there is some sort of crysis there? Last EAX/OpenAL supporting games were like in year 2006. Why is that? Is there is a major lost of interest of gamers to these effects, or game developers just switching to surround sound (however this has nothing to do with 3D sound effects)?

I think these effects in the video above are pretty nice, why there is so little possibilities for game developers to create such things? From where this limitation comes from?

As far as I undersand it's both lack of some good (preferrably multiplatform) standard API like OpenGL, and support for this API by either OS (for software emulation, if it's possible) or sound card drivers. Does my conclusion is correct? Or maybe there are some other reasons as well?

**UPDATE**. I've found examples of modern games which produces some other effects in 3D environment, so it's looks like I was wrong. Seems like just this is not-so-popular subject for a common public discussion. What I mean by that it's either so common it became not-to-mention feature of a game, either it's a very narrow area which doesn't produces much discussion or maybe both.

However, I would like to see more example of *modern* 3d sound effect libraries *in action*.

# Answer
FMOD is practically an industry standard. Wwise is also gaining a lot in popularity. They both support a wide variety of platforms. You can get high-quality 3D sound and advanced sound effects on every single worthwhile platform today, with hardware acceleration when available.

There are close to no large commercial games that lack 3D audio and effects. Many hobbyist, student, and indie games also support it. I'm not sure why think there are a lack of games with these features.

There is a lack of a quality open API for such things. OpenAL exists, but... man, it's just horrible. Until such a time that the Open Source community can cobble together a good competitor, FMOD or Wwise are freely available for hobbyists and support Linux and plenty of other platforms.
> 2 votes

---
Tags: sound, game-industry
---


title: AndEngine sprite movement

text:
# Question
Title: AndEngine sprite movement
I want to ask that I have a player in my game. I may walk. I have a image which has five different frames for walk and two frames for standing position. I want to ask that how can I change the images on runtime depending on the player state? I have loaded the image in tiledtextureregion. Also player can walk in forward and backward direction as well. How to use the same image strip for walking back and forth? I am new to andengine.

# Answer
You can flip the texture like so: myTextureRegion.setFlippedHorizontal(true);

or by using the sprite

mySprite.setFlippedHorizontal(true); // set false to flip it back

Have you looked at AnimatedSprite class? AnimatedSpriteClass

You could google for examples. It's in the API
> 4 votes

---
Tags: animation, sprites, andengine
---


# Question
Title: XNA Framework sprite vectors and also scaling
I'm working on making my first Pong game with XNA Framework 4.0. Right now i've put 2 pong paddles and a ball (they have separate classes). In the "Paddle" class i've made a function that returns a Vector2 list of the **normals to its edges** (i'm going to leave all 4 of them as i'm considering adding rotation and other things in the future).

Right now i'm trying to do my own implementation of the separating axis theorem. My question is: is there a more **efficient** method of computing the edges(or the normals to them), other than doing them by hand? Here's my code from the Paddle class:

```
public List<Vector2> NormalsToEdges()
    {
        Vector2 Edge = Vector2.Zero;
        List<Vector2> lst = new List<Vector2>();

        //take this normal because our reference axes have the origin in the top left corner
        //upper edge
        Edge = (this.paddlePosition + new Vector2(this.Width, 0)) - this.paddlePosition;
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //right edge
        Edge = (this.paddlePosition + new Vector2(this.Width, this.Height)) - (this.paddlePosition + new Vector2(this.Width, 0));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //bottom edge
        Edge = (this.paddlePosition + new Vector2(0, this.Height)) - (this.paddlePosition + new Vector2(this.Width, this.Height));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        //left edge
        Edge = this.paddlePosition - (this.paddlePosition + new Vector2(0, this.Height));
        if (Edge != Vector2.Zero)
        {
            Edge.Normalize();
            lst.Add(new Vector2(Edge.Y, -Edge.X));
        }

        return lst;
    }

```

I don't know why but i have a feeling that i'm over-complicating things (considering that i have to update these edges on every update cycle in the main game). For example, if i decide to change the sprite to some convex irregular polygon with 50+ (or 500+) edges will the performance impact be high? (suppose i know all the vertex coordinates and/or that i can actually get the list of edge-vectors somehow, in CCW or CW order).

Second issue. Suppose i want to heighten one of the paddles under certain conditions in the game. I know i can use scaling for this (on Draw) and test the scale factor (like if it's 1.0f i use height/width of the original sprite, otherwise i make a new property that gives the scaled values), but is there a way to actually **scale the sprite** itself? (so that height/width/etc values will return the scaled versions). I'm asking this because i think it might save additional coding of properties, recalculation of rectangles etc.

All in all, i'm aiming for maximum efficiency.

Thanks

# Answer
> 2 votes
First of all if you are not rotating the paddle then you do not need to recalculate the normals every frame.

In case you have a world matrix then you can get the normals easily from it using its front, right, up etc vectors.

As you are using c# which has a garbage collector creating a new list every frame is not a good idea (if you are targeting xbox or wp7 you're likely to notice problems). Instead you can have an array that is updated every frame in case the solution with a world matrix does not suit you.

SAT is very demanding on bodies with many faces (or edges) so I guess you would have to use some modified variant of it if you had a 500+ edge body. You could divide a convex body into subsets but I have never done anything like that myself. Personally I think I would just go for using a simpler body for collision detection if that was the case.

In case the width and height was to increase I would do so by having vectors represent their corners and actually moving these (in local space of course). Then let physics, rendering etc handle that accordingly. It might be good for you to have an array of corner points anyway when you are going to go through collision handling.

---
Tags: xna, sprites, vector
---


# Question
Title: Deferred rendering with VSM - Scaling light depth loses moments
I'm calculating my shadow term using a VSM method. This works correctly when using forward rendered lights but fails with deferred lights.

```
// Shadow term (1 = no shadow)
float shadow = 1;

// [Light Space -> Shadow Map Space]

// Transform the surface into light space and project
// NB: Could be done in the vertex shader, but doing it here keeps the
// "light shader" abstraction and doesn't limit the number of shadowed lights
float4x4 LightViewProjection = mul(LightView, LightProjection);
float4 surf_tex = mul(position, LightViewProjection);

// Re-homogenize
// 'w' component is not used in later calculations so no need to homogenize (it will equal '1' if homogenized)
surf_tex.xyz /= surf_tex.w;

// Rescale viewport to be [0,1] (texture coordinate system)
float2 shadow_tex;
shadow_tex.x = surf_tex.x * 0.5f + 0.5f;
shadow_tex.y = -surf_tex.y * 0.5f + 0.5f;

// Half texel offset
//shadow_tex += (0.5 / 512);

// Scaled distance to light (instead of 'surf_tex.z')
float rescaled_dist_to_light = dist_to_light / LightAttenuation.y;
//float rescaled_dist_to_light = surf_tex.z;

// [Variance Shadow Map Depth Calculation]

// No filtering
float2 moments = tex2D(ShadowSampler, shadow_tex).xy;

// Flip the moments values to bring them back to their original values
moments.x = 1.0 - moments.x;
moments.y = 1.0 - moments.y;

// Compute variance
float E_x2 = moments.y;
float Ex_2 = moments.x * moments.x;
float variance = E_x2 - Ex_2;
variance = max(variance, Bias.y);

// Surface is fully lit if the current pixel is before the light occluder (lit_factor == 1)
// One-tailed inequality valid if
float lit_factor = (rescaled_dist_to_light <= moments.x - Bias.x);

// Compute probabilistic upper bound (mean distance)
float m_d = moments.x - rescaled_dist_to_light;

// Chebychev's inequality
float p = variance / (variance + m_d * m_d);

p = ReduceLightBleeding(p, Bias.z);

// Adjust the light color based on the shadow attenuation
shadow *= max(lit_factor, p);

```

This is what I know for certain so far:

* The lighting is correct if I do not try and calculate the shadow term. (No shadows)
* The shadow term is correct when calculated using forward rendered lighting. (VSM works with forward rendered lights)

With the current rescaled light distance (lightAttenuation.y is the far plane value):

`float rescaled_dist_to_light = dist_to_light / LightAttenuation.y;`

The light is correct and the shadow appears to be zoomed in and misses the blurring:

Incorrect Shadow http://www.rhysperkins.com/XNA/Rescaled.png

When I do not rescale the light and use the homogenized 'surf\_tex':

`float rescaled_dist_to_light = surf_tex.z;`

the shadows are blurred correctly but the lighting is incorrect and the cube model is no longer lit

Correct Shadow http://www.rhysperkins.com/XNA/NonRescaled.png

Why is scaling by the far plane value (LightAttenuation.y) zooming in too far?

The only other factor involved is my world pixel position, which is calculated as follows:

```
// [Position]
float4 position;

// [Screen Position]
position.xy = input.PositionClone.xy;           // Use 'x' and 'y' components already homogenized for uv coordinates above
position.z = tex2D(DepthSampler, texCoord).r;       // No need to homogenize 'z' component
position.z = 1.0 - position.z;
position.w = 1.0;                   // 1.0 = position.w / position.w

// [World Position]
position = mul(position, CameraViewProjectionInverse);

// Re-homogenize position (xyz AND w, otherwise shadows will bend when camera is close)
position.xyz /= position.w;
position.w = 1.0;

```

Using the inverse matrix of the camera's view x projection matrix does work for lighting but maybe it is incorrect for shadow calculation?

EDIT:

Light calculations for shadow including 'dist\_to\_light'

```
// Work out the light position and direction in world space
float3 light_position = float3(LightViewInverse._41, LightViewInverse._42, LightViewInverse._43);

// Direction might need to be negated
float3 light_direction = float3(-LightViewInverse._31, -LightViewInverse._32, -LightViewInverse._33);

// Unnormalized light vector
float3 dir_to_light = light_position - position;    // Direction from vertex
float dist_to_light = length(dir_to_light);

// Normalise 'toLight' vector for lighting calculations
dir_to_light = normalize(dir_to_light);

```

EDIT2:

These are the calculations for the moments (depth)

```
//=============================================
//---[Vertex Shaders]--------------------------
//=============================================

DepthVSOutput depth_VS(
    float4 Position : POSITION,
    uniform float4x4 shadow_view,
    uniform float4x4 shadow_view_projection)
{
DepthVSOutput output = (DepthVSOutput)0;

// First transform position into world space
float4 position_world = mul(Position, World);

output.position_screen = mul(position_world, shadow_view_projection);
output.light_vec = mul(position_world, shadow_view).xyz;

return output;
}

//=============================================
//---[Pixel Shaders]---------------------------
//=============================================

DepthPSOutput depth_PS(DepthVSOutput input)
{
DepthPSOutput output = (DepthPSOutput)0;

// Work out the depth of this fragment from the light, normalized to [0, 1]
float2 depth;
depth.x = length(input.light_vec) / FarPlane;
depth.y = depth.x * depth.x;

// Flip depth values to avoid floating point inaccuracies
depth.x = 1.0f - depth.x;
depth.y = 1.0f - depth.y;

output.depth = depth.xyxy;

return output;
}

```

EDIT 3:

I have tried the folloiwng:

```
float4 pp;
pp.xy = input.PositionClone.xy;         // Use 'x' and 'y' components already homogenized for uv coordinates above
pp.z = tex2D(DepthSampler, texCoord).r; // No need to homogenize 'z' component
pp.z = 1.0 - pp.z;
pp.w = 1.0;                             // 1.0 = position.w / position.w

// Determine the depth of the pixel with respect to the light
float4x4 LightViewProjection = mul(LightView, LightProjection);
float4x4 matViewToLightViewProj = mul(CameraViewProjectionInverse, LightViewProjection);
float4 vPositionLightCS = mul(pp, matViewToLightViewProj);

float fLightDepth = vPositionLightCS.z / vPositionLightCS.w;

// Transform from light space to shadow map texture space.
float2 vShadowTexCoord = 0.5 * vPositionLightCS.xy / vPositionLightCS.w + float2(0.5f, 0.5f);
vShadowTexCoord.y = 1.0f - vShadowTexCoord.y;

// Offset the coordinate by half a texel so we sample it correctly
vShadowTexCoord += (0.5f / 512);        //g_vShadowMapSize

```

This suffers the same problem as the second picture.

I have tried storing the depth based on the view x projection matrix:

```
output.position_screen = mul(position_world, shadow_view_projection);
//output.light_vec = mul(position_world, shadow_view);
output.light_vec = output.position_screen;

depth.x = input.light_vec.z / input.light_vec.w;

```

This gives a shadow that has lots surface acne due to horrible floating point precision errors. Everything is lit correctly though.

EDIT 4:

Found an OpenGL based tutorial here

I have followed it to the letter and it would seem that the uv coordinates for looking up the shadow map are incorrect.

The source uses a scaled matrix to get the uv coordinates for the shadow map sampler

```
/// <summary>
/// The scale matrix is used to push the projected vertex into the 0.0 - 1.0 region.
/// Similar in role to a * 0.5 + 0.5, where -1.0 < a < 1.0.
/// <summary>
const float4x4 ScaleMatrix = float4x4
(
0.5, 0.0, 0.0, 0.0,
0.0, -0.5, 0.0, 0.0,
0.0, 0.0, 0.5, 0.0,
0.5, 0.5, 0.5, 1.0
);

```

I had to negate the 0.5 for the y scaling (M22) in order for it to work but the shadowing is still not correct.

Is this really the correct way to scale?

```
float2 shadow_tex;
shadow_tex.x = surf_tex.x * 0.5f + 0.5f;
shadow_tex.y = surf_tex.y * -0.5f + 0.5f;

```

The depth calculations are exactly the same as the source code yet they still do not work, which makes me believe something about the uv calculation above is incorrect.

# Answer
So you're scaling the moments to fit into 0–1, which suggests a 0–1 texture (integral), but you're also subtracting them from 1.0 for floating point reasons. So are you using an integer texture or a floating-point texture? Because only one of those techniques should be necessary. That's probably not your problem, though.

One thing you can consider trying is to store the *depth*, not the *distance*, in your shadow texture. (i.e. the post-projected w coordinate instead of the `length()` of your position in light view space). I don't think the two are so different that it would entirely explain the lack of filtering in your first picture, but it's worth a shot.

I *can* tell you why the lighting in your second picture is wrong (or, rather, why the cube is considered to be entirely shadowed). The projection-space Z coordinate is fundamentally not the same as the rescaled depth you're using. You're simply dividing by the far-plane distance, to put the maximum distance at 1. The projection-space Z, after performing the homogeneous division, is a ratio of Z (a rescaled depth, which is 0 at the near plane and 1 at the far plane—like your depth but with an offset) and W (an unscaled distance to the eye along the depth axis). The Z/W division, then, is non-linear: at *z* = *n* (near plane distance) it is zero (doesn't even match your depth there), and even as close as *z* = 2 * *n*, you'll get a Z/W of about 0.5. In other words, that's not what you want to use.
> 1 votes

---
Tags: xna-4.0, shadows, deferred-rendering, shadow-mapping
---


# Question
Title: Sea water shader using only fragment processor
I have a game that runs on mobile devices (OpenGL ES 2.0) and for which I would like to create some sea water using the shaders. Now, the plane on which the sea water texture will be has only 4 vertices and I need it to remain like that (because of performance issues). So, I think, my only option is to simulate the water from the fragment shader. At conceptual level, how should I do it? I must mention I'm a beginner with the programmable pipeline (I barely learned the language, in some extent) and have no idea where should I start.

# Answer
See the paper in the GPU Gems series treating this subject: http://http.developer.nvidia.com/GPUGems/gpugems\_ch01.html

What you can do is to adapt that idea (Gerstner waves) and compute the normals for each of your rendered fragment. The way to do that would be to assign a water texture (without too much light information in it, since you're gonna compute colours on in the shader anyway). That texture also comes with a texcoord set mapping (for each of your 4 vertices you get an **uv** pair of texture coordinates in the range of \[0,1\]). All in all, you have a plane you can deform in the fragment shader: the \[0,1\]x\[0,1\] square described by your **uv** texcoordset. Each **uv** pair that will be interpolated and present in your fragment shader can be used to recover a normal vector like you would in the vertex shader. That is useful only if the water surface is relatively far away from the camera: since you can't deform/displace vertices, you can observe light reflecting in different directions and shading that surface according to a time variable. It should work in a sense and it should be easier and more convincing than distorting/moving a texture through texcoord manipulation as older game effects do.

*Implementation details* Consider the above picture to be your water surface given as a quad. When you prepare it for shader drawing, you must supply a texture to it (if you don't want to colour it solidly). When you bind a texture to it, for that to work, you mus associate to each of the vertices an *attribute* containing the texture coordinates. This is the so called *uv* set and, if there's no tiling involved on your quad, these could be given as *A(0,0), B(1,0), C(1,1), D(0,1)*, where A, B, C, D are the vertices of your quad.

*in the vertex shader*

compute the position as you normally would and pass the *uv* you get as an attribute input variable to the fragment shader through a *varying* variable. The other, simpler way, could be to pass the object frame vertex coordinates (the positions prior to their multiplication through the worldvieprojection matrix). The varying descriptor will make sure the fragment gets an interpolated position on the quad. Let's call this variable **xy** and pass it to the frag shader as said.

*in the fragment shader*

Pass as an input uniform the world transformation matrix because you'll have to transform the computed normals to align with your lights position. Alternatively, pass the light already transformed in the object's own frame of reference and use the directly computed normal (should be quite faster and more elegant).

**xy** is a 2D vector and we need a 3D point on a water surface. Gerstner waves associate to a flat rectangle a height for each of its inner points. If you then consider the union of all of those **xy** displaced via that height function, you get the wave surface. We can't discuss positions in the frag shader, but we can compute and use normals for other purposes.

The normal you are looking for can be computed from the **xy** pair following this rationale: http://mathbin.net/105022 . For the waves to be animated, make sure to pass a *time* instance as an input uniform to the fragment shader. It is required as an input for the *H(x,y,t)* height function. That should be all. The rest is just plain lighting computation in a frag shader.
> 6 votes

---
Tags: opengl-es, glsl, opengl-es2
---


title: Shaders not linking correctly

text:
# Question
Title: Shaders not linking correctly
I'm writing a rather simple "ShaderManager" which aids me with loading shaders in Open GL, altough I am having a few issues:

1. The shaders don't link correctly
2. The the attributes don't bind

Here's the output of my program:

```
The shaders did not link correctly.
Could not bind attribute: v_coord3d
Could not bind attribute: v_color
Could not bind uniform: mvp

```

And here's the relevant code and header file...

```
void ShaderManager::create_program(std::string name)  {
    GLuint vertexshader;
    GLuint fragmentshader;

    GLint link_ok = GL_FALSE;

    if ((vertexshader = create_shader(name + ".v.glsl", GL_VERTEX_SHADER)) == 0)  {
        print_shader_errors(&vertexshader);
    }

    if ((fragmentshader = create_shader(name + ".f.glsl", GL_FRAGMENT_SHADER)) == 0)  {
        print_shader_errors(&fragmentshader);
    }

    program_values.emplace_back(glCreateProgram());
    program_keys.emplace_back(name);
    glAttachShader(program_values[program_values.back()], vertexshader);
    glAttachShader(program_values[program_values.back()], fragmentshader);
    glLinkProgram(program_values[program_values.back()]);

    glGetProgramiv(program_values[program_values.back()], GL_LINK_STATUS, &link_ok);

    if (!link_ok)  {
        std::cout << "The shaders did not link correctly." << "\n";
    }
}

bool ShaderManager::bind_attribute(std::string shader_name, std::string attribute_name)  {
    GLuint attribute = glGetAttribLocation(get_program(shader_name), attribute_name.c_str());

    if (attribute != -1)  {
        attribute_values.emplace_back(attribute);
        attribute_keys.emplace_back(attribute_name);

        return true;
    }

    std::cout << "Could not bind attribute: " << attribute_name << "\n";

    return false;
}

// bind uniform function is much the same as the above

class ShaderManager {
    public:
        ShaderManager();
        virtual ~ShaderManager();

        static GLuint get_program(std::string shader_name);
        static int get_index_of_program_key(std::string program_name);

        static void create_program(std::string name);
        static bool bind_attribute(std::string shader_name, std::string attribute_name);
        static bool bind_uniform(std::string shader_name, std::string uniform_name);

    protected:
    private:
        static std::vector<GLuint> program_values;
        static std::vector<std::string> program_keys;

        static std::vector<GLuint> attribute_values;
        static std::vector<std::string> attribute_keys;

        static std::vector<GLuint> uniform_values;
        static std::vector<std::string> uniform_keys;

        static void print_shader_errors(GLuint *shader);
        static const char* file_read(std::string filename);
        static GLuint create_shader(std::string filename, GLenum type);
};

```

Here's the code which actually calls the functions:

```
ShaderManager::create_program("shader");
ShaderManager::bind_attribute("shader", "v_coord3d");
ShaderManager::bind_attribute("shader", "v_color");
ShaderManager::bind_uniform("shader", "mvp");

```

Another issue I have is that I can't access a string in a vector list with program\_names\[0\], anyone know why?

# Answer
> 3 votes
Are you sure, this is correct?

```
glAttachShader(program_values[program_values.back()], vertexshader);
glAttachShader(program_values[program_values.back()], fragmentshader);
glLinkProgram(program_values[program_values.back()]);

glGetProgramiv(program_values[program_values.back()], GL_LINK_STATUS, &link_ok);

```

I am not OpenGL expert, but you probably mean this:

```
glAttachShader(program_values.back(), vertexshader);
glAttachShader(program_values.back(), fragmentshader);
glLinkProgram(program_values.back());

glGetProgramiv(program_values.back(), GL_LINK_STATUS, &link_ok);

```

# Answer
> 2 votes
Use `glGetProgramInfoLog` to get a log from the linker and understand what is wrong.

```
char errbuf[4096];
GLsizei len;

glGetProgramInfoLog(program_values[program_values.back()], sizeof(errbuf), &len, errbuf);
glGetProgramiv(program_values[program_values.back()], GL_LINK_STATUS, &link_ok);
if (!link_ok)  {
    std::cout << errbuf << std::endl;
    std::cout << "The shaders did not link correctly." << std::endl;
}

```

I assume you are not using `glGetShaderInfoLog` in the compilation stage either, so I suggest you do that, too.

# Answer
> 1 votes
Shaders not linking can be caused by a few things. One of them is that the shaders are not comiled correctly. The tool I use for finding problems with my shaders is gDEBugger (there are two versions to go with, you can read that question/answer to find out more, I found that the original (older) version has worked better for me). I recommend you download this and see what errors are being reported in your shader loading.

You can also have your program output the last error code after each operation. To see where things might be going wrong. Though, I've found at least one time where my shaders were not linking and no errors were being reported with my code. But once I got it loaded up in gDEBugger, I was able to find the issue.

---
Tags: c++, opengl, shaders, glsl
---


title: Blender to 3ds max to cal3d format

text:
# Question
Title: Blender to 3ds max to cal3d format
There are quite a few questions on cal3d but they are old and don't apply anymore.

In Blender(must be 2.49a for python script to work!!!):

I have a scene with 7 meshes, 1 armature, 10 bones. I tried going to one mesh to simplify it but doesn't change anything. I found a small blend file that was used for cal3d and it exported just fine. So I tried to copy it's setup with no success.

EDIT\*8/13/2012

In the last week here is what I have found so far.

I made the mesh in the newest blender(2.62?) and exported it to import it in the old one(2.49a). Did an animation in the old one because importing new blend files to old blenders, its just said it would lose keyframe data and all was good. And then you get the last problem of it not exporting meshes. BUT I found that meshes made in the old one export regardless. I can't find any that won't export. So if I used the old blender to remake my model I could get it to export :)

At this point I found a modified release of cal3d (because the most core model variable would not initiate as I made a really small test subject in old blender instead of remaking my big one which took 4 hours.) which fixes the morph objects and adds what cal3d left off with. Under their license they have to release the modification but it has no documentation so I have to figure it out on my own. Its mostly the same. But with this lib it came with a 3ds max exporter.

My question now is how do I transfer armature and mesh information from blender to 3ds max in order to export into cal3d format. Every time I try the models are see through and small and there are no bones. The formats I have tried to import are .3ds .obj(mesh only) and COLLADA. In all of them the mesh is invisible and no bones. It says the default texture is on so I should be able to see it. All the vertices are present I found a vertex highlighter so I can see those.

If any of this is confusing let me know so I can clear it up. Its late \>.\<=sleep.

# Answer
blender2cal3d worked for me in 2.49. Remember to make sure you select and export the skeleton first.
> 1 votes

---
Tags: animation, models, blender, 3d-meshes, skeletal-animation
---


# Question
Title: VBO and gl*Pointer management practises?
I'm aware it's not a simple yes/no question and for the moment I can't tell if it can be simply answered, or is it a topic for a long discussion which is not suitable for our Q&A format.

I want to do some VBO management in order to reduce calls to GL.

I have **4 VBOs** for all meshes:

* one for static draws
* one for dynamic draws
* one for stream draws
* one for indices

I want these four to handle my whole scene - this is going to **reduce calls to glBindBuffer**.

My *mesh object* consists respectively of *static part*, *dynamic part* and *stream part*, each of the part is specified by *vertex specificator* that is created at runtime, just by pushing back *attribute objects* containing size/type/offset to a member vector.

Based on the *vertex specificators* you can fill the *parts* with interleaved data, you don't have to do this for all the *parts* though. As I read here, separating vertex parts with different usage modes is good as it allows you to update all the dynamic/stream data at once **without ever touching the static data**. For example, doing particle simulation I may not be necessarily interested in streaming texture coordinates - changing vertex positions may be enough.

What's going to happen next:

1. sort all *mesh objects* by the *vertex specificator* of its *static part*
2. upload all the meshes' *static parts'* vertex data in obtained order to the **static VBO**
3. sort all *mesh objects* by the *vertex specificator* of its *dynamic part*
4. upload all the meshes' *dynamic parts'* vertex data in obtained order to the **dynamic VBO**

... and so on.

In short, static/dynamic/stream chunks (each in one of the 3 VBO's to which it belongs) with the same vertex types will be next to each other, and this is going to **reduce calls to glVertexAttribPointer**. Here I will need to smartly organize meshes that may want to use various *parts*, and then implement kind of lazy binds, probably if mesh needs to call gl*Pointer for two different VBOs (separate static and stream parts for example), check if one of them is not already bound and **call corresponding gl*****Pointer first**.

Of course, each of the big batch obtained that way will then be sorted inside on the level of draw calls to reduce switches of shaders, textures and so on.

In short, this is my idea:

Although such a case may be uncommon, it's just to illustrate what should my mesh organizer be able to deal with.

Well, now it's only a plan and I haven't yet implemented it but..

How do the modern, high performance engines do their VBO and gl\*Pointer state management? Is there something wrong with my concept, or am I totally misguided? Google results for *VBO management* and similiar tend to give me topics where people are asking for help because their programs crash, or just usage examples that tell nothing about optimizing my rendering procedures on VBO level but just **"avoid redundant calls to GL"**, or some actual one-line tips (like glBufferData with NULL). So what I've described above is what I've concluded myself using those informations and I'm not sure if I am even on the right path.

Could somebody show me some good and actually proven practises managing VBOs in big 3D scenes, or maybe guide me a bit if I am actually reasoning right ?

# Answer
This answer is more or less in flux, due to the recent advent of this.

In general, what you want to avoid is calling `glVertexAttribPointer` wherever possible. There are several tools for this; the biggest is the use of BaseVertex indexed rendering. This allows you to put multiple models into the same buffers, with the same vertex formats. Then, you draw each one with a `glDrawElementsBaseVertex` call, updating the base vertex and the index buffer offset.

Naturally, this requires that many of your models share a vertex format: they take the same attributes, stored in the same order, with the same offsets and strides. You should strive to have relatively few different kinds of vertex formats.

Thus, you have a few large arrays of vertices, all of the same format, which your BaseVertex and index lists select individual meshes from.

---

Vertex attrib binding brings with it entirely new ideas, the specific performance of which are not entirely clear. However, since vertex attribute binding is taken almost verbatum from Direct3D's concept of vertex formats and streams, it is useful to look to that API for guidance.

There, a vertex format is an *immutable* object. You create a format, and that's the end of it; it cannot be changed or modified. This suggests that there is a significant cost associated with changing vertex formats. Indeed, when NVIDIA was coming up with bindless vertex transfer, they took the opportunity to do something very similar: separate the format from the buffer that provides it.

Therefore, a reasonable suggestion is to follow D3D conventions: set the format once for a VAO and don't touch it. Just change the buffer binding with `glBindVertexBuffer` (the equivalent functionality in D3D is mutable).
> 7 votes

---
Tags: c++, opengl, 3d, performance, vbo
---


# Question
Title: Should I dedicate a single thread to each player in a split-screen game?
I was thinking about making multiplayer version of a game I am making with SDL and OpenGL. It would be a split-screen game.

Do you think it would be a good idea to have each part of the screen (game session) handled by different thread? Those threads would have no data to share except for pause and game over/victory events. Since the single player version is already written, I thought I could save a lot of development time by implementing it this way.

# Answer
> Do you think it would be a good idea to have each part of the screen (game session) handled by different thread?

When it comes to rendering: No!

OpenGL and multithreading don't mix well. It's best practice to keep all OpenGL operations to one single thread.
> 8 votes

# Answer
> I thought I could save a lot of development time by implementing it this way.

If the single thread solution fits your needs in terms of performance, I'm pretty sure that using more than one thread will not save you development time.

If you come to conclusion that you need multithreading, consider making a thread pool. Here's a good discussion on multithreading in games.

You may also be interested in http://gamedev.stackexchange.com as this question is clearly related to game development.
> 2 votes

# Answer
**No**, you shouldn't.

---

There simply is no reason why you would want threads. Threads have two use-cases: performance and asynchronity. The performance isn't a problem and there is no reason to do it asynchronous.

Threads aren't to be taken lightly and don't simplify anything.

Splitscreen multiplayer only requires you to code a few things: a camera for each player, input managment for each player and On-Screen-Effects for each player seperate. Also the AI or other gameplay elements need to be aware that there are multiple players. This is trivial in comparison to what it would take to write a threaded solution.
> 2 votes

---
Tags: multithreading, opengl, screen, sdl
---


title: CCsprite.flipX not working!

text:
# Question
Title: CCsprite.flipX not working!
Here is my function, it makes random point on the ground and makes my sprite go there. If the x position of location is less then position of my sprite, I flip my sprite so it looked left (it looks right by default). But this is not working at all. I tried different flip methods but none work! Please help what is wrong?

```
- (void) wander
{
    CGPoint rand = CGPointMake(CCRANDOM_0_1() * 270 , CCRANDOM_0_1() * 140 );

    float distance = ccpDistance([currentSprite position], rand);
    float speed = distance / 2;
    ccTime time = distance / speed;
    CCAction *move = [CCMoveTo actionWithDuration:time position:rand];

    if (currentSprite.position.x > rand.x)
    {

       currentSprite.flipX = YES;
    }
    else {
        currentSprite.flipX = NO;
    }

    [self runAction:move];
}

```

There is no problem with this code. Problem was that I was trying to flip sprite that was a child of my Pet object. When I tried flipping sprite everything worked just fine. If anybody could explain that, would be great.

# Answer
You can also try flipping it by using the scale:

```
currentSprite.scaleX *= -1.f;

```

You should also ensure that `currentSprite` is the sprite that contains the texture you want to flip, and is not a parent of the sprite that contains the texture you want to flip. See the documentation about `flipX` for more info.
> 2 votes

---
Tags: cocos2d-iphone
---


# Question
Title: What is the correct way of changing image of existing CCSprite?
How do I correctly change sprite to show another image? Or to have another texture? This is the way I do it now. When I need to change sprite image I increase state variable. So i have one picture for 0, another for 1 and another for 2. First i tried just saying mysprite = \[CCSpriteWithFile:@"sprite.png"\] but that didn't end up too well since I was making new objects every frame and it got messy pretty fast. So I added a check. There is another variable that is stateChanged and it starts at zero. So I compare state to stateChanged before actually making any sprites and if it differs I do the magic. But here comes the problem. Somehow this sprite won't flip. And I believe the problem is in this method.

```
- (void) updateState
    {
        if (stateChanged != state) {

        if (state == 0)
            {
                currentSprite = [CCSprite spriteWithFile:@"eggclosed.png"];
                [self addChild:currentSprite];
            }

        if (state == 1)

        {
            currentSprite = nil;
            [self removeAllChildrenWithCleanup:YES];
            currentSprite = [CCSprite spriteWithFile:@"eggopen.png"];
            [self addChild:currentSprite];
        }

        if (state == 2)
        {
            currentSprite = nil;
            [self removeAllChildrenWithCleanup:YES];
            currentSprite = [CCSprite spriteWithFile:@"yoshi.png"];
            [self addChild:currentSprite];
        }

            stateChanged = state;
        }
            }

```

TLDR: How to correctly change image of sprite. I have a Pet object that has a CCSprite property. And I sometimes need to change sprte to look another way. How do?

# Answer
> 1 votes
```
CCTexture2D* tex = [[CCTextureCache sharedTextureCache] addImage:@"new_image_name"];
[spriteWant2Change setTexture: tex];

```

---
Tags: cocos2d-iphone
---


# Question
Title: Do UDP game clients/servers block for receive calls?
One way to implement a client/server relationship is to have the server simulate the whole game based on the clients input and send updates back to each client, while the client is is simulating the game for the player and sending back input and game state messages that the server can use to process the whole state of the game.

My question is, since a ReceiveFrom() call blocks till it receives data and a Select() call blocks for a set period of time, does that mean all clients and servers block for a certain amount of time each frame? I am aware that a call to Select() can be set to zero which would be an effective poll to the read write states of the current sockets, but wouldn't you miss out on new data if it comes in just microseconds later? How is this problem solved now a days? Pro select() method handling? Asynchronously? Separate thread completely? Other?

I may be over thinking this, but I would like to know more information so I can write an effective client/sever relationship. -Haywire

# Answer
> I am aware that a call to Select() can be set to zero which would be an effective poll to the read write states of the current sockets, but wouldn't you miss out on new data if it comes in just microseconds later?

No. When a remote computer sends you data, it first goes onto your network adapter which has its own data buffers, and from there into your operating system which again has data buffers. Reading data pulls it from the buffer - it doesn't poll data that is sitting on the wire at that precise moment (which is lucky, since the information on the wire at any instantaneous point of time can be measured in bits, not bytes, certainly not kilobytes).

The only time you can 'miss' data is if you allow the buffer to overflow, which is unlikely to happen unless you are not reading at all or you are being flooded with data. If select says there's no data, but then data comes in microseconds later, select will just tell you the next time that you call it that there is now data available.
> 4 votes

# Answer
Whether your functions block or not, depends on the specific implementation (library/language). It is however safe to assume that the function will block at least as long as it takes to fetch/write the data.

The simplest solution is a second thread that does nothing but reading/writing. Instead of working with that data immediately, push it into a queue so it can be consumed by another thread(like your main game loop). Writing works the same way in the other direction. If the function call is blocking, call it with a small timeout, so you can switch between read/write fast and with minimal delay.

Depending on what you are doing you should really think of using TCP instead of UDP. Unless you really need the speed *and* a lost packet does not need to be resent, TCP is usually the better choice.
> 1 votes

---
Tags: networking
---


# Question
Title: Client/Server Object updates seems to run at different speeds
i have been playing around with the NetworkPrediction sample from Microsoft. Trying to adapt it to use gameTime. The client is running without fixed TimeStep and the server is custom C# and updates a lot faster than client.

Both client and server runs this code at update:

```
protected void UpdateState(ref ShipState state, GameTime gameTime)
    {
        if (turnRightAcceleration)
            state.Rotation += (this.RotationSpeed * (float)gameTime.ElapsedGameTime.TotalMilliseconds);
        else if (turnLeftAcceleration)
            state.Rotation -= (this.RotationSpeed * (float)gameTime.ElapsedGameTime.TotalMilliseconds);

        Vector2 shipForward = new Vector2((float)Math.Cos(state.Rotation),
                                          (float)Math.Sin(state.Rotation));

        if (trustAccelerating)
            state.Velocity += ((shipForward * this.TrustSpeed) * (float)gameTime.ElapsedGameTime.TotalMilliseconds);

        // Update the position and velocity.
        state.Position += (state.Velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds);
    }

```

This seems theoretically correct, every time a value is increased or decreased its affected by ElapsedGameTime.

And this is my Server Pump:

```
    public void Run()
    {
        foreach (GameServerComponent component in this.Components)
            component.Initialize();

        Console.WriteLine("Server running...");

        //DateTime serverStart = DateTime.Now;
        //DateTime lastUpdate = DateTime.Now;

        Stopwatch sw = Stopwatch.StartNew();
        TimeSpan lastTime = sw.Elapsed;
        GameTime gameTime;

        while (!exit)
        {
            TimeSpan currentTime = sw.Elapsed;
            TimeSpan elapsedTime = currentTime - lastTime;
            lastTime = currentTime;

            gameTime = new GameTime(currentTime, elapsedTime);

            foreach (GameServerComponent component in this.Components)
                component.Update(gameTime);
        }

        sw.Stop();
    }

```

This seems theoretically correct as well. Unless there is something about time management in .NET and XNA, but i cant find anything indicating it.

But the server and client updates at different rates, and the further you get from Vector 0,0 the greater the difference becomes and close to 0,0 it works quite well. But at Vector2(-1387865f, -1158338f) the "Ship" is barley able to move. I believe this tells me the server "Clock" is running slower than the client (the ship moves slower on server than on client), but i dont understand why it would be more prominent further away from 0,0 (makes me think its the UpdateState() function I need to look at)

I dont know what to test next and I have no idea how to fix this behavior.

Please, i need ideas. Or even better, can you see something obvious wrong with the code i have?

Thank you.

**Update:** This are the results from some measurements, recommended from William 'MindWorX' Mariager. Im currently trying to throttle the server to get closer to the clients updates. And i think i need to look at some performance from the client as well (later), since it seems it runs slower than 60fps atm. Ill update with results.

**Server** updateCount 252092674

gameTime.TotalGameTime {00:09:59.9810854}

avgElapsed.TotalMilliseconds 0.0021000000000000003

(float)avgElapsed.TotalMilliseconds 0.0021

**Client** updateCount 24027

gameTime.TotalGameTime {00:09:55.5527941}

avgElapsed.TotalMilliseconds 24.03

(float)avgElapsed.TotalMilliseconds 24.03

# Answer
From what you said in the comment section, it appears it was an issue with the server ticking too fast and the imprecision of floats that caused the issue. It was solved by first checking and comparing the ticks of the client and server, and then subsequently slowing down the amount of server updates.
> 0 votes

# Answer
Since you use a completly synchronized approach to networking you need to use a constant delta for the physics calculations, else a similar outcome is not guaranteed.

Something like this:

```
float overflow=0.f;
// Update physics only in multiples of 120th seconds.
float timestep=1.f/120;

while([...gameloop...])
{
  timeReminder += timeDelta;
  while(overflow > timestep)
  {
    foreach (GameServerComponent component in this.Components)
      component.Update(timestep);
    timeReminder-=timestep;
  };
}

```

Note that the different float-implementations on the different CPUs might behave slightly different. So to get really 100% synchronization you'll need to either write your own float type (slow, but you have float precision) or to use fixed point numbers instead (fast, easy to implement)
> 0 votes

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


# Question
Title: The most popular pattern for game-related programming in C++
As the title says, what are the most popular design solutions when creating a new game or a new game engine?

# Answer
Patterns were designed to solve a certain problems within a/several domain(s). There are tons of design patterns for games. There is even the possibility that you might come up with your own! ( Well that depends on how much of problem solver you are ).

Allot of articles on creating games implicitly show you certain design patterns.

But ...hey google is your friend. Here

These are pretty much common
Prototype
Singleton
Flyweight
Command
Observer
State
Abstract Factory
Factory
Object Pool

But there are so many others that apply as well.

I think the reason you got a downvote is because it's too hard to give you an exact answer. It really depends on what your game specifics are.

edit:
Also I agree with lorancou. Don't try to hammer on design patterns. There are other solutions to any problem.
> 1 votes

---
Tags: c++, design-patterns, patterns
---


# Question
Title: What's the best open source physics engine to use with JOGL?
I have a past with jbullet but the existing jogl compatible sources and demos seems uncompleted. I have managed to implement it to an extent but still looking for a better documented engine with more demo applications.

My answer to this question is currently **JBullet** but wondering if there are any better and easier solutions.

Any ideas & suggestions?

# Answer
It's JBullet in my opinion, more noise about it means better documentation, more growth, etc. I'm using JBullet and I've had no issues.
> 1 votes

# Answer
If you only need 2D physics (Bullet is 3D) you can use the Java port of Box2D, which works very nicely, is well documented and is used throughout the world.

You can go for the stable 2.0 port, which is rather old now, or the in development 2.1 port, which I use and find to be working well.
> 1 votes

# Answer
Maybe this can help you http://www.dyn4j.org/.
> -1 votes

---
Tags: 3d, opengl, physics, java, physics-engine
---


title: rotate opengl mesh relative to camera

text:
# Question
Title: rotate opengl mesh relative to camera
I have a cube in opengl. It's position is determined by multiplying it's specific model matrix, the view matrix, and the projection matrix and then passing that to the shader as per this tutorial (http://www.opengl-tutorial.org/beginners-tutorials/tutorial-3-matrices/). I want to rotate it relative to the camera.

The only way I can think of getting the correct axis is by multiplying the inverse of the model matrix (because that's where all the previous rotations and tranforms are stored) times the view matrix times the axis of rotation (x or y).

I feel like there's got to be a better way to do this like use something other than model, view and projection matrices, or maybe I'm doing something wrong. That's what all the tutorials I've seen use.

PS I'm also trying to keep with opengl 4 core stuff.

edit: If quaternions would fix my problems, could someone point me to a good tutorial/example for switching from 4x4 matrices to quaternions. I'm a little daunted by the task.

# Answer
> 1 votes
I ended up just doing something like this

```
glm::mat4 cubeInv = glm::inverse(cubeMat);
glm::vec4 rX = cubeInv * ViewMat * glm::vec4(0.f, -1.f, 0.f, 1.f);
glm::vec4 rY = cubeInv * ViewMat * glm::vec4(-1.f, 0.f, 0.f, 1.f);
cubeMat = glm::rotate(cubeMat, (wWidth/2 - xpos) * delta, glm::vec3(rX.x, rX.y, rX.z));
cubeMat = glm::rotate(cubeMat, (wHeight/2 - ypos) * delta, glm::vec3(rY.x, rY.y, rY.z));

```

Nicol Bolas's answer ended up being more of a camera-relative translation, so that the cube was always oriented towards the camera, but moving the mouse meant moving the cube along a sphere around the camera. I was looking for more of a rotation around camera-relative axis, and my original assumption turned out to be correct. I hope this poorly drawn picture will explain the differences better. https://i.stack.imgur.com/uR2Kt.png Definately reading through those tutorials though.

---
Tags: opengl, mathematics
---


# Question
Title: What maps sizes did old 2D RTS games like C&C and WarCraft support?
I'm looking for the size (in tiles) of the maps for the old 2D games Command and Conquer and Warcraft 1 and 2.

# Answer
> 6 votes
It seems that Warcraft II has maps in the range 32x32 to 128x128. And given that the large maps generally feel pretty large I'd say that you don't actually need more than that. Usually going larger pretty much just means that you have to have stuff fill more on the map.

# Answer
> 3 votes
Command & Conquer - Tiberian Dawn supports up to 64 x 64. Tile size is 24px x 24px. Red Alert 1 - The Aftermath supports up to 128 x 128.

---
Tags: tilemap, rts
---


# Question
Title: How should I structure an extensible asset loading system?
For a hobby game engine in Java, I want to code a simple but flexible asset/resource manager. Assets are sounds, images, animation, models, textures, et cetera. After a few hours of browsing and some code experiments I'm still not sure how to design this thing.

Specifically, I'm looking for how I can design the manager in a way so that it abstracts away how specific asset types are loaded and where assets are being loaded from. I would like to be able to support both file system and RDBMS storage without the rest of the program needing to know about it. Similarly, I would like to add an animation description asset (FPS, frames to render, reference to the sprite image, et cetera) that's XML. I should be able to write a class for this with the functionality to find and read an XML file and create and return an `AnimationAsset` class with that information. I'm looking for a *data-driven* design.

I can find a lot of information on *what* an asset manager should do, but not on *how* to do it. The generics involved seem to result in some form of cascading of classes, or some form of helper classes. However I haven't seen a clear example that didn't look like a personal hack, or a point of consensus.

# Answer
> 25 votes
I would begin by not thinking about an asset manager. Thinking about your architecture in loosely-defined terms (like "manager") tends to let you mentally sweep many details under the rug, and consequently it becomes more difficult to settle on a solution.

Focus on your specific needs, which appears to be to do with creating a resource loading mechanism that abstracts the underlying origin storage and allows for extensibility of the supported type set. There's nothing really in your question concerning, for example, the caching of already-loaded resources -- which is fine, because in keeping with the single-responsibility principle you should probably build an asset cache as a separate entity and aggregate the two interfaces elsewhere, as appropriate.

To address your specific concern, you should design your loader so that it doesn't do the loading of any assets itself, but rather delegates that responsibility to interfaces tailored to loading specific types of asset. For example:

```
interface ITypeLoader {
  object Load (Stream assetStream);
}

```

You can create new classes that implement this interface, with each new class being tailored to loading a specific type of data from a stream. By using a stream, the type loader can be written against a common, storage-agnostic interface, and doesn't have to be hard coded to load from disk or a database; this would even allow you to load your assets from network streams (which can be very useful in implementing hot-reloading of assets when your game is running on a console and your editing tools on a network-connected PC).

Your main asset loader needs to be able to register and track these type-specific loaders:

```
class AssetLoader {
  public void RegisterType (string key, ITypeLoader loader) {
    loaders[key] = loader;
  }

  Dictionary<string, ITypeLoader> loaders = new Dictionary<string, ITypeLoader>();
}

```

The "key" used here can be whatever you like -- and it need not be a string, but those are easy to start with. The key will factor in to how you expect a user to identify a particular asset and will be used to look up the appropriate loader. Because you want to hide the fact that the implementation might be using a file system or a database, you can't have users referring to assets by a filesystem path or anything like that.

Users should refer to an asset with a bare minimum of information. In some cases, just a file name alone would be sufficient, but I've found that it's often desirable to use a type/name pair so everything is very explicit. Thus, a user might refer to a named instance of one of your animation XML files as `"AnimationXml","PlayerWalkCycle"`.

Here, `AnimationXml` would be the key under which you registered `AnimationXmlLoader`, which implements `IAssetLoader`. Obviously, `PlayerWalkCycle` identifies the specific asset. Given a type name and a resource name, your asset loader can query its persistent storage for the raw bytes of that asset. Since we're going for maximum generality here, you can implement this by passing the loader a means of storage access when you create it, allowing you to replace the storage medium with anything that can provide a stream later on:

```
interface IAssetStreamProvider {
  Stream GetStream (string type, string name);
}

class AssetLoader {
  public AssetLoader (IAssetStreamProvider streamProvider) {
    provider = streamProvider;
  }

  object LoadAsset (string type, string name) {
    var loader = loaders[type];
    var stream = provider.GetStream(type, name);

    return loader.Load(stream);
  }

  public void RegisterType (string type, ITypeLoader loader) {
    loaders[type] = loader;
  }

  IAssetStreamProvider provider;
  Dictionary<string, ITypeLoader> loaders = new Dictionary<string, ITypeLoader>();
}

```

A very simple stream provider would simply look in a specified asset root directory for a subdirectory named `type` and load the raw bytes of the file named `name` into a stream and return it.

In short, what you have here is a system where:

* There is a class that knows how to read raw bytes from some kind of backend storage (a disk, a database, a network stream, whatever).
* There are classes that know how to turn a raw byte stream into a specific kind of resource and return it.
* Your actual "asset loader" just has a collection of the above aboves and knows how to pipe the output of the stream provider into the type-specific loader and thus produce a concrete asset. By exposing ways to configure the stream provider and the type-specific loaders, you have a system that can be extended by clients (or yourself) without having to modify the actual asset loader code.

Some caveats and final notes:

* The above code is basically C#, but should translate to just about any language with minimal effort. To facilitate this I omitted a lot of things like error checking or properly using `IDisposable` and other idioms that may not apply directly in other languages. Those are left as homework for the reader.
* Similarly, I return the concrete asset as `object` above, but you can use generics or templates or whatever to produce a more-specific object type if you like (you should, it's nice to work with).
* As above, I don't deal with caching at all here. However, you can add caching easily and with the same kind of generality and configurability. Try it and see!
* There are lots and lots and lots of ways to do this, and there is certainly no one way or consensus, which is why you haven't been able to find one. I've tried to provide enough code to get the specific points across without turning this answer into a painfully long wall-of-code. It's already exceedingly long as it is. If you have clarifying questions, feel free to comment or to find me in the chat.

---
Tags: architecture, asset-management, resource-management, data-driven
---


# Question
Title: How do I perform collision tests between two 3D oriented bounding boxes?
I want to test two 3D oriented bounding box objects against each other and stop them if there is a hit detected.

How can I accomplish this using only the collision detection functions in the Bullet physics API?

# Answer
> 0 votes
Bullet comes with many demos, some of them just show or uses exactly what you want to achieve.

I suggest to have a look at the Bullet demos.

The demos folder should be right in the root of the Bullet source code.

You can browse the code online here https://code.google.com/p/bullet/source/browse/#svn%2Ftrunk

---
Tags: 3d, collision-detection, bullet-physics
---


# Question
Title: How can I simulate light using mask images on the iPad?
> **Possible Duplicate:**
> Can I achieve a torchlight effect (lighter area around a light source) in a 2D game?

I want to have a picture as a background, say this:

Then I would like to apply a mask, just a circle with blurred edges, so it looks like this:

The idea is to simulate something emitting. Is this a good way of simulating light or should I use another method? And if so how? And I'm not really sure how to apply this method.

# Answer
> 0 votes
You could use the Core Image `CISpotLight` filter:

```
CIImage *inputImage = // your image here
CIFilter *spotlight = [CIFilter filterWithName:@"CISpotLight"];
[spotlight setDefaults];
[spotlight setValue:inputImage forKey:@"inputImage"];
CIImage *spotlightImage = [spotlight valueForKey:@"outputImage"];

```

See the Core Image Programming Guide for more information.

---
Tags: rendering, objective-c, lighting, image-effects
---


# Question
Title: Something like libgdx for C++ / cross-platform (with mobile) SDK
Is there an SDK like libgdx which allows me to code in C++? I really like the features libgdx has, but would prefer to code in C++. I've looked around but can't find anything. I found the commerical Maramlade project, but that doesn't support Linux at all, plus I'd prefer an open solution.

# Answer
I'll answer myself since I found something called GamePlay. It appears to support the most platforms of any SDK I've seen so far and is all in C++. It doesn't quite have its Linux support yet working but it appears to be a priorty issue.
> 2 votes

# Answer
Guess you're looking for something more complete, but gdx++ is the ongoing port of libGDX, though it still lacks some essential features - quoting from the README:

* Backend polishing. Seriously, it's working, but there is a lot of stuff that is ugly and in a haste.
* iOS support
* GLES 2. Check if it's working
* etc *(whatever that entails)*

Porting efforts seem a little slow-paced at the moment though.
> 1 votes

# Answer
Cocos2d-x is a cross-platform and open source framework. It allows to do everything which allows libgdx.
> 1 votes

# Answer
Someone over on badlogic forums was porting libgdx over to c++ a while back but I can't seem to find it now. Maybe you can politely ask over there? It may have been scrapped because the main branch will eventually support ios.
> 0 votes

---
Tags: c++, libgdx
---